Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / Javascript

JavaScript Questions

Rate me:
Please Sign up or sign in to vote.
4.57/5 (31 votes)
18 Jun 2013CPOL6 min read 54.5K   54   17
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 <code>x, y and z after the execution of the below three lines of script?  

JavaScript
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<code><code> x=y++. In the above line of code the actual execution will happen in the two steps explained below:
JavaScript
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:
JavaScript
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.

JavaScript
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:

  1. Alert 2 times with values: 5 and 5
  2. Alert 2 times with values: 10 and 10
  3. Alert 3 times with values: 10, 10 and 10
  4. 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:

JavaScript
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 ?  

JavaScript
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.

  1. First is Global Execution Context during this all variable instantiations happens and assigned to Global Object.
  2. 2nd is "declareMe" function invoke Execution Context.
  3. 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 ( <code>declareMe(); ) will get evaluated successfully because, global object already had the property named as 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.  

JavaScript
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 script
JavaScript
var 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 

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. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States

I am a Senior Software Developer working since 2005 in Microsoft ASP.Net and related Technologies.


I work on C#, Asp.Net, MVC, RAZOR, Entity Framework, JavaScript, jQuery, HTML5, CSS3, WCF, Silverlight, WPF, MVVM, SQL, SSIS, etc. Did Function Point Analysis, WBS to estimate projects and worked on Agile Scrum team.



I enjoy on exploring new technologies by implementing and writing about them, great interest in learning Design Patterns and their implementations. I love learning, writing JavaScript; now my favorite JavaScript library is jQuery. I enjoy writing jQuery Plugins and core JavaScript. I also write Technical blogs here. You can find me on LinkedIn.



I wrote an article on Swami Vivekananda posted his audio speeches by reading them.


Comments and Discussions

 
GeneralMy vote of 5 Pin
Oron Mizrachi29-Jun-13 2:17
Oron Mizrachi29-Jun-13 2:17 
GeneralMy vote of 4 Pin
saguptamca18-Jun-13 22:05
professionalsaguptamca18-Jun-13 22:05 
GeneralRe: My vote of 4 Pin
Rupesh Kumar Tiwari19-Jun-13 4:06
Rupesh Kumar Tiwari19-Jun-13 4:06 
GeneralRe: My vote of 4 Pin
saguptamca19-Jun-13 4:27
professionalsaguptamca19-Jun-13 4:27 
GeneralRe: My vote of 4 Pin
David Rogers Dev1-Jul-13 2:59
David Rogers Dev1-Jul-13 2:59 
GeneralRe: My vote of 4 Pin
saguptamca1-Jul-13 23:42
professionalsaguptamca1-Jul-13 23:42 
GeneralMy vote of 5 Pin
Mohammed Hameed18-Jun-13 21:09
professionalMohammed Hameed18-Jun-13 21:09 
GeneralRe: My vote of 5 Pin
Rupesh Kumar Tiwari19-Jun-13 3:43
Rupesh Kumar Tiwari19-Jun-13 3:43 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA12-Apr-13 19:17
professionalȘtefan-Mihai MOGA12-Apr-13 19:17 
GeneralMy vote of 4 Pin
Prasad Khandekar13-Mar-13 20:11
professionalPrasad Khandekar13-Mar-13 20:11 
GeneralMy vote of 5 Pin
Sebastiaan Meijerink12-Mar-13 9:34
professionalSebastiaan Meijerink12-Mar-13 9:34 
GeneralMy vote of 4 Pin
Andre Pieterse12-Mar-13 2:52
Andre Pieterse12-Mar-13 2:52 
QuestionNice artilcle Pin
Mehul198811-Mar-13 21:49
Mehul198811-Mar-13 21:49 
GeneralGood Info About JavaScript. Pin
JayantaChatterjee11-Mar-13 3:48
professionalJayantaChatterjee11-Mar-13 3:48 
QuestionJavaScript Hoisting Question 2 need to be described more. Pin
Kundan Singh Chouhan10-Mar-13 3:53
Kundan Singh Chouhan10-Mar-13 3:53 
AnswerRe: JavaScript Hoisting Question 2 need to be described more. Pin
Rupesh Kumar Tiwari10-Mar-13 4:09
Rupesh Kumar Tiwari10-Mar-13 4:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.