1

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?

1
  • 1
    A LISP programmer has created the examples? Commented Aug 30, 2017 at 10:05

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.