13,199,311 members (72,139 online)
alternative version

#### Stats

33.2K views
52 bookmarked
Posted 6 Mar 2013

# JavaScript Questions

, 18 Jun 2013
 Rate this:
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?

```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:
```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);//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

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 , 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(){
}

//creating a function by expression.
var fnExpression = function(){
}```

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.

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

## Share

 Software Developer (Senior) 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.

## You may also be interested in...

 Pro

 First Prev Next
 My vote of 5 Oron Mizrachi29-Jun-13 2:17 Oron Mizrachi 29-Jun-13 2:17
 My vote of 4 saguptamca18-Jun-13 22:05 saguptamca 18-Jun-13 22:05
 Re: My vote of 4 Rupesh Kumar Tiwari19-Jun-13 4:06 Rupesh Kumar Tiwari 19-Jun-13 4:06
 Re: My vote of 4 saguptamca19-Jun-13 4:27 saguptamca 19-Jun-13 4:27
 Re: My vote of 4 David Rogers Dev1-Jul-13 2:59 David Rogers Dev 1-Jul-13 2:59
 Re: My vote of 4 saguptamca1-Jul-13 23:42 saguptamca 1-Jul-13 23:42
 My vote of 5 Mohammed Hameed18-Jun-13 21:09 Mohammed Hameed 18-Jun-13 21:09
 Re: My vote of 5 Rupesh Kumar Tiwari19-Jun-13 3:43 Rupesh Kumar Tiwari 19-Jun-13 3:43
 My vote of 5 Mihai MOGA12-Apr-13 19:17 Mihai MOGA 12-Apr-13 19:17
 My vote of 5 Sebastiaan Meijerink12-Mar-13 9:34 Sebastiaan Meijerink 12-Mar-13 9:34
 My vote of 4 Andre Pieterse12-Mar-13 2:52 Andre Pieterse 12-Mar-13 2:52
 Nice artilcle mehul198811-Mar-13 21:49 mehul1988 11-Mar-13 21:49
 Good Info About JavaScript. Jayanta Chatterjee11-Mar-13 3:48 Jayanta Chatterjee 11-Mar-13 3:48
 JavaScript Hoisting Question 2 need to be described more. Kundan Singh Chouhan10-Mar-13 3:53 Kundan Singh Chouhan 10-Mar-13 3:53
 Re: JavaScript Hoisting Question 2 need to be described more. RupeshKumar10-Mar-13 4:09 RupeshKumar 10-Mar-13 4:09
 I will put more explaination on question number 2 by modifying this article. Thanks for your feedback.
 Message Closed 7-Mar-13 4:47 Muslembof 7-Mar-13 4:47
 Last Visit: 31-Dec-99 18:00     Last Update: 22-Oct-17 7:26 Refresh 1