JavaScript Questions






4.57/5 (30 votes)
Discussing a few JavaScript fundamental topics to make our understanding more in JavaScript.
Introduction
In this article, we will discuss a few JavaScript concepts by solving answering questions. I hope this will help us understand JavaScript more in depth.
Background
Before we proceed, I want to discuss the Closure and Hoisting principles of JavaScript.
Closure is the local variables for a function - kept alive after the function has returned or we can say Closure is a stack-frame which is not deallocated when the function returns.
Hoisting is the mechanism In JavaScript where variables are moved to the top of the script and then run. This is because, JavaScript doesn't have lexical scoping.
JavaScript questions and their simple answers
Let's begin learning with questions and answers.
First question
What would be the value of
and x
,
yz
after the execution of the below three lines of script?
var x=5,y=6,z;
x=y++; //what will be x and y ?
z=++y; //what will be z and y ?
Let's take first x=y++
. In the above line of code the actual execution will happen in the two steps explained
below:x=y; //x=6 //y will be assigned to x first before it gets incremented.
y=y+1; //y=7
Therefore the value of x
will be 6
and the value of y
will be 7
Let's take the 2nd line
z=++y
. In the single line, the actual execution will happen in 2 steps like below:
y=y+1 //y=7+1=8 y will be incremented first before it will be assigned to z.
z=y //z=8
Therefore the value of z
will be 8 and the value of y
will be 8.
JavaScript Hoisting Question 1
Let's see first question on hoisting.
var x = 5;
function c() {
if (typeof(x) === 'undefined') {
var x = 10;
alert(x);
}
alert(x);//what would be the result ?
}
c();
alert(x);//what will be the value of x ?
What would be the result of above script ? Select any one option:
- Alert 2 times with values: 5 and 5
- Alert 2 times with values: 10 and 10
- Alert 3 times with values: 10, 10 and 10
- Alert 3 times with values: 10,10 and 5
The answer is 4
Surprised! :O Let's discuss this:
In JavaScript, variables do have Global and functional scope. In above script, variable x
is already
defined and assigned with the value of 5. This x
has its scope globally
and is available everywhere. However, in the function, we have again declared the
same variable one more time inside the if condition. Therefore, when script gets loaded, function gets
parsed and the variable x
get hoisted to the top inside the function and
creates new functional scope.
It is something like, someone has declare the variable
x
in the first line of the function before the if condition statement.
see below:
var x=5;//x is already defined and assigned with value 5 and is available in Global scope.
function c( ) {
var x; // variable x get hoisted to the top.
if (typeof(x) === 'undefined') {//therefore, here it will be undefined.
x = 10;//assigning value 10
alert(x); //x will be 10
}
alert(x);// x will be 10 , value of x will be 10 inside the function scope.
}
alert(x); // here the value of x will be still 5. Since it has its own value available in the global scope.
Therefore, when we call function c
then x
gets declared
one more time as undefined
inside scope of the function. The if condition which
checks if x
is undefined
becomes true
and x
will be further assigned by the value 10 and inside the function
scope the value of x
becomes 10. However the value of the x
outside the function scope will be still 5.
Therefore, it's considered best practice to have all variables declared at the top of the area they will be used to prevent hoisting causing a problem. JSLint is good tool which will suggest you to do this, if test your code in JSLint.
JavaScript Hoisting Question 2
What would be the result of below script ?
declareMe();//calling function
fnExpression();//calling function
//Creating a function by declaration.
function declareMe(){
alert("this is function declaration");
}
//creating a function by expression.
var fnExpression = function(){
alert("this is function expression");
}
Answer: This script will throw exception at the fnExpression()
invoke call saying "Object Expected"
This is because, in JavaScript all the function declarations get hoisted at the
top of the script. However, function expressions are not get hoisted till they evaluated.
Therefore, declareMe
function will be available even before its declaration
gets evaluated. Hence the call declareMe()
will be evaluated without
any exception. However, the fnExpression()
call will throw exception
saying that "Object Expected"
. Because, fnExpression
is a function expression and as per hoisting principle the function will not be hoisted at the top of the script unless function expression gets evaluated.
Let me explain it in Execution Context point of view also
In ECMAScript functions are objects and each line of JavaScript code executes in separate Execution Context.
There are 3 Execution contexts for above lines of code.
- First is Global Execution Context during this all variable instantiations happens and assigned to Global Object.
- 2nd is "
declareMe
" function invoke Execution Context. - 3rd is "
fnExpression
" function invoke Execution Context.
During the Global Execution Context:
Variable instantiations takes place and Function objects are created for all Function Declarations and got assigned to Global Object. Hence, the function object (for declareMe
function) that is created is referred to by the property of the Global Object with the name "declareMe
".
However, function objects are not created for function expressions during the variable instantiation of the Global Execution Context. Hence, the Global Object will have property named as "fnExpression
" with having no function object assigned.
In the next Execution context that is the function call to declareMe
function (
) will get evaluated successfully because, global object already had the property named as declareMe
();declareMe
referring to the corresponding function object which get invoked.
And in the last Execution context that is the function call to fnExpression
function ( fnExpression();
) will result "Object Expected"
error because, global object had the property named as fnExpression
which had never assigned with corresponding function object.
Question on Closure
Write a function named as newAdd
such that it will
add 2 numbers by invoking in below way:
newAdd(2)(5);
Lets write this function using closure principle.
function newAdd(num1) {
return function (num2) {//num1 variable will be still alive after returning this anonymous function.
return num1+num2;
}
}
The above function declaration creates a num1
variable in the newAdd
function scope. The num1
variable will be available to the inner
anonymous function because of the closure. Hence when we first call newAdd
with value 2 then it stores the value 2 in num1
and returns
a anonymous function which takes one more variable, adds it with the num1
value and returns the final result. In the second time call by passing 5 the anonymous
function gets invoked, sets num2
is equal to 2, does the sum of num1
and num2
makes it 5+2 and returns the final result as 7.
Last Question
This question is last but still it has significant importance.
What would be the result of below scriptvar x=5;
alert(x == "5") //what would be the result here ?
alert(x === "5") //what would be the result here ?
Answer: First alert will say true
, and second will say false
The ==
equality operator only compares the value, it never compares the data type.
Therefore, the first comparison results true. The ===
equality operator compares
both value and data type hence the 2nd comparison statement results false. Therefore,
if we want to compare the value along with the type then we should use ===
operator.
var a= 0; if(a=='') { console.log("a=='' is true"); } else { console.log("a is 0"); } if(a === '') { console.log("a==='' is true"); } //What will be the output here
The answer is "a=='' is true"
. So suppose if a = 0
then you wanted to print a is 0
. However it will not go to the else condition rather it will go in if condition only because, "=="
operator does type coercing. Therefore, if you want to compare the value as well as the data Type then always use "===".
References
- http://javascript.crockford.com/
- http://jslint.com/
- http://www.jibbering.com/faq/notes/closures/
- http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
- http://javascript.crockford.com/style2.html
I tried to write as per my understanding, let me know if you have some comments, I will try to respond them and if you see some correction to my examples then I will correct them ASAP.