Brackets in ES6 JavaScript

  • A+

I'm desperate for someone to give me just some concise information about when I should use which brackets where and why in JS ES6. I know the basics but when we start talking about arrow syntax I just lose it and then can't see why we're wrapping braces in brackets etc... I feel like in order to truly understand why we lay things out the way we do I need to first understand what all of the use cases are for both {} and ().

For example. I'm really struggling to work out syntax like this:

const func = (obj) => { console.log(obj.a) }  func({a: "blue"})  

It's the func({a: "blue"}) part I'm struggling with here.

Here's another example:

makeSound({     a: "bark",     b: 2,     c: "hiss" })  function makeSound(options) console.log("the" + options.a + "was a " + options.c) 

I don't know what to make of this. What are we doing at the top with makeSound? I can see we're making an object but then why aren't we just declaring it as a variable with standard let makeSound = {}. What are we actually doing here? Is makeSound nothing untill we make it into a function further down the code?


I understand your confusion as there are quite a lot of curly braces indeed!

First, objects. You define an object using brackets like this.

const obj = { a: 1 }; 

But you can also define an object inline, directly in a function argument list, using an object literal like this:

myFunc({ a: 1 }); // same as myFunc(obj); 

Then you have arrow functions.

Their bodies is defined using curly braces too, just as regular functions, in which case you have to use the return keyword if you want to return a value from your function:

const myFunc = (arg) => { return 'hello ' + arg; } 

However, arrow function also support implicit return, if you omit the curly braces, the return value will be implicit:

const myFunc = (arg) => 'hello ' + arg; 

Now, you can also use the curly braces for desctructuring assignment. For example:

const { a } = { a: 1 }; 

Here the desctructuring happens to the left of = and it allows you to extract properties from objects and assign them to variables.

You can also use object destructuring in function arguments, to access specific properties, like so:

const myFunc = ({ name }) => 'Hello ' + name; 

This is equivalent to:

const myFunc = (person) => 'Hello ' +; 

And you could call this function with an object literal like this:

myFunc({ name: 'Jo' }); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: