Javascript Interview Questions | Part 1

Javascript Interview Questions | Part 1
Javascript Interview Questions | Part 1

Introduction  

Javascript is one of the most powerful and widely used programming languages on the web. It is a client-side scripting language which means that the source code is not just hosted on the webserver but can be processed by the client’s web browser.

It is used to create web applications and can be used to create 2D,3D animations and games. However, JS was initially designed to make web pages functional and was known as LiveScript. But since Java has been a popular language simultaneously, the creators renamed it to be JavaScript.

We have prepared the top 30 questions a developer must know before entering for a JavaScript Interview. You could too seek preparation, check out our 10 best JavaScript Certifications.

The below questions will help you crack your interviews and get your dream job.

Companies like Netflix, Capital One, Nagarro, and many more are now hiring JavaScript developers, and we have listed the top 30 questions asked by most of the companies during the interview.

Questions

Here are the top 30 questions asked in JavaScript Interviews, which are essential for every young developer. 

1. Difference between var and let keyword?

Answer: The var keyword is used to declare. The scope of this keyword is “function-scope,” which means that if a variable is declared using the var keyword, it could be accessed anywhere in the entire function or a program.

The ‘let ‘variable is also used to declare a new variable, but its scope is limited to a block, which means variables declared using the let keywords have block scope.

Let’s take an example to understand better: 

blog banner 1

The following examples take variables from the loop and display the result accordingly.

for (var a = 0; a < 5; a++) {
  console.log(a);
}
console.log(a);
Output : 

0
1
2
3
4
5

As the loop ended, we could still access the variable, and hence we can see 5 as the output in this scenario.

But if we try the same with “let” keyword :

for (let a = 0; a < 5; a++) {
  console.log(a);
}
console.log(a);
Output : 

0
1
2
3
4

file.js:4
console.log(a);
            ^

ReferenceError: a is not defined
    at Object.<anonymous> (HelloWorld.js:4:13)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
    at internal/main/run_main_module.js:17:11

The above code will result in an error saying that the variable was not defined, as the variable’s scope was just in the loop. While we were trying to access it after the loop ended, the variable had to be defined again.

2. What is Hoisting in Javascript? 

Answer: The declarations of variables or functions are by default moved at the top of the entire code, making sure they are accessible everywhere in the program. The assignment of the variables happens only when they are declared. This property is known as Hoisting. 

For example –

This image explains how the variables are used in Js.

Variables_used_in_Js
Variables used in Js

The first important step is to declare a variable using let/var. The second is to initialize it or assign any value to the variable, and the last is the final step to use the variable. 

To understand it better, let’s consider the following code snippet :

console.log(a);
var a = 5;

As the declaration and assignment are made after using the variable, we would get an Output as undefined.

 Output : 

undefined

But if we would have had the variable declared and assigned first, 

var a = 5;
console.log(a);
Output : 
5

We would get five as the Output because we made the declaration before using the variable. 

3. What is ECMAScript?

Answer: ECMAScript(European Computer Manufacturers Association Script) is a scripting programming language based on JavaScript and is widely used for the World Wide Web for client-side scripting. It is an object-oriented programming language and is considered a core programming language.

4. What is the key difference between “==” and “===” in Javascript?


Answer:

== (Equality Operator)=== (Identity Operator)
It converts the variable value to the same type before performing the comparison.
It follows type coercion.
It does not follow any type conversion and only returns true if both the values and types are identical for the variables in comparison.
It is less preferred than the Identical operator as it might give us unexpected results at times. It is widely preferred and gives us accurate results.

For example: “1” == true or “0” == false will give you true as the final answer.

It is more preferred over the Equality operator.

Let’s take an example to understand better : 

console.log(123==123);
console.log(123===123);
Output : 

true
true

In the above example, both operators were true as the final Output as it involved no type conversion. Hence, a simple equality condition has been checked for both of the cases. But let’s see if we try to compare a string value and an integer value now, 

console.log(123=="123");
console.log(123==="123");
Output : 

true
false

The above example shows that the double equals do not consider the change in data type and simply compare the variable’s value. In contrast, the triple equals compare the deals of the same data type. 

The double equals perform a type conversion and then compare the values. 


5. What is NaN in Javascript?

Answer: In Javascript, NaN stands for Not a Number. This property is used to check if the entered value is a valid number or not. NaN value gets generated when the value cannot be computed, or type conversion of the non-numeric value to the number is not a valid numeric.

For example, when we try to divide a 0 by 0. For any arithmetic operation in which one of the values is undefined Javascript returns NaN. 

Javascript
NaN

We will get a NaN value in the following given scenarios: 

1. If any one of the operands is an arithmetic operation is undefined 

2. When we try to divide a number by 0 

3. When we try to multiply zero with infinity 

4. When we divide infinity by infinity 

Let’s see an example to understand it better : 

