J. Jackson
J. Jackson

Reputation: 3764

What do the square brackets after ES6 function do?

Recently I was looking for a way to rewrite an ugly switch/case statement and came across this Medium article.

I rewrote my switch/case into an es6 function like this:

const url = category => ({
          'itemA': itemAService.getItemCategories(payload),
          'itemB': itemBService.getItemCategories(payload),
        })[category]

When I call this function with something like const response = url(category); it works, which is great! But then I got to wondering what exactly the [category] means at the end of the function. I thought maybe it was an Immediately Invoked Function, but that didn't seem right either.

The article mentions that it's an object literal, but when I went to the MDN docs I couldn't find anything that explained what this is or what it does, or even any examples that showcase this same thing.

So what does it do?

Upvotes: 1

Views: 1537

Answers (3)

Charlie
Charlie

Reputation: 23798

What confuses you here are the braces.

Imagine that you have an object expression and you use a property assessor on the variable which points to the object.

obj = {foo: 1, bar: 2}
return obj["foo"];    //returns 1

Now, how would you call a property assessor on an object literal? You need braces around them to complete the shorthand syntax.

return {foo: 1, bar: 2}["foo"];    // WRONG Syntax
return ({foo: 1, bar: 2})["foo"];  // CORRECT syntax 

So, your function can be rewritten using the following traditional syntax.

function getUrl(category) {

   return ({
          'itemA': itemAService.getItemCategories(payload),
          'itemB': itemBService.getItemCategories(payload),
        })[category]

}

Upvotes: 1

Barmar
Barmar

Reputation: 781038

That shorthand is roughly equivalent to the following traditional function syntax:

function url(category) {
    var obj = {
      'itemA': itemAService.getItemCategories(payload),
      'itemB': itemBService.getItemCategories(payload),
    };
    return obj[category];
}

It's easier to see what's happening when you create a named variable for the object.

The parentheses are needed around the object in the arrow function because if an arrow function begins with { it's treated as a body containing statements, rather than a value to return.

They could have put [category] immediately after the object literal, rather than after the close parenthesis, that might have been clearer.

Upvotes: 4

Jonas Wilms
Jonas Wilms

Reputation: 138267

It's not "after" the function, it is in the functions body. It could also be written as:

  const url  = category => {
    const obj = {
      'itemA': itemAService.getItemCategories(payload),
      'itemB': itemBService.getItemCategories(payload),
    };

    return obj[category];
 };

So this is basically just a dynamic property lookup in the object.

Upvotes: 3

Related Questions