JavaScript Interview Questions

Take the first step and prepare in advance for your Javascript Interview. We have compiled the best possible JavaScript Interview questions along with the best answers that will help you in cracking your Javascript Interview and land your dream career as a JavaScript Developer.

  • 4.6 Rating
  • 50 Question(s)
  • 55 Mins of Read
  • 3329 Reader(s)

Advanced

Prototypal inheritance is to add new capabilities to a constructor function using Prototype.
Let’s first understand what are Constructor functions. They are basically JavaScript way to implement the concept of Classes.
Let’s consider the example below, where we have a “Car” constructor function. In it we have a “model”, which we are also returning by getModel(). Now we can create a new instance of it by using the “new” keyword. Each instance will have its own “this” and have its own getModel(). 

let Car = function(model) {
  this.model = model;
  this.getModel = function() {
    return this.model;
  }
}
 
let harryCar = new Car('toyota');
console.log(harryCar.getModel()); //toyota
 
let maryCar = new Car('nissan');

console.log(maryCar.getModel()); //nissan

Now, the problem is that every time we create a new instance we get a new copy of getModel(). Suppose we have 100 instances, then we will have 100 copies. Below console log shows the same thing.

We should somehow move the logic for getModel() outside our Constructor function and that is where the concept of Prototype helps.

In JavaScript as you know everything is an Object. Whenever a function is created there are two object one is the function object another is the prototype object. Now to access the Prototype object we have a property on the function object also known as “prototype”.

Every instance created from the function have access to the Prototype object.  Now, let’s move our getModel() outside our Constructor function using prototype.

let Car = function(model) {
  this.model = model;
}
 
Car.prototype.getModel = function() {
    return this.model;
 }
 
let harryCar = new Car('toyota');
console.log(harryCar.getModel()); //toyota
 
let maryCar = new Car('nissan');
console.log(maryCar.getModel()); //nissan

We get the same result and this is known as Prototypal Inheritance. Also, each new instance don’t have its own getModel(), which we can see in below console log.

JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time. 

Many people think JavaScript is asynchronous because we can do async tasks like setTimeout, callbacks, promises in it. But the asynchronous behaviour of JavaScript(setTimeout, callbacks, promises) is not a part of JavaScript itself and built on top of JavaScript language in browser and accessed through browser APIs.

The browser have a Call Stack, Browser API and Message Queue and the order of their processing is called event loop.

We will see the working of the classic interview question to understand how the event loop and with it the asynchronous behaviour of JavaScript works.

function main() {
  console.log('A');
  setTimeout(function(){
    console.log('B');
  },0);
  console.log('C');  
}
main();
 

//Output

//A

//C

//B

The output will be A C B , even after the setTimeout() was set to display “b” after 0 ms. This happens because of the internal working of the browser. Let’s look into the step of execution.

The main() is pushed into Call Stack, which then console logs A. Then it is popped out and the setTimeout is pushed into Call Stack. Now the setTimeout() uses Browser API, so it is pushed there and the console log C is pushed into Call Stack.

Even with the delay of 0ms the exec() for setTimeout have to go to the Message Queue.
After all the statements of main() is run and the Call Stack is empty, then only the exec() from Message Queue can be pushed to the Call Stack.

This is how event loop works and the asynchronous, non-blocking part of JavaScript comes from.

Every function in JavaScript have call, apply and bind methods. These methods can be used to set the custom value of “this” to the execution context of the function.

call
Let’s say that we have an object called obj. It only has one property called num, which has a value of 3. Let’s also make a function called addNumbers

Now, in addNumbers we have this.num. But how do we pass the value obj.num to it. We need to pass it a context, which means the value of “this”. We will do this my call method by passing a first argument as obj, so the “this” is the obj now.

let obj = {num: 3};
let addNumbers = function(a, b, c){ 
  return this.num + a + b + c;
};
console.log(addNumbers.call(obj, 1, 4, 6));  //14 

apply
It is totally similar to call, but the only difference is that we can pass array as the second argument. We will use the same code for apply also. But now we have an arr, to be passed as second argument. 

let obj = {num: 3};
let addNumbers = function(a, b, c){ 
  return this.num + a + b + c;
};
let arr = [7, 3, 8];
console.log(addNumbers.apply(obj, arr)); //21

bind
Bind works in a bit different way then call and apply. It works by returning a copy of the function. We will take the returned function in bindFunc and then execute it in the next line.

let obj = {num: 3};
let addNumbers = function(a, b, c){ 
  return this.num + a + b + c;
};
 
let bindFunc = addNumbers.bind(obj);
console.log(bindFunc(7, 3, 8)); //21

Question Continued:

const cleanRoom = function(soap) {
  const innerFunc = function(_soap) {
    console.log(`Cleaning ${this. room} with ${_soap}`)      
  }
  innerFunc(soap);
}
let harrysRoom = {
  room: "Harry's room"
}
cleanRoom.call(harrysRoom, "Harpic"); 
//Output - Cleaning undefined with Harpic
Answer:
There are four solutions to access “this” inside the innerFunc().

Solution 1
Use a “that” variable in cleanRoom() for accessing “this” inside innerFunc(). Basically “that” is nothing but the outer “this”.

const cleanRoom = function(soap) {
  let that = this;
  const innerFunc = function(_soap) {    
    console.log(`Cleaning ${that.room} with ${_soap}`)      
  }
  innerFunc(soap);
}
 
let harrysRoom = {
  room: "Harry's room"
}
cleanRoom.call(harrysRoom, "Harpic");
//Output - Cleaning Harry’s room with Harpic

Solution 2
Use call method to use the outer “this” inside the innerFunc().

const cleanRoom = function(soap) {
  const innerFunc = function(_soap) {    
    console.log(`Cleaning ${this.room } with ${_soap}`)      
  }
  innerFunc.call(this, soap);
}
 
let harrysRoom = {
  room: "Harry's room"
}
cleanRoom.call(harrysRoom, "Harpic");
//Output - Cleaning Harry’s room with Harpic

Solution 3
Use bind method to use the outer “this” inside the innerFunc().

const cleanRoom = function(soap) {
  const innerFunc = function(_soap) {    
    console.log(`Cleaning ${this.room } with ${_soap}`)      
  }
  innerFunc.bind(this)(soap);
}
 
