4 JavaScript trivia questions that may help you understand the language a bit better

The next 4 Javascript questions may seem easy to some of you, but I am sure that more than a few will get confused.
I believe that these 4 simple questions will help you understand a key feature of the language.

Question: What will happen after executing the next JS code?

function outer(){
	var x=1;
	var inner = function(){
		alert(">"+x);
	}

	x=2;
	return inner;
}

outer();

1. Nothing
2. alert ‘>undefined’
3. alert ‘>1’
4. alert ‘>2’

Answer:
Nothing, because outer() returned a function but it wasn’t executed.

Question: What will happen after executing the next JS code?

function outer(){
	var x=1;
	var inner = function(){
		alert(">"+x);
	}
	x=2;
	return inner;
}

outer()();

1. Nothing
2. alert ‘>undefined’
3. alert ‘>1’
4. alert ‘>2’

Answer:
alert ‘>2’, because the x that inner() uses is the same x the outer() uses.

Question: What will happen after executing the next JS code?

function outer(){
	var x=1;
	var inner = function(x){
		alert(">"+x);
	}
	x=2;
	return inner;
}

outer()();

1. Nothing
2. alert ‘>undefined’
3. alert ‘>1’
4. alert ‘>2’

Answer:
alert ‘>undefined’. Inner uses a variable x which is different than the outer x. The inner x is never initialized

Question: What will happen after executing the next JS code?

function outer(){
	var x=1;
	var inner = function(x){
		alert(">"+x);
	}
	x=2;
	return inner;
}

outer()(3);

By now the answer should be obvious: alert ‘>3’ .

One Reply to “4 JavaScript trivia questions that may help you understand the language a bit better”

Leave a Reply

Your email address will not be published.