JessiAbrams JessiAbrams - 1 month ago 9
Javascript Question

Javascript fn has 2 arguments when called but only 1 parameter when declared?

I don't understand why this works:

function doSomething(a) {
b = a + doSomethingElse( a * 2 );

console.log( b * 3 );
}

function doSomethingElse(a) {
return a - 1;
}

var b;

doSomething( 2 ); // 15


How is it that the doSomethingElse inside the doSomething fn can be passing (a * 2) as arguments //line 2// since when doSomethingElse was declared it only takes one parameter?
What the heck is going on here? Can someone explain the order in which this whole thing runs?

Thank you!

Answer

a * 2 is only one argument. It's whatever the value of a is, multiplied by 2.

It would be the same as doing this:

function doSomething(a) {
    var c = a * 2;
    b = a + doSomethingElse( c );

    console.log( b * 3 );
}

Arguments are separated (in ES5) by a comma. However, you can pass expressions as a single argument, since they result in one value.