let harrysRoom = {
  room: "Harry's room"
}
cleanRoom.call(harrysRoom, "Harpic");
//Output - Cleaning Harry’s room with Harpic

Solution 4
Use arrow function in the innerFunc(). Arrow functions have special meaning for “this” and it is that, it takes the value of “this” from the enclosing scope and is very useful in this case.

const cleanRoom = function(soap) {
  const innerFunc = (_soap)=> {    
    console.log(`Cleaning ${this.room } with ${_soap}`)      
  }
  innerFunc(soap);
}
 
let harrysRoom = {
  room: "Harry's room"
}
cleanRoom.call(harrysRoom, "Harpic");
//Output - Cleaning Harry’s room with Harpic

 One of the main use of “call” is to change an array like object to array.

There is an array like object arguments  available for every normal function(not arrow function). It is very useful in functions, as we can get the number of arguments passed to it.  Let’s convert the arguments into array, because arrays have a lots of functionality.

Consider the below example, where we console log arguments. If we expand it in dev console, it shows it’s not and array and it’s __proto__ doesn’t have array functionalities.

let sumNumbers = function() {
  console.log(arguments);
} 
sumNumbers(1, 2, 3, 4);

Now to convert it we will take an empty array and use it’s slice method. Then call it through call, by passing the argument Object. Now it is converted into array and the __proto__ have all array functionalities. So, we are using the array reduce method available to do the sum of the number of arguments passed to it.

let sumNumbers = function() {
  const argsToArray = [].slice.call(arguments);
  console.log(argsToArray);
  return argsToArray.reduce((acc, curr) => acc + curr);
} 
console.log(sumNumbers(1, 2, 3, 4)); //10
console.log(sumNumbers(1, 2, 3)); //6


The second application of call is in inheritance , using constructor functions. 

Consider the below example. Here in the Cat function, we called its parent Mammal using call method with “this” of Cat.

let Mammal = function(legs) {
  this.legs = legs;
}
 
let Cat = function(legs, isDomesticated) {
  Mammal.call(this, legs);
  this.isDomesticated = isDomesticated;
}
 
let tiger = new Cat(4, false);
let homeCat = new Cat(4, true);
 
console.log(tiger); // { legs: 4, isDomesticated: false }
console.log(homeCat); // { legs: 4, isDomesticated: true } 

One of the practical use of apply is to pass an array to a function, which expects arguments only.

Consider the case of Math.max, which gives the maximum of the arguments passed. So, now to pass an array like in below code, we convert it through apply. Note the first argument is null because we are not passing any Object for “this” binding.

let arr = [20, 6, 29, 12];
console.log(Math.max(20, 6, 29, 12)); // 29
console.log(Math.max.apply(null, arr)); // 29

One of the practical use of bind is in React. In React whenever we call a function from render(), we have to bind it’s “this” in constructor.

Consider the below code. We bind the “this” of the event handler to the component instance in the constructor, we can pass it as a callback without worrying about it losing its context.

class Foo extends React.Component{
  constructor( props ){
    super( props );
    this.state = {
      text: ''
    }
this.handleChange = this.handleChange.bind(this);
  }
handleChange(event){
    this.setState({
      text: event.target.value
    })
  }
render(){
    return (
      <input type="text" value={this.state.text}
      onChange={this.handleChange} />
    );
  }
}
ReactDOM.render(
  <Foo />,
  document.getElementById("app")
);
Question Continued:
var hero = {
    _name: 'Johnny Deep',
    getIdentity: function (){
        return this._name;
    }
};
var heroIdentity = hero.getIdentity;
console.log(heroIdentity());
console.log(hero.getIdentity());

What is the issue with the code and how can it be fixed ?

Answer:

The output logged will be:

undefined
Johnny Deep

The first console.log prints undefined because heroIdentity()is been invoked in the global context (i.e., the window object) where the _name property doesn’t exists.

The way to fix it is by binding, it to hero object by using bind.

var heroIdentity = hero.getIdentity.bind(hero);

Question Continued:

var length = 10;
function fn() {
console.log(this.length);
}
var obj = {
  length: 5,
  method: function(fn) {
    fn();
    arguments[0]();
  }
};
obj.method(fn, 1);

Answer:

The output logged will be:

10
2

When inside the method, fn() is called the “this” of the function fn is at window level. So, “this.length” will produce 10.
Now, when arguments[0]() is called, then argument[0] is equivalent to “fn” and function fn is called. But “this” now is the arguments array, which is of length 2 because it contains two arguments (fn, 1). So, “this.length” will produce 2.

Question Continued:

console.log(('hello').__proto__.__proto__.__proto__);

Answer:

The output logged will be: null

The reason is for prototype chaining. The __proto__ of ‘hello’ is the global String.

console.log(('hello').__proto__);

Then the __proto__ of it is the global Object.

console.log(('hello').__proto__.__proto__);

Now, the Object is the final thing from which everything in JavaScript is created and it points to null.

Nested promises are set of promises in which , the result of one promise we call another in the .then statement.
It is very useful in practical applications, where the result of fetch from an API endpoint will result in sending the data to another endpoint. Nested promises can also be done with callback functions, but the code get complicated soon.

Let’s look at an example of nested promises. Here we have three functions which return promises- movieTicketQueue, buyPopcorn and happyPartner. Now only the movieTicketQueue is returning resolve() or reject() depending on random number. The other two functions are returning only resolve() for simplicity sake.

Now, when the movieTicketQueue function is run and return a resolve(), then the immediate .then block will be run or else we will go to the .catch block. In the .then we are returning the next buyPopcorn and in its .then we are returning the happyPartner. We are passing the message from one function to other, so it will be appended.

On running the code and getting a resolve, because we random number greater than 0.5, we get below output. 

On running the code and getting a reject, because we random number less than 0.5, we get below output.

We can implement the Array.prototype methods by using callbacks and actually this is the way it is implemented in JavaScript internally.

forEach
We are implementing our version of forEach as myEach by having the callback attached to the prototype, which is available to every JS function. Here “this” is equal to the array. So, we are iteration over it using traditional for loop and calling the callback function on each iteration.

map
We are implementing our version of map as myMap, by creating an empty array in our function and then pushing it in the iteration. From inside the push we are calling our callback, so when we are calling it we can use something like Math.round(line 17) to change an individual item or just return it like in line 13.

