5

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

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

I absolutely recommend this book from the You Don't Know Js Series
Good link! @LionelDamiánT is right. I've been speaking about "scope" without actually mentioning it. The fundamental issue in OP is scope related. Made that a little clearer in answer.
0

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.

1 Comment

thanks guys for your explanation it was a test question in an online example of questions asked in one company

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.