OLe TKACH
OLe TKACH

Reputation: 141

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

Upvotes: 5

Views: 106

Answers (2)

Obinna Nwakwue
Obinna Nwakwue

Reputation: 209

If you were trying to set a as a variable, then var is needed in front. Because you didn't do so, it is exposed to the global scope, in which it is part of the window object, and you can access it with window.a. So, the best thing to do is to change the first body line of your function to say: var a = 3.

Upvotes: 0

Sebastien Daniel
Sebastien Daniel

Reputation: 4778

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

Upvotes: 11

Related Questions