filter
We are implementing our version of filter as myFilter. The process is quite similar to map, where we create an empty array ad push to it. But as we know that filter goes through the array and gives an subset of elements depending on boolean expression.
Here when we iterate through the array and call the callback in an if statement, and if it’s true we are pushing the item into the array.

We will be implementing some, every and reduce by using of callbacks, in the same way, we used to implement forEach, map and filter in the previous question.

some
The Array prototype method some returns true if any element of the array fulfils the condition we are testing. Here also like filter, we will have the callback been checked in an if statement in every iteration. This will test our condition and even if one of it pass we return a true and get out of loop. If the iteration is complete, it means not a single element satisfy condition and we return false.

every
It is the opposite of some. The method “every” will return true only if every element passes the test. Here we do a trick in the if statement. We check the opposite of the test, so say if element should be greater than 10, we are checking for less than 10. So, if even one is less than 10 we return false. And if we iterate through whole loop, means all element satisfy the condition so we return true.

 reduce
The method reduce is considered the hardest in the Array prototype methods to master. It is because it’s concept is quite different. It takes the whole array and iterate through it and returns a single value. It is useful to do sum/multiply/subtract of all the elements of an array, but is more powerful than that. To do this it have an accumulator, which is used to hold the number in each run. This accumulator will be operated with the current value of the iteration.
Now in our implementation, we first check whether an accumulator was supplied or else make it to undefined. Now inside the loop we update the accumulator variable by using the callback.

 Named after Haskell Brooks Curry, currying is a technique of evaluating function with multiple arguments, into sequence of function with single argument.

In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled. 

Here is a simple example to write a simple multiply function and then the function asked in the question with currying.

Currying works because of JavaScript concept of closures. The closure created by the nested functions to retain access to each of the arguments. So inner function which do “return a * b * c * d” have access to all arguments.

Map and WeakMap are data structures that were introduced in ES6.
Map is a collection of elements where each element is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key,value pair in the same order as inserted.

Let’s find out the reason for Map by analysing a problem with Objects. In the below example, we have an object “x” and another object “a”. Now we are using “a” as a key and push a value to “x”. Now, if we console log “x” the key is shown as [object object], but then also we can extract it’s value by x[a].

But the real problem occurs when we add another object to “x” for key. It over-writes the earlier object. This occurs because in JavaScript we can have only 1 key as an object.

Now we will look at how Maps help. We create Map by the new keyword. And also to add to Map we need use one of its method set.
In the below example the objects “a” and “b” are been added as key successfully.

Notice that the __proto__ object contains Symbol.iterator, so the for..of loop can be used to iterate over it like arrays. The same is not true for Objects.

We iterate over Map using the for..of loop. We get an array of [key, value] for each element in Map. So, we de-structure it into [key, value] pair.

If we add the same object as key as in line 9 for “a”, the Map will over-write the old value of the key.
Also, we can delete an entry by passing it’s key in delete method.

There is one problem with Map and it is that it holds the Map’s key, even if the original key is deleted. That is the reason we use WeakMap. So, WeakMap allows garbage collector to work as it holds a weak reference to its key but Maps doesn’t allow garbage collector to work.

 Another difference is that keys of WeakMaps are of type Object only. Primitive data types(Number, String, Boolean, Symbol) can only be used in Maps.

Set and WeakSet are also new data structures introduced in ES6 along with Map and WeakMap. Set are data-types like arrays, but the key feature is that we cannot keep duplicate data. In a nutshell Sets are nothing but unique arrays.

Let consider below example. The way to create a Set is through the constructor function using “new” keyword. We add value to Set by using add method and delete value from Set using delete method.

Notice that it’s __proto__ object have Symbol.iterator like array, which means it is iterable.

There is another method to create a Set. We can pass an iterable like array to the constructor function.
Also, we cannot add duplicates value in a Set. Also we can add values to Set using add in method chaining format. All are shown in below example.

We can use this feature to get unique items from an array containing duplicate items. Notice at Line 3, we are using spread operator inside an array. It is because Set is not exactly array and we are converting it to array.

WeakSets are like WeakMaps and one of key feature is that we cannot have Primitive data-types(Number, String, Boolean, Symbol) as it’s items. So, the below will throw and error.

So, we will add Objects to WeakSet. Also, notice that it’s __proto__ doesn’t have many methods and it is not an iterable. 

Symbols are the new primitive data-type introduced in ES6. Symbols is unique and immutable data-type. They are tokens that can be used as unique ids.

Two Symbols are never the same, even if they are declared as same. Consider the below example.

We can also put some value inside the constructor in Symbol, which helps in identifying it. Also, it’s typeof is symbol

We cannot directly concatenate it to a Sting as it will throw an error.

So, we convert a Symbol into a String by using string in-built function toString().

One of the use case of Symbol is to be used as unique keys. We can use them very efficiently in Objects and Maps, where only unique keys are allowed.

The concept of Sub-classes and inheritance is like that in other languages like Java and C++. The sub-class can inherit properties from its parent class and can also override or update an existing method.

Let’s consider the below example. We have a Parent class “Mammal” and a Sub-class “Bat” which is inheriting from it. Notice, that we have use the “extends” keyword.
To  use the “legs” and “name” variable in “Bat”, we use the “super()” method. Also, notice that we can use update “walk()”, and add additional functionalities.

To understand iterators, we will first look into recently introduced [Symbol.iterator] property in data types. 

This indicates whether a data structure is iterable or not. This includes array, strings, Map, Sets and NodeList. Objects doesn’t have a [Symbol.iterator] property.

If we check the __proto__ of an array, we can find the [Symbol.iterator] property.

But it is not the case with Objects as it is not iterable.

Now, iterator are created using the “Symbol.iterator” and can be used to iterate over all data structures which have [Symbol.iterator] property.

Let consider the below example. Here we create an iterator by the syntax at line 3. Now we can iterate over the array using “iterator.next()”. Each run gives and Object which have the “value” and “done”, which specifies whether there is an element. Notice, after the fifth run we get the “value” as undefined and “done” as true.

ES6 introduced a new way of working with functions and iterators in the form of Generators (or generator functions). A generator is a function that can stop midway and then continue from where it stopped.  