var cn = 0/ 0;
console.log(cn);
Output : 

NaN

Javascript treats NaN like an actual number, which can be used to perform any number type operations.

6. What is asynchronous programming in Javascript? 

Answer: Asynchronous programming allows it to express waiting for long-running actions without freezing the program during these actions. JavaScript environments typically implement this programming style using callbacks, which are called when the actions are complete.

An event loop schedules such callbacks to be called when appropriate, one after the other, so their execution does not overlap.

7. What are the different iterable values in JavaScript?

Answer: The different types of inbuilt iterable values in Js are : 

  1. Arrays
  2. Strings
  3. Maps
  4. Sets
  5. DOM-based node lists

8. What will be the Output of 5+2+” 3″?

Answer: In Javascript, 

5 and 2 will be considered as integer values, and their sum will be 7 

But 3 is a string type variable,

So the final output will be the concatenation of both of these numbers leading the answer to be 73.

9. Is Javascript a case-sensitive language?

Answer: Yes, Javascript is a case-sensitive language. This means that the keywords,function-name, variable name all should be typed with a consistent capitalization of letters. The word let and LET will have different meanings in JS.So while using any variable or keyword, we should keep the case of the letters in mind.

10. What is the value of ans[0] in the below script?

const ans = ['jacket', 't-shirt'];
ans.length = 0;


ans[0]; // => ???

Answer: The length method used for arrays has a unique property that deletes the array values between the old and the new length. As the ans.length is set to 0, all the values in the array have been deleted. Hence the final answer is undefined. 

Ans[0] is undefined as the array has been emptied.

11. What is the difference between Object.freeze() and const? 

Answer: const applies only to the keywords and does not allow re-assigning a value to a const variable. 

Const variables cannot be redeclared or reassigned. The scope of a const variable is limited to block-scope. This means we cannot use a const variable declared in a block outside it. 

For example : 

{
const Pi = 3.14;
console.log(Pi);
}

// outside block
console.log(Pi); // error
Output :
 
3.14

Uncaught error: Pi is not defined

Object.freeze() : It is applied to the objects in Javascript. It freezes the objects, which does not allow any new properties to be rendered in them. It also prevents any modifications to the existing properties, attributes and values. 

For example : 

let ans ={
Pi = 3.14
};
Object.freeze(ans);
ans.Pi = 3.145;
console.log(ans.Pi); // 3.14, the value will not be modified.
Output : 

3.14


12. What are Promises in Javascript?

Answer: A promise is an object which represents the eventual completion of either completion or failure of an asynchronous function.

There are three states of the Promise object :

  1. Pending: which is the initial state (before the promise succeeds or fails
  2. Resolved: When a promise is successfully completed 
  3. Rejected: When a promise is rejected(failed)

It can be created using a constructor.

var promise = new Promise(function(resolve, reject){
    //add body to the function
});

13. What is currying in JavaScript?

Answer: Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions. It returns a new function that expects the next argument inline. It helps to avoid passing the same variable again and again, also in creating high order functions.

function addcn(a, b, c) {

    return a + b + c;
}

function addcn_curried(a)//curried function {

    return function (b) {
        return function (c) {
            return a + b + c
        }
    }
}

let res = addcn(1, 2, 3);
console.log(res);

let mc1 = addcn_curried(1);
let mc2 = mc1(2);
let res2 = mc2(3);
console.log(res2);

let res3 = addcn_curried(1)(2)(3);
console.log(res3);
Output : 


6
6
6

14. Define DOM in Javascript. 

Answer: Document Object Module (DOM) is not a part of Javascript, but it is a web API used to build websites. Using DOM, developers can create documents, navigate through them and modify, add accordingly to the document.

Document_Object_Module
Document Object Module



15. What is the Javascript Event Delegation Model?

Answer: Event delegation allows us to attach a single event listener to a parent element, which will work for all descendants matching a selector, whether those descendants exist now or are added in the future.                                   

16. How to empty an array in JavaScript?

Answer:

There are various methods to do so. Let’s discuss each one of them.

Suppose a[] = [1,2,3,4,5,6];

Method 1:

We can set the value of a [] = []; 

The above method assigns a new array to the variable a, deleting its previous values.

Method 2: 

We are aware of the JS array.length function, this function deletes the values of the array within a defined value.

We can empty an array ‘a’ by simply assigning, 

a.length = 0;

Method 3:

We can use a pop() method to delete all the elements of the array till the array.length is true.

while(a.length)
{
a.pop()
}

Method 4:

The splice method in array.splice(cuts) the array from a defined initial value till the final value.

It requires two parameters (initial, final) values from the user. 

In the above example, to delete all the elements of an array, we can write the following code,

a.splice(0,a.length);

17.How can you create a cookie using Javascript?

Answer: Cookies are data stored on your system and were invented so that the browser can remember a few details about the user. 

We can create a cookie by simply assigning a string value to document.cookie object. 

