user3335796
user3335796

Reputation: 1237

Javascript functions with different parameter passing

Recently i came through a fine example of javascript function. Please find in below code.

function add(a,b){
  return (a+b);
} 
console.log("Summation is===>",add(1,2));    
console.log("Summation is===>",add((1),(2)));

Both prints output has a 3. What is the difference between two function arguments? How second function arguments is different from first?

Upvotes: 1

Views: 53

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075337

What is the difference between two function arguments?

There is none whatsoever. With only a very few exceptions*, putting the grouping operator (()) around an already-isolated expression has no effect at all. The 1 and 2 in add(1,2) are already isolated.


* Some (all? heh, probably not) of the very few exceptions:

  1. If you want to put the single expression in a return on a separate line from the return, e.g.:

    return            // WRONG
        expression;
    

    you have to put () around it like this:

    return (
        expression
    );
    

    to prevent the horror that is automatic semicolon insertion from adding a ; after return where the line break is, creating a very subtle bug (since an expression on its own after return; is not an error, though a lint tool would hopefully help you catch it).

  2. If you're using a concise body on an arrow function to return the result of an object initializer:

    () => {foo: "bar"} // WRONG
    

    you have to wrap the object initializer in () to avoid the { of the initializer being taken as the beginning of a function body, like this:

    () => ({foo: "bar"})
    
  3. If you want to start a function expression where a statement is expected, you have to put something in front of the function keyword, since otherwise it will start a function declaration rather than function expression. It can be any of several things that tell the parser to switch from expecting a statement to expecting an expression, but () is a common choice, particularly for an IIFE:

    (function() { /*...*/})();
    

Side note: The grouping operator you're using in return (a+b); has no effect, as it's an isolated expression and you're not dealing with #1 above.

Upvotes: 3

Related Questions