I defined the following function in a chrome developer console-
let splitNumber=function(num){
let arr=[];
arr=num.toString().split("");
return arr};
Then I tried to delete this function from the console scope using this command -
delete window.splitNumber
> true
Now if I try to use the same variable 'splitNumber' again in the console, I get this error -
Uncaught SyntaxError: Identifier 'splitNumber' has already been declared
Can someone please help me understand what I am doing wrong here? Please let me know if the question is not clear.
let
cannot be deleted var
, let
, and const
create non-configurable properties which cannot be deleted with the delete
operator. Since you declared the function with let
, it cannot be deleted.
Any property declared with
let
orconst
cannot be deleted from the scope within which they were defined.
delete
statement return true? Generally, when a property is non-configurable and cannot be removed, delete
will return false. So you may be wondering why your delete
statement returns true.
Well, delete
returns true if the property does not exist after deletion. This means it will return true either if the delete was successful or if the property never existed in the first place. Unlike var
, let
does not create a property on the global object. So delete window.splitNumber
returns true because splitNumber
does not exist as a property of the global window
object.
If you try delete splitNumber
, it will return false
indicating that splitNumber
exists in the global scope and cannot be deleted.
When you declare a variable using let
or const
it wont be added to window
object.
Your attempt to delete splitNumber
on window
object as no effect as it won't exists on window
.
And the splitNumber
still exits and it throws error when you try to redefine it.
Redeclaring the same variable within the same function or block scope raises a SyntaxError.
if (x) {
let foo;
let foo; // SyntaxError thrown.
}
In ECMAScript 2015, let bindings are not subject to Variable Hoisting , which means that let declarations do not move to the top of the current execution context. Referencing the variable in the block before the initialization results in a ReferenceError (contrary to a variable declared with var, which will just have the undefined value). The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.
Read the docs for more.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.