Function problem


#1

here while creating a function it is saying that to use () => , this format . I just want to ask that does it is better than using function keyword followed by a function name as we have learnt in other programming languages. Does this type of declaration of function has any advantages ??


#2

Functions, no matter how defined are all the same in terms of identifier, parameter, code body and return value.

function foo(bar) {
    return "foo" + bar;
}

var foo = function (bar) {
    return "foo" + bar;
};

const foo = bar => `foo" + bar;

All of the above do the exact same thing.


One concept that sets the first one apart from the other two is hoisting. This deserves further study but I’ll leave it for you to follow up.

Declared functions (the first one) are hoisted, whereas expressions are not, only their identifier is hoisted. The function expression (anonymous function) isn’t parsed until the second pass at load time (JS takes two passes to parse).

Anonymous functions have no identifier.

function () {}

() => {}

Both are the same.

Arrow functions differ in a number of ways over and above the similarities.

  1. They do not have a this context variable.
  2. They do not have an arguments object.
  3. Some of the syntax is optional (given special case).

The optional syntax is,

  1. Parens on the parameter not needed when only one argument.
  2. Curly braces only needed when there is more than one line of code.
  3. return is implicit when there is only one line of code.

Eg.

const foo = bar => `foo${bar}`;

ES6 gives us another fantastic interpolation tool… Template literals. We can now write strings and variables in a single set of backticks.

As for advantages of one form over another, it really depends on the code design as a whole, and using shorter, more concise code when it makes sense to do so. The shortcuts offered in arrow syntax are invaluable in a program that is largely functional. The general premise is that functions should be pure and not interact with the outside. Something in, something out, and always predictable.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.