Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

JavaScript Questions

, 18 Jun 2013
Rate this:
Please Sign up or sign in to vote.
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 x, y and z 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:

  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!  Blush | :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.

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

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
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)

Share

About the Author

Rupesh Kumar Tiwari
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.

Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 5 PinmemberOron Mizrachi29-Jun-13 2:17 
GeneralMy vote of 4 Pinprofessionalsaguptamca18-Jun-13 22:05 
GeneralRe: My vote of 4 PinmemberRupesh Kumar Tiwari19-Jun-13 4:06 
GeneralRe: My vote of 4 Pinprofessionalsaguptamca19-Jun-13 4:27 
GeneralRe: My vote of 4 PinmemberDavid Rogers Dev1-Jul-13 2:59 
GeneralRe: My vote of 4 Pinprofessionalsaguptamca1-Jul-13 23:42 
GeneralMy vote of 5 PinprofessionalMohammed Hameed18-Jun-13 21:09 
GeneralRe: My vote of 5 PinmemberRupesh Kumar Tiwari19-Jun-13 3:43 
GeneralMy vote of 5 PinmemberMihai MOGA12-Apr-13 19:17 
GeneralMy vote of 4 PinmemberPrasad Khandekar13-Mar-13 20:11 
GeneralMy vote of 5 PinmemberSebastiaan Meijerink12-Mar-13 9:34 
GeneralMy vote of 4 PinmemberAndre Pieterse12-Mar-13 2:52 
QuestionNice artilcle Pinmembermehul198811-Mar-13 21:49 
GeneralGood Info About JavaScript. PinmemberJayanta Chatterjee11-Mar-13 3:48 
QuestionJavaScript Hoisting Question 2 need to be described more. PinmemberKundan Singh Chouhan10-Mar-13 3:53 
AnswerRe: JavaScript Hoisting Question 2 need to be described more. PinmemberRupeshKumar10-Mar-13 4:09 
QuestionMessage Automatically Removed PinmemberMuslembof7-Mar-13 4:47 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 19 Jun 2013
Article Copyright 2013 by Rupesh Kumar Tiwari
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid