Javascript - confused about });

Javascript - confused about });
0

#1

I seem to be getting in a muddle with when to use }); in javascript.

I keep getting errors and just adding more }'s to try and clear them.

I know they enclose functions and if/else arguments etc. Why am I finding this so much of a problem - is there a simple guide i’m missing??

Thanks


#2

They need to match … an opening { with a closing }. Same with ( and ).

That’s it really.

You most commonly see }) when closing a callback function inside a call to another function like:

const some_array = [];

some_array.forEach(function( elem, e ){
// DO STUFF WITH ELEMENT
});

There you hare calling the forEach method on the array, which takes as an argument a function … but your defining your function right in place, so you see a function(){} block because a standard javascript function needs the braces.

Really, it’s …

some_array.forEach( callback );

And the forEach method executes the callback for each element in the array.

You could easily define the callback first and pass it to the forEach method.


function callback( elem, e ){
// DO SOMETHING WITH ELEM
}

some_array.forEach( callback );

If that made things clearer to read.

Curly braces are used to surround blocks of code … statements in a function, a while block, an if block, statements in a for … loop, etc.

MDN Reference on code blocks.

They are also used for the creation of objects, called an object literal. So you might see …

const some_obj = {
   'property_name': property_value
};

MDN Reference on Object creation.

Most code editors I know of offer opening/closing bracket highlights to help you spot the beginning and end of a bracket and that can be helpful in highlighting mismatches (where you’ve opened a block, but not closed it).

Regards,
Micheal


#3

Yes, you need to close everything. :slight_smile:

If you don’t use a code editor / IDE, or your code editor doesn’t close your parentheses, braces and brackets, you can do a simple trick to not to forget it. When you write an opening bracket, immediately close it and just get back using your arrow key.


#4

That’s exactly what I forgot to add … :slight_smile:

I always write out the boilerplate first … that way I don’t forget.

Good tip!


#5

if you’re using codepen, and you have your cursor on a bracket, you’ll notice that it gives the bracket a little underline. The “matching” bracket will also be underlined. You may find that the matching bracket is not the one you thought it was.


#6

Thanks everyone. I was over-complicating things I think.