Let’s look at the below example. The generator function have a special syntax with “*”. Also, inside the generator we have “yield” statements. Each “next()”, goes to the next yield statement.

The above example doesn’t shows any advantages of generator and it is same as iterating through an array. But let’s look at next example, where we have an infinite while loop inside an generator.
First look at this normal function. If we run it, it will cause an infinite loop and crash your browser.

But the same type of function with generator doesn’t produce an infinite loop. It pauses every time yield is called and will generator the next value of “i” every-time “next()” is called. So, this function can be used to generate any time “i” and not like in array where we have to give the size of array in advance.

 In JavaScript every object is created from a global “Object”(Notice the capital ‘O’). If we look at it in console, it have many properties and create been one of it.

 The Object.create() method creates a new object, using an existing object as the prototype of the newly created object. 

Consider the below example, where we can create a new object from the existing object and can also add new properties to it or modify an existing property.


Now, let see a practical use of Object.create in Inheritance. In below example we have an Employee function, which have two functions in its Prototype. Then we have another function SalesEmployee and then set it’s Prototype to Employee’s Prototype. We also have a function in the prototype of SalesEmployee 
SalesEmployee.prototype = Object.create(Employee.prototype);

We then create an instance of the SalesEmployee as emp1 variable. It have all functions of Employee function and can also use it.

Prototype chain can be explained through below example. Here we have three functions MammalWhale and BlueWhale. Each have their own version of print().

We are inheriting from Mammal to Whale by setting Whale’s prototype to be Mammal’s prototype.
Then inhering from Whale to BlueWhale by setting BlueWhale’s prototype to be Whale’s prototype.

Then we have three instances of Mammal, Whale and BlueWhale. On calling the print(), we get the respective console log.

Now, let remove BlueWhale’s print() method and then if we call print() on its instance blueWhale, we get result from Whale’s print().

If we further remove Whale’s  print() method and then if we call print() on its instance blueWhale, we get result from Mammal’s print().

So, if you call an method on a Child and the method is not there, it will check in its Parent and if not there then will check in Parent’s parent.

 To understand inheritance using constructor function, we will see an example containing a Mammal parent function and Human child function. Also, make the Human’s Prototype have a reference of Mammal’s Prototype using Object.create. Human’s Prototype will have all methods of Mammal’s Prototype.

 Now, let’s look into “Human” in the console. As you can see it contains “Mammal” sleep and walk function in it’s __proto__.

But we have a major problem because the statement Human.prototype = Object.create(Mammal.prototype) wipes out any Human’s Prototype function and also it’s constructor.
We didn’t declared any Human’s Prototype function, but the constructor was wiped. 

So, we solve it by below code. It is using Human.prototype.constructor = Human to set the constructor back in “Human”.
Also, we are declaring Human’s Prototype function after Human.prototype = Object.create(Mammal.prototype)

...
...
Human.prototype = Object.create(Mammal.prototype);
Human.prototype.constructor = Human;
Human.prototype.fly = function() {
  return 'Flying with Gliders';
}

Let’s now complete the code and create two instances of “Human” as hari and harry. Both can access functions walk, sleep and fly.


Interview Tips for Freshers
The industry is looking for candidates who can start with their work immediately and not the ones who are looking for a training. As a newbie in the IT Industry for a career as UI Developer, it’s good to learn the various UI frameworks like Vue.JS, React.JS, and Angular.js which are Javascript frameworks. To be shortlisted you can also take up some courses on these front-end technologies.

These javascript interview questions for beginners will help you to crack your javascript interview. Be prepared with the best interview questions for javascript and you will be able to pass the Javascript interview easily. All the best!

Beginner

Let’s first understand what is an compiled language and interpreted language.

Compiled Languages are languages in which we turn a program first from human-readable format to machine format, generally through a compiler. After that we execute that code. So, it is generally a two-step process. Languages like C, C++ and Java are example of Compiled languages. For example if we have a “C” program(hello.c), we will first convert it into machine code by using a gcc(gnu C compiler) like below:

gcc hello.c -o hello

If no error it will generate an executable “hello” and we will run it by:

./hello

Interpreted Languages are languages in which code doesn’t needs to be compiled first. Language like Perl, Python are interpreted languages. To run a python code we just need to run it directly by command like below:

python hello.py

The above code does not need to be compiled first but it does require that python is installed on any machine that needs to run the script.

JavaScript is a special case where you directly execute your source code. A webpage will directly execute your JavaScript. So, for that reason many people think JavaScript as a interpreted language.

However there is a compilation step just before the interpretation step in JavaScript. So, JS is both compiled and interpreted language.

 Compilation Step – During this step the compiler mainly registers the variable declarations.

Let consider the below example. The compilation steps mainly looks at the var keyword. It is not bothered with what is assigned in these variables.

var a = 10;

var b = 20;

console.log(a+b)

When the compiler goes to line 1, it encounters var a and registers it in the global scope and then goes to line 3 and registers the var b. Line 5 is only a console and it doesn’t finds any var, so don’t do anything.

Interpretation Step – During this the actual execution takes place. 

For the above example, the interpreter starts at line 1 and see a variable a and ask the compiler, if it have a variable “a” in Global scope and the compiler have it. So, it assigns the value 10 to it.
Next the same step is repeated for line 3 and interpreter assigns 20 to variable “b”. 

Now once the interpreter goes to line 5, it finds console. It first looks for console at global scope from the compiler but don’t find it. So, it checks in the JavaScript global and finds it. Inside the console there are variable a and b, which it finds at global scope. It then adds them using addition operator and display the result.

The variable “var” was since the beginning of JavaScript i.e. since 1997. So, if someone didn’t updated there browser since the beginning(or past 10 years) the keyword “var” will only work on there browser. 

The variables "let” and “const” were introduced recently in ES6(In 2015).  There were some design mistakes made with “var” and these were rectified with “let” and “const”. 

The problem is that “var” is function scoped and it causes a lot of problems.
Consider the below example where we are using “var” inside a traditional “for” loop. But we are also able to access and update “i” outside of the “for” loop.

for(var i=0; i<5; i++) {
  console.log(i); //Output- 0 1 2 3 4
}
 
i = i + 2;
console.log(i); //Output- 7

Since, “var” is function scope so we can put our “for” loop inside a function and then “i”  won’t be accessible outside.

function incrementI() {  
  for(var i=0; i<5; i++) {
    console.log(i); 
  }
}
 
incrementI(); //Output- 0 1 2 3 4
i = i + 2;
console.log(i); 

//Output- 

/*

Exception: ReferenceError: i is not defined

@Scratchpad/6:9:1

*/

 Traditional languages like C, C++ and Java as they are blocked scope and it is what was desired from JavaScript. So, the variable “let” and “const” introduced in 2015 were made block scoped.

 The “for” loop declared with “let” will also throw an error, when we try to access “i” outside of it. It is because the scope of “i” ends with the “for” loop.

for(let i=0; i<5; i++) {
    console.log(i);  //Output- 0 1 2 3 4
}
i = i + 2;
console.log(i); 

//Output-  

/*

Exception: ReferenceError: i is not defined

@Scratchpad/6:6:1

*/

We will understand “const” now. It is similar to “let” and have block scope. But it was created to declare constant variables in JavaScript. We cannot assign a new value to a variable after the initial declaration for primitive types like integers and strings.

const c = 12;
c = 14;
console.log('c is ', c);

/*

Exception: TypeError: invalid assignment to const `c'

@Scratchpad/6:2:1

*/

But can add or update values for non-primitive like arrays and objects. 

const arr = [1, 2, 3];
arr.push(4);
console.log('arr is ', arr); // [ 1, 2, 3, 4 ]
 
const obj = { name: 'Robin', skill: 'JS' };
obj.skill = 'React';
obj.profession = 'Developer';
console.log('obj is ', obj); 
// { name: "Robin", skill: "React", profession: "Developer" }

 JavaScript has both strict and type-converting equality comparison. For strict comparison we use === and for type-converting comparison we use == . Let’s look at each of it in details :

Strict Comparison(===)
For strict comparison the items been compared must be the same type.

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions. 
console.log("Coder" === "Coder"); //true
console.log("Coder" === "coder"); //false
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
console.log(23 === 23); //true
console.log(NaN === NaN); //false
console.log(0 === -0); //true 
  • Two Boolean operands are strictly equal if both are true or both are false.
console.log(true === true); //true
console.log(false === false); //true
  • Two objects are strictly equal if they refer to the same Object.
var obj = {};
var newObj = obj;
console.log(newObj === obj); //true
  • Null and Undefined types are not equal
console.log(null === undefined); //false
console.log(null == undefined); //true

Type-converting comparison
The == does a type conversion before comparing, if both items are of different types. 

As you can see in the below example. String 1 is equal to numeric 1, when using ==. It is because the type of String 1 is converted to Number before comparison. 
It is the similar case with “1 == true”. The 1 is converted into Boolean, which is true before comparison.
Same expressions are not true while using ===, as we know it doesn’t do any type conversion.

console.log('1' == 1); //true
console.log(1 == true); //true
console.log(1 === true); //false
console.log('1' === 1); //false

Both null and undefined  represents empty values. Let’s understand them first and then we will see what is the difference.

undefined
To understand “undefined” we have to understand what is declaration and definition of variables. When we declare a variable as in below diagram by “var value”, the compiler makes space for a variable “value”. The definition means that we assign a value to the variable and it’s allocated in that space. You can also do these two together by
var value = 42;

So, every language have a way of handling the value of a variable between function declaration and definition.
In JavaScript that is handled by type “undefined”. The type undefined is a primitive type which have only one value possible i.e. undefined. 

null
It is also similar to “undefined” and is a primitive type. It also have only one possible value i.e. null. It is also used to represent empty values, but is generally assigned by the users.

var a;
console.log(a); //undefined 
a = null;
console.log(a); //null

Function declaration is like most other traditional languages, but in JavaScript we use the keyword “function”.
In function expression we assign an anonymous function to an variable. They are very useful when we pass function as arguments to other function or return an function.

function funcDeclaration() {
  console.log('Function declaration');
}
 
let funcExpression = function() {
  console.log('Function expression');
}
 
console.log(funcDeclaration()); //Function declaration
console.log(funcExpression());  //Function expression 

One of the key difference is that, we can call a function declaration even before defining it but same is not true for function expression and it will give reference error. Let’s move both the function call to the top. 

console.log(funcDeclaration()); //Function declaration
console.log(funcExpression());  //ReferenceError
 
function funcDeclaration() {
  console.log('Function declaration');
}
 
let funcExpression = function() {
  console.log('Function expression');
}

/*

Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization

@Scratchpad/7:2:1

*/

But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we understood in Question 1. 
The compiler runs first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration. 
So, the function declaration call doesn’t give as any error.
But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t knows what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t know what is functionExpression.

Closures are one of the most complex topic in JavaScript, but they are everywhere in JavaScript.

Closures are basically, the inner function having access to the variables in the outer function scope, even after the outer function has returned. To use a closure, simply define a function inside another function and expose it. To expose a function, return it.

Consider the below code. The variable b have an scope in outer function i.e. from line 4 to line 10. So, at line 13 when we call the outer function, it can access the value of b, but at line 14 there is no outer function.

So, how does the innerFn() access the value of b. This is where the JS feature of Closures comes into play.

When the “var inner” is created at line 6, the JS engine not only stores the function object information but also its scope information. So, it stores a scope of variable b inside the inner function object.

Now it doesn’t matter where you call inner, whether in this file or some third party file. It will always remember the value of a and b, as if a snapshot is been taken.

var a = 10;
 
function outer() {
  var b = 20;
  
  var inner = function() {
    console.log(a);
    console.log(b);
  };
  return inner;
}
 
var innerFn = outer();
innerFn();
 

//Output

//10

//20

JavaScript “this” keyword simply means that whatever scope you are inside, it belongs to that. Now the scope can be a function or and Object. Although, there are some exception to this rule. We can have “this” in various context. Let’s go through them.

“this” in simple function
In a normal JS function like below, the “this” refers to global window object.

function foo() {
  console.log(this);
  console.log(this === window);  
}
foo();

Running the above code will give.

There is a special case with strict mode.

In strict mode “this” to be undefined , as global object refers to undefined instead of window object. 

function foo() {
  'use strict';
  console.log(this);
  console.log(this === window);  
}
foo();

“this” in an object property
In an object which have a property as a function, the value of “this” is the Object itself.

