Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable name is like function name -- when causes error/when doesn't

Tags:

javascript

This question is about the same names of function and variable. Please tell me - why this code doesn't have errors:

    var Task = new Task();
     
    function Task() {
        console.log('work!');
    }

but this one won't work:

start();
 
function start() {
  var Task = new Task();
};
 
function Task() {
    console.log('work!');
}
 

Why it's so?

like image 268
qwe Avatar asked Aug 25 '16 14:08

qwe


People also ask

Why can't I name a function?

What went wrong? There is a function statement in the code that requires a name. You'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an IIFE, or if the function code is placed correctly in this context at all.

What are the most common causes of variable name errors?

One of the most common causes is misspelling the function or variable name. Especially with longer names or names containing similar characters (such as the letter l and numeral one), it is easy to make mistakes and hard to detect them.

What does the error name mean in a formula?

Important: The #NAME? error signifies that something needs to be corrected in the syntax, so when you see the error in your formula, resolve it. Do not use any error-handling functions such as IFERROR to mask the error.

What does Sy syntax error require a name mean?

SyntaxError: function statement requires a name The JavaScript exception "function statement requires a name" occurs when there is a function statement in the code that requires a name.


1 Answers

Through name hoisting, your first code essentially works like this:

var Task;  // (undefined)

Task = function () {
    console.log('work!');
};

Task = new Task();

Your second one like this:

var start, Task;

start = function () {
  var Task; // (undefined)
  Task = new Task();
};

Task = function () {
    console.log('work!');
};

start();

As you can see, Task is being overridden by undefined inside the start function. This does not happen when the function and variable definition are both in the same scope, since then var and function are essentially the same thing.

If you leave out the var inside start, it works as well.

like image 178
deceze Avatar answered Nov 15 '22 00:11

deceze