Javascript function

there is such javascript code:

function a() { a = 3; return a; } console.log(a()); console.log(a()); 

After execution, it produces: 3, Type error. Can anyone explain why please

+6
source share
2 answers

You have a problem with the scope

Since you did not use "var", you are redefining the global variable "a" (used as your function) with the number (3).

When you try to execute it a second time, this is no longer a function, but a number that causes a 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 a number 

, What would you like

 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 almost always recommended inside a function; otherwise, you pollute or worse redefine global variables. In JS, var forces your variable into the local scope (your function).

Note that using var in a global scope still creates a global variable

+12
source

If you tried to set a as a variable, then var needed in front. Since you did not do this, it appears in the global area in which it is part of the window object, and you can access it using window.a . So, the best thing to do is change the first line of the body of your function to say: var a = 3 .

0
source

All Articles