Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Function call on adjacent object?

You will have to forgive me, as I am sure this is addressed elsewhere, but I have no idea what to call this bit of syntax or the concept that this example illustrates. How does this get() function know that the parameter I am passing into it refers to an index of the adjacent array? I am not giving get() any indication of what object I am referring to, unless putting an object in parenthesis directly next to it has this effect. Is this correct? Is there a broader concept here that I am unaware of involving proximity and function calls?

function get(prop) {
  return function(obj) {
    return obj[prop]
  }
}
get(1)([1,2,3]);

// output = 2
like image 471
swoopedj Avatar asked Feb 18 '26 17:02

swoopedj


2 Answers

It might make more sense if you split get(1)([1,2,3]) out into 2 lines like this:

var get1Function = get(1);
get1Function([1,2,3]) 
// output = 2

Note: after execution of this line

var get1Function = get(1);

get1Function is now set to function(obj) { return obj[1] }

like image 148
sheilak Avatar answered Feb 21 '26 07:02

sheilak


There's no magic here. You have a function that returns a function. When you call get(2), the returned function has 2 for the value of prop. Your code is essentially equivalent to this:

var fn = get(2);
// fn = function(obj) {
//        return obj[2]
//      }

fn([1,2,3]);
// => 3
like image 23
Jordan Running Avatar answered Feb 21 '26 05:02

Jordan Running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!