VitWorks
VitWorks

Reputation: 103

Run a function inside a console.log?

I'm reading someone's javascript code and I have a hard time understanding what they are trying to do here.

var add3 = add(3);
var add4 = add(4);

console.log(add3(4));

Can someone explain what is going on inside the console.log() here?

Is console.log just taking the add3 value and automatically adds it to a integer 4?

Thanks

Upvotes: 3

Views: 6055

Answers (2)

Chad Hedgcock
Chad Hedgcock

Reputation: 11755

window.console is how your browser gives feedback on the document it has downloaded and parsed. You can usually see it by pressing F12 and then clicking the "console" tab. It's a good substitute for alert, but you can also write JavaScript directly into it and then click "Run" (or press enter if it's a one-line command box). That's much easier than writing it to a file, saving it, refreshing, and seeing what happens.

Not knowing anything about your add function, it looks like it's meant to show an example of currying. So instead of saying:

function add(x, y){
   return x + y;
}

You write:

function add(x){
    return function(y){
        return x + y;
    }
}

Then you can do:

var add3 = add(3); //returns a function that will add 3 to anything
console.log(add3(4)); //returns 7.
console.log(add(3)(4)); //also returns 7.

This seems like a silly way to do it, but it's a way to generate functions on the fly. If I did add(3) to the first example, it would break and say "y is undefined" in the console. Using the curried example, var add3 = add(3) is like saying "well, I don't know what I want to add three to yet, so add3 will just be another function that will add 3 to anything."

Upvotes: 1

Igor Chubin
Igor Chubin

Reputation: 64563

console.log outputs its argument to the console. Its arument (add3(4)) is a function call, that calls the function add3 with the argument 4.

add3 is a function that is generated by add.

The function add looks lke this (probably):

function add(n) {
   return function(x) {
      return n + x;
   }
}

Upvotes: 1

Related Questions