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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With