Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unfamiliar use of square brackets in calling a function

Tags:

javascript

In the middle of this page, I find the code below.

var plus = function(x,y){ return x + y };
var minus = function(x,y){ return x - y };

var operations = {
  '+': plus,
  '-': minus
};

var calculate = function(x, y, operation){
    return operations[operation](x, y);
}

calculate(38, 4, '+');
calculate(47, 3, '-');

Now while I can trace how it works, I've never seen this use of square brackets before. It certainly doesn't look like it's creating an array or referencing a member of an array. Is this common? If so, where are some other examples?

like image 639
dwilbank Avatar asked Sep 05 '13 15:09

dwilbank


3 Answers

It is a dictionary access, which is like an array, but with a key instead of a numeric index.

operations['+'] will evaluate to the function plus, which is then called with the arguments plus(x,y).

like image 94
Hans Then Avatar answered Nov 09 '22 22:11

Hans Then


It's called bracket notation. In JavaScript you can use it to access object properties.

like image 31
Sergiu Paraschiv Avatar answered Nov 10 '22 00:11

Sergiu Paraschiv


here operations is an object where the symbols + and - refers to two functions.

operations[operation] will return a reference to function plus where value of operation is + and then the following () will invoke the function

like image 38
Arun P Johny Avatar answered Nov 10 '22 00:11

Arun P Johny