2

Please check the code in http://jsfiddle.net/4a42n8g8/. it alerts "undefined". Why? I have 2 questions in particular.

var a = 10;

function x() {
a = 20;
alert(this.a);
}

x();

1) Isn't the variable "a" within function x a global variable since it does not have a var prefix? Or is it that with or without var prefix, any variable within a function is not a global variable?

2) Since var a = 10 is defined outside the function, doesn't it make it a global variable? Or is it that all global variables SHOULD NOT have a var prefix?

2
  • 1
    try the same code in chrome console and you will get correct answer! Commented Dec 24, 2014 at 13:58
  • for opening chrome console press F12 while chrome is open and then press console in option Commented Dec 24, 2014 at 13:59

1 Answer 1

2

The reason is that jsfiddle is running your code within a function like the following:

window.onload=function(){
var a = 10;

function x() {
    a = 20;
    alert(this.a);
}

x();
}

Therefore, your var a is local to the onload function, but this inside of x points to the global window object

If you change your fiddle settings to No wrap - in <head> (or in <body>), it will work as you expect. http://jsfiddle.net/mendesjuan/4a42n8g8/1/

Question 1

var a is not a global because it's within a function, if it was outside of any functions, it would be global.

Question 2

Same as question one, var a actually is defined in a function.

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

12 Comments

So, If the above question was asked in an interview, we would answer it with virtual No wrap, right?
Sp If you can answer and confirm my 2 questions, thanks!
I am not sure what you mean with your interview question. virtual no wrap doesn't make any sense in this context.
I meant, if the above question was asked in an interview(just the snippet), then we should be answering the question keeping in mind that there is no "window.onload...." right?
Or correct me if you think otherwise - 1) any variable outside or within a function, if does not have a var prefix is a global variable.
|

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.