HeavensGate666
HeavensGate666

Reputation: 75

Should returning an anonymous function end with a semicolon?

MDN uses the second code I have provided and it runs fine but throws an error at the end. Why did they end the anonymous function with a semicolon? Is it ok to have an anonymous function if its not going to be in a function expression? Functions aren't supposed to end in semicolons if they aren't function expressions.

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

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

versus

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

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

Upvotes: 2

Views: 207

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370619

it runs fine but throws an error at the end

Sounds like a linting error, not a Javascript error - the difference is important to keep in mind. Linting is mostly a style guide, rather than a logic guide.

In

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

The function there is being returned, not declared - that means it's a function expression, not a function declaration, and so the end of the return expression should have a ;.

Anonymous functions are always function expressions; function declarations require a name, eg:

function someFnName() {
}

Upvotes: 6

Related Questions