Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function

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

like image 687
OLe TKACH Avatar asked Jan 30 '16 15:01

OLe TKACH


1 Answers

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

like image 150
Sebastien Daniel Avatar answered Oct 20 '22 21:10

Sebastien Daniel