var obj = {};
obj.foo = function() {
  console.log("Inside obj foo");
  console.log(this);
}
obj.foo();

this is Object itself

“this” with constructor function
When a function is called with “new” keyword, it is known as constructor function. And the value of “this” refers to the newly created instance.

function Person(fn, ln) {
 this.first_name = fn;
 this.last_name = ln;
this.displayName = function() {
    console.log(`Name: ${this.first_name} ${this.last_name}`);
    console.log(this);
 }
}
let person = new Person("Tim", "Horton");
person.displayName();  
let person2 = new Person("Mary", " Poppins");
person2.displayName();

The newly created instance is nothing but an object, because everything in JS is an object.

One The for..in loop is mainly used to iterate over properties of an Objects.
In JavaScript Arrays are also Objects and each characters in an string have an index. So, we can use them also to iterate over Arrays and Strings also.

//Object example

const obj = {
  'frontend developer': 'Thomas',
  'designer': 'Mary',
  'backend developer': 'Harry',
  'engineering manager': 'Vikas'
}
 
for(const key in obj) {
  console.log(`${key}: ${obj[key]}`)
} 

//Array example

const array = ['frontend developer', 'designer', 'backend developer', 'engineering manager'];
for(const index in array){
  console.log(array[index]);
}

//String example

const string = 'frontend developer';
for(const index in string){
  console.log(string[index]);
}

The for..of loop was introduced in ES6 and is used to iterate over Objects that have [Symbol.iterator] property. This includes array, strings, Map, Set and NodeList. They cannot be used to iterate over Objects are not iterable.

If we check the __proto__ of an array, we can find the [Symbol.iterator] property.

But it is not the case with Objects as it is not iterable.

Some use of for..of loop are below:

//Array example

const array = ['frontend developer', 'designer', 'backend developer', 'engineering manager'];

for(const item of array){
  console.log(item);
}

//String example

const string = 'developer';
for(const char of string){
  console.log(char);
}

//Map example

const map = new Map();
 
const emp1 = {name: 'Vikas', Degree: 'MS'};
const emp2 = {name: 'Thomas', Degree: 'MBA'};
 
map.set(emp1, 'frontend developer');
map.set(emp2, 'engineering manager');
 
for(const [key, item] of map) {
  console.log(key, '-', item);
}

Hosting means we can use a variable even before declaring it. When the compiler runs(details in Question 1) and finds all the var declaration, it move them to the top of the file.

Let’s consider this below example. Here we are assigning values to  on name , age and profession without declaring them first. They are declared on line 8, 9, 10 and yet the interpreter doesn’t throws a runtime error. It is because it doesn’t matter where the variables are declared. They are always hoisted to the top by when the compiler makes the first pass.

name = "Thomas";
age = 45;
profession = "Engineering Manager";
 
console.log(`${name} aged ${age} is ${profession}`);
//Thomas aged 45 is Engineering Manager
 
var name;
var age;
var profession;

This is also true for function declaration, as the compiler also treats function declaration as variable declaration as in JS all function declaration are object declaration. But same is not true for function expression and it will give reference error. 

console.log(funcDeclaration()); //Function declaration
console.log(funcExpression());  //ReferenceError
 
function funcDeclaration() {
  console.log('Function declaration');
}
 
let funcExpression = function() {
  console.log('Function expression');
}

/*

Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization

@Scratchpad/7:2:1

*/

But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we understood in Question 1.
The compiler runs first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration.
So, the function declaration call doesn’t give as any error.


But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t knows what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t know what is functionExpression.

Question Continued:

var A = {
   x: function() {
       console.log('x');
   },
   y: function() {
       console.log('y');
   },
   z: function() {
       console.log('z');
   }
   
}

A.x().y().z();

Answer:

The output right now will be as below, as the method chaining is not understood by the compiler.

/*
Exception: TypeError: A.x(...) is undefined
@Scratchpad/1:14:1
*/

We can get the desired output by “return this” in each function.
Now “this” is the object “A”. So, A.x() will result in console logging ‘x’ followed by returning the object “A” to y().
After that the function A.y() will print ‘y’ followed by returning the object “A” to z().
Finally, ‘z’ is printed on console.

var A = {
    x: function() {
        console.log('x');
        return this;
    },
    y: function() {
        console.log('y');
        return this;
    },
    z: function() {
        console.log('z');
        return this;
    } 
}
A.x().y().z(); 
//Output
x
y
z

The sort() method is used to sort the elements of an array. But the output of the above is not what expected out of sort() function. The output will be [ 1, 15, 2, 30, 4, 45, 7 ] and it is far from desired.

This is because the default sort is according to tring Unicode points. The fix to it is by adding an anonymous function and tell to sort according to ascending or descending order. 

Ascending order is as below:

const array = [1, 2, 15, 4, 30, 7, 45];
console.log(array.sort((a, b)=> a-b)); //[ 1, 2, 4, 7, 15, 30, 45 ]

Descending order is as below:

const array = [1, 2, 15, 4, 30, 7, 45];
console.log(array.sort((a, b)=> b-a)); //[ 45, 30, 15, 7, 4, 2, 1 ]

Question Continued:

b
let i = ?
console.log(i * i); //Gives 0
console.log(i + 1); //Gives 1
console.log(i - 1); //Gives -1
console.log(i / i); //Gives 1

Answer:

The most obvious answer to think is the value of “i” will be 0. So, let’s put i = 0 and see what happens.

let i = 0;
console.log(i * i); //Gives 0
console.log(i + 1); //Gives 1
console.log(i - 1); //Gives -1
console.log(i / i); //Gives NaN

Everything is ok, but the last one produce NaN(Not a Number) because “0 divide by 0 will produce infinity”

So, we need a number which is like zero but gives 1 if we divide it by itself. Fortunately there is such a number in JavaScript. The number is the minimum value that is allowed in JavaScript and is represented by Number.MIN_VALUE

let i = Number.MIN_VALUE;
console.log(i * i); //Gives 0
console.log(i + 1); //Gives 1
console.log(i - 1); //Gives -1
console.log(i / i); //Gives 1

Now, what is this MIN_VALUE and why it produces the above correct desired result. If we console log it we can see it’s a very small number 5e-324.

console.log(Number.MIN_VALUE); //5e-324

