user3810193
user3810193

Reputation: 53

When can assign a function to a var?

Why can't I assign a non-nested function to a variable counter? Why does the second function generates error?

The first one:

function makeCounter() {
  return function() {
    return "hello";
  };
};
let counter = makeCounter();
console.log( counter() ); 

The second:

function makeCounter(){
  return "hello";
};
let counter = makeCounter();
console.log( counter() ); 

Upvotes: 1

Views: 58

Answers (3)

Linh Nguyen
Linh Nguyen

Reputation: 941

When you defining

function makeCounter(){
  return "hello";
};
let counter = makeCounter();
console.log( counter() ); ` 

You are defining a function to return a string, not a function.

And at the first function, you are defining a function to return a function, that why you can call it with as a function- you can use () here

function makeCounter() {
  return function() {
    return "hello";
 };
};

Upvotes: 0

Ronak07
Ronak07

Reputation: 894

Assign the function as reference then it will work fine.

function makeCounter(){
  return "hello";
};
let counter = makeCounter;
console.log( counter() ); 

Upvotes: 1

Clarity
Clarity

Reputation: 10873

You're not assigning the function but a result of its return in the second case, which is a string hello, change your code to this to work:

function makeCounter(){
  return "hello";
};
let counter = makeCounter; // Assign function reference
console.log( counter() ); 

Upvotes: 1

Related Questions