We can not only create but read, delete cookies using this document. cookie property.

We can create Javascript Cookies using :

document.cookie = "Coding Ninjas";

18. Name a few Javascript frameworks.

Answer: Best Javascript frameworks to use today are :

  1. Angular
  2. React
  3. Vue.Js
  4. ember.Js
  5. Meteor

19. What is Strict mode in JS?

Answer: It is a stricter or secured version of ordinary javascript language that produces errors for those mistakes handled silently otherwise. It was introduced in ECMAScript 5.

For example : 

In normal Js, if we try to run the below commands 

a=10;
console.log(a);

We will not get an error as the compiler would by default consider ‘a’ as a ‘var’ data type.

But if we use strict Js, we would get an error if we try to run the above code stating a is not defined.

20. What is the difference between a null, undefined, and undeclared variable in Javascript?

Answer: We can assign null as a value to any variable.

A variable is said to be undefined when its value is yet to be assigned.(empty variable)

A variable is said to be undeclared when it is not assigned any data type. When a variable is not even declared and used, the compiler will give us an error stating that the variable is not defined.

For example ,

var a = null; // null is assigned to a variable
var b;
console.log(b);// b does not hold any value
console.log(c);//c is not declared
Output:

null
undefined

HelloWorld.js:5
console.log(c);//c is not declared 
            ^

ReferenceError: c is not defined
    at Object.<anonymous> (HelloWorld.js:5:13)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
    at internal/main/run_main_module.js:17:11

21. Explain array.slice and array.splice in Js

Answer:

1) The slice() method copies a given part of the array and returns it. It does not modify the original array.

array.slice(inital,final) 

2) Array.splice method is used to remove the items of the selected array and does not form another array. This method modifies the original array. Array.splice can be used to add or remove elements from the array. 

22. Determine the Output of the following code.

var courses = ["JavaScript","Java","C","C++","Python"];
delete courses[2];
console.log(courses.length);

Answer: The delete function does not affect the array’s length as the operator deletes only the value present at the given position. 

Hence the Output would be 5. 

We will have an empty value in the ‘C’ course in the array courses.

23. What are IIFEs?

Answer: Immediately Invoked Function Expressions are also called Self Executing Anonymous Functions, executed immediately after their definition.

It contains two major parts :

  1. The first is the anonymous function in the given scope enclosed within ‘()’
  2. The second part is the immediately invoked function expression through which the Js interpreter will directly interpret the function.

24. What are ArrayBuffers?

Answer: ArrayBuffers is a data type used to store a generic, fixed-length binary data buffer. We cannot directly modify the contents of an ArrayBuffer, but we can create a typed view or a DataView, that is used to read or write the contents of the buffer.

let buffer = new ArrayBuffer(16);

The above statement creates a buffer of a fixed length of 16 bytes. 

25. What is Callback hell?

Answer: Callback hell is also known as the Pyramid of Doom. It is an anti-pattern of multiple nested callbacks, making it difficult to read or debug the code. It is a slang term used to define multiply nested if statements or functions.

async1(function() {
    async2(function() {
        async3(function() {
            async4(function() {
                ....
            });
        });
    });
});

26.What is the difference between a window and a document?

Answer: The window is the first thing that gets loaded into the browser. This window object has most properties like length, innerWidth, innerHeight, name if it has been closed, its parents, and more. The window object refers to the browser window.

The document object is your HTML, ASPX, PHP, or another document that will load into the browser. The document gets loaded inside the window object and has properties like title, URL, cookie, etc.

27. Explain Arrow functions. 

Answer: Arrow Functions are a new concept of ES, as they allow us to create smaller and cleaner functions. 

For example : 

let a = function(a,b){
  return a +b ;
}

We can write the above function as, 

// using arrow functions
let a = (a, b) => a * b;

28. What is the Output?

console.log(typeof typeof 1);

Answer: typeof method returns the data type of the given variable. 

Here, typeof 1 will return ‘number’

typeof’ number’ will return a string.

The answer is String. 

29. What is a WeakMap in Javascript?

Answer: In a WeakMap, the keys are objects instead of primitive values. It is known as a directory where all the keys are weak. Weak maps provide a way to extend objects without interfering with garbage collection.

30. What are the limitations of Javascript?

Answer:

  1. It cannot write files on the server.
  2. Due to security reasons, every web browser provides an option to disable javascript.
  3. Developers cannot use it for network applications.
  4. We need AJAX and a server-side script to access Databases
  5. It is not engine-friendly.
  6. It cannot access web pages hosted on different domains. 

Key Takeaways

This article discussed the most asked Javascript Interview questions for freshers and experienced developers.

The article covered the most heated topics in Javascript. More such questions will be discussed in the upcoming blogs.

You can take a look at this blog to know about the 10 Most Asked JavaScript Interview Questions and Answers.

Happy learning!