Now, this number in most cases behaves like a zero(0). Like when we multiply it by itself(i * i), add it to 1(i + 1) or substract it from 1(i -1).
But when we divide this small number by itself it produces 1.

When an event happens on an element, it first runs on which it was clicked, then on its parent, then all the way up on other ancestors. It is the default behaviour of the browser.

Event capturing is the opposite of bubbling and it means when you click on parent element, it goes till the child.

We will first see Event Bubbling. The HTML contains an parent element containing a child element called Child1. When we click on the “Child1” button, first the console log of child is displayed and then the parent is displayed.

We will now see Event Capturing. The HTML contains an parent element containing a child element called Child1. When we click on the button, first the console log of parent is displayed and then the child is displayed. Notice that in addEventListener we have to pass a value of true.

 IIFE means Immediately Invoked Function Expression. Let’s first see a normal way to create function in JavaScript, also known as function as “Function declaration”. This is most similar, to the syntax of declaring functions in most other traditional languages like C++ and Java.

Consider the below example which have a simple function to add two numbers. Notice that these function definitions always start with the function keyword. You can’t omit it as it’s invalid syntax.

In JavaScript functions are first class citizens. So, there is another way to declare them. It is known as “Function Expression”.  We will refactor the above addNumbers() code. Here we are treating as if addNumbers is a variable declaration. But then assigning an anonymous function to it.

IIFE(Immediately Invoked Function Expression) is nothing but a function expression, but it is defined and invoked at the same time. Here we had got rid of the addNumbers name itself and calling it also at the same time. Notice, that we are passing 2,3 immediately after the anonymous function is declared.

As JavaScript for most part is function scoped, so IIFEs are great way to create private variables.

Promises in JavaScript are like promises in real life. You promise to do something, and then it is done or not done. A promise may be in one of 3 possible states: resolve, rejected, or pending.

They are mainly used to do asynchronous task like calling a REST api and getting the result back. So, these network calls takes time. When the network call is been made, the promise is in Pending state. Once the network call is successful the promise returns a resolve and if it fails it returns resolve.The resolve is captured by the then() callback function and reject captured by catch() callback function.

Consider the below example. Here inside promiseCleanRoom we generate a random number between 0 and 1. If the number is greater the 0.5, we send a resolve or else we send a reject.
Depending on the case either .then is executed or .catch is executed.

Below is the resolve case

 A callback function, also known as a higher-order function, is a function that is passed to another function as a parameter, and the callback function is executed inside the that Function.

Callback function are used everywhere in JavaScript. In JavaScript, functions are first-class citizens. They can be “stored in variables, passed as arguments to functions, created within functions, and returned from functions”.

Let’s look at the example below. Here we call function mainFunc with function “x” as argument and then from inside mainFunc, calling it after some console log.

When we use anonymous function inside our function call for callback like in the below code.

The in-built forEach, map, reduce, filter uses callback functions internally. Check the below example and here we are passing a function, just like above calc code.

Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result.
Now, in recursive function there are two parts. One is termination condition and other is the recursion itself.  The termination condition is very important or else the recursion never stops and goes into infinite loop. 

Let consider the below simple example to add numbers from the current passed number backwards till 1. Say we pass 3, then 3+2+1 = 6. In the below example If(n≤0) is the termination condition and return n + add(n-1); is the recursion. 

The recursion works as shown in the diagram below.
It works like loop, so the first call will go to recursion part and give “3 + add(2)”. 

Now the add(2) will be called and will be expended into “2 + add(1)”.
After that add(1) will be called and expanded into “1 + add(0)”. 

Finally the add(0) will trigger the termination condition If(n≤0) and produce 0.
After this everything will be added 3 + 2 + 1 + 0 to give 6.

 A Higher Order Function is a function that takes one or more function as argument. We use them at many places in JavaScript, and are also called callback functions.

Consider, the below JS code which uses filter to filter-out Adult people. Here, we have a callback function isAdult  which is called on every item.

These callbacks are usually defined inline as anonymous function. So, the refactored code is below.

 We can further refactor it using arrow functions as below.

So, the array methods of map(), filter(), reduce(), forEach() are all Higher Order Functions.

Beside this eventListener like below are also Higher Order Function, as they use a callback function.

Template Strings are also known as Template Literals. They are the new way to write Strings in JavaScript and been introduced in ES6. We can now write Stings using back-ticks(``), which have a special way to interpolate variables.

They are very useful in Expression interpolation and Multi-line strings. Although they don’t add any new feature to JavaScript, but they are a better visual way to write strings.

Expression interpolation
The old JavaScript way is quite cumbersome and we have to use many + operators to concatenate Strings, whereas with back-ticks we interpolate variable name using ${}.

Multi-line strings
The old way to have multiline strings is to have a newline(\n) inserted after where we want the next line.
Template strings provides a new way. You just go to the next line and the text will be displayed in next line.

Default parameters are the parameters, which are used if we don’t pass the value to that argument in a function while calling it.

Earlier to ES6, it was a bit difficult to handle a situation like this. In the below example if user didn’t supplied a value to argument , we check inside the function “add” if “a” has a value or assign 0 to it. Same is done for “b”. 

So, now we can handle all three situation successfully like when we pass no arguments, or pass only value of ‘a’ or pass only value of ‘b’.

The same can be done in ES6 by changing the parameter to contain the default value. Re-writing the above with ES6 default parameters.

Spread operators(…) were introduced in JavaScript in ES6 version. Just like plus(+) and minus(-) are operators, spread(…) is also an operator in JavaScript. Basically Spread operator spreads on demand. 

When you pass arguments to a function using Spread operators they are called Rest parameters.

Consider the below example for arrFunc. We can pass any number of arguments to a function and use the …arr to get it. Now inside the function the arr gets converted into and array. This functionality is quite similar to arguments object.

Now see the restFunc, here we are using rest parameter to get the remaining of the arguments. We can get argument a, b, c and then the rest is converted into array. 

The Spread operator can be use separately from function parameter and have some very useful use in array manipulation. They can now also be used with Objects.

Consider that we want to copy an array to other array. Now as you can see in the problem that when we assign variable y to x, we are referencing it and any changes to y will reflect in x. 

In the first solution, we use the new JavaScript method Object.assign() to copy all contents of “a” to an empty array and then assigning it to “b”.

