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?
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)
.
It's called bracket notation. In JavaScript you can use it to access object properties.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With