there is such javascript code:
function a() {
a = 3;
return a;
}
console.log(a());
console.log(a());
After execution it prints out: 3, Type error. Could anybody explain why, please
You have a scope issue
Because you didn't use "var" you are overriding the global "a" variable (used to be your function) with a number (3).
When you try to execute it a second time, it's no longer a function but a number, which throws the type error.
function a() {
a = 3; // you just over-wrote a()
return a;
}
console.log(a()); // 3, but now "a" === number, not function
console.log(a()); // ERROR, you treated "a" as a function, but it's a number
what you want
function a() {
var a = 3; // using var makes "a" local, and does not override your global a()
return a;
}
console.log(a()); // 3
console.log(a()); // 3
Using var is recommended almost always inside a function, otherwise you're polluting, or worse overriding, global variables. In JS, var enforces your variable into the local scope (your function).
Note that using var in the global scope still creates a global variable
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