But the better and simple solution is with Spread operator where we spread the array “c”, and take its content in an array.

Another use it that if we pass an array to build in functions, which expects normal arguments. Consider the below examples. 

We can also use Spread operator in Objects. So, by it we can do both clone and merge as shown in below example. Notice, that in mergedObj foo is “baz” as Object cannot have duplicate keys.

 Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. You can also handle nested structure by using nested destructuring syntax.

Object Destructuring
Consider the old way to assign variable to Object properties without destructuring.

Now we will refactor the above using “Object Destructuring”. Basically, you use an object literal on the left-hand-side of an assignment expression for object destructuring.

Nested Object Destructuring
If there is nested object as in below case, we can destructure it by adding it’s value to another object syntax 

Array Destructuring
Let’s first see how to do it without destructuring. Here we use the index to assign the variables.

 Array destructuring is similar to object destructuring, but here instead of keys you assign any variable.

Skipping Items
It is possible to skip items in array destructuring by omitting items with comma(,).

ES6 introduced the keyword class in JavaScript. But class in JavaScript is still different than those used in Object Oriented Programming languages like C++ and Java. The ES6 classes are nothing but synthetic sugar for constructor function and internally behaves exactly the same.

Consider the below example of Constructor function. Here we have a constructor function named “Mammal”. It have two properties of legs and name. It also have a function called walk(), which uses the legs and name property. We are creating an instance called person, which then is calling the walk function.

 The same can be written with ES6 classes with constructor, but it is exactly the same.

Async await help in allowing us to write completely synchronous-looking code while performing asynchronous tasks behind the scenes.

Async await are basically promises under the hood. But they have made the code for promises very easier to implement. If promises had simplified the code for callbacks, then async await have simplified the code for promises.

Let’s first check a nested promise example. Here we have three functions which return promises- cleanRoom, removeGarbage and winPizza. Now, when the cleanRoom function is run and resolve is returned from the promise, then the immediate .then block will be run . In the .then we are returning the next removeGarbage and in its .then we are returning the winPizza. We are passing the message from one function to other, so it will be appended.

We will refactored the code with async await. Here, instead of three functions we have one function cleaningTheRoom, which have a keyword “async” infront of it. It means that the function will have await statement(s). In the “await” we can have the value returned by a Promise stored in a variable. This type of code is much more cleaner then promise.

The Promise.all  method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

Let’s refactor the async await code from previous question to use Promise.all. Notice, that we are also using array destructuring at line 6, to receive all the values returned by the promise.

 We should use Promise.all in only cases like above, where the result of one Promise is not dependent on other promise.

 In Promises we handle any error or reject in the .catch block. Let’s look at the below example, where we are sending reject() from cleanroom(). So, now the error will be caught by the .catch block and then we are displaying the same in console log.

 

Now, when we refactor the above code using async-await, we don’t have any .catch block. So, we take help from the good old try…catch block available in JavaScript. 

Constructor functions are the equivalent of classes of traditional programming languages like C++ and Java. Sometimes people will refer to them as reference types, classes, data types, or simply constructors.  

If you aren’t familiar with classes, they are a construct that allows you to specify some properties and behaviours (functions), and multiple objects can be created with those properties and behaviours.  

A common analogy you’ll often hear is, a class is an architecture’s map and an object is a house created using it. Multiple houses can be created from a single map, as multiple objects can be created from a class.

Let’s start with creating a simple function using object to create employee objects.

 Now consider the line var newObj = {} and return newObj. They will be same in every function which we create. So, JavaScript gives us a special type of function known as Constructor function to create them.

We will refactor the above to use Constructor function. Look at the below code.

We are adding the keyword new to create the object. It basically takes care of the creation and returning of the newObj. But gives this a new name this.
Note, that we don’t need to put those two line in our code and automatically put by JavaScript engine.

We can also add methods to a Constructor function and then it can be called with any object created with new keyword.

Let us first consider the below code for normal Constructor function. Here we can directly access the variable “name” by person.name.
 Now, this might be not desirable at many places and in Traditional languages like C++ and Java, this is  solved by the having “private” variables in class and then having “Getters” and “Setters” to access them. 

Now, we implement the same in JavaScript using Closures. We have two closure functions setName and getName which are basically “setters” and “getters”. Now, the variable _name is private and cannot be accessed outside the function by person._name and we can access it only by person.getName() 

In JavaScript everything is an Object. So whenever we create an function, there is a one object which is created for that function. But actually there is another object which is created which is known as the Prototype object.
Now to access the Prototype object we have a reference on the function object also known as prototype. Notice the small “p”.

When we create an instance of the function with the new keyword interesting things happens. It create something known as __proto__. This is created by the JavaScript engine for every function call using the new keyword.

Now, let’s look how to create an function using prototype and the benefit of it. The below code have two function haveFun and drinkBreak. The function haveFun is an normal function inside the Constructor function. The function drinkBreak is created outside and added to the Prototype Object using it’s reference prototype.

Both the function seems to be doing the same thing, then what’s the benefit.
The benefit of declaring function using prototype is that it’s created once in the Prototype object. So, now whenever we create a new instance of the Constructor function the function is not created again. As in the below screenshot, you can see that emp1 and emp2 both have name and haveFun. But the drinkBreak is inside the __proto__, which is a reference to Prototype object.

Description

JavaScript is a scripting language for web development. It implements complex things like displaying timely content updates, interactive maps, etc. on a webpage, making the page more lively and interactive. It is widely used in Mobile application development and Game development. 
 
Over the last few years, JavaScript has taken over the web development world and became the primary language of choice for many new developers.  It’s not just because JavaScript provides a great way to make web pages interactive, but also because JavaScript developers have a great demand in the job market. According to the US Bureau of Labor Statistics, web developer jobs are targeted to grow by 20% in 2012-2022.

You need to be prepared with all the possible interview questions which could be asked in a JavaScript interview. 
But how can one crack a tricky JavaScript interview? How to answer the toughest of JavaScript interview questions? 
These are the questions that bother interviewees, beginners and freshers alike, more than the JavaScript interview questions themselves.
To relieve you of the worry and burden of preparation for your upcoming interviews, we have compiled the above JavaScript interview questions with answers prepared by industry experts.  These common interview questions on javascript will help you ace your Javascript Interview.
 

Read More
Levels