Frequently asked - JavaScript Interview Questions and Answers - Part 01
August 25, 202410 min read

Frequently asked - JavaScript Interview Questions and Answers - Part 01

JavaScriptInterview QuestionFrequently asked
share this article on

1. What are the differences between null and undefined?

In JavaScript, undefined means, the value of the variable is not yet defined. And typeof undefined is also “undefined”. We are getting undefined in JavaScript in some ways, like: declaring a variable without assigning any value to it, store a function return value to a variable but the function does not return anything, return statement does not return any values, a function parameter does not passed and the global variable undefined.

null means empty or non-existent value which is used to indicate “no value”. Even though typeof null returns object, null is primitive type and not an object.

2. How can you manipulate the DOM using JavaScript?

The document represents the web page loaded in the browser and it is an entry point to the page content.

This provides a powerful API to interact with the DOM like getElementsById, getElementsByClassName, getElementsByTagName, and querySelector. Through this, we can select one or group of elements and manipulate them.

3. What is the difference between getElementsById, querySelector or querySelectorAll?

getElementsById returns a single element that matches the id. Since id is an unique value, we cannot select more than one element. If there is no element with the given id, then this function returns null.

querySelector can process complex selectors like combination of elements, id, class and children nodes. It returns one element only even though the selector matches many.

querySelectorAll is same like querySelector, but this will return all the matching elements in the document.

4. What are the differences between == and ===?

The == will not check the type of the operands whereas === checks both type and value of the operands.

Other way of saying is, == will convert the operands to same type and then do the comparison. But === does not do any conversion. It will simply return false if any of them is in different type.

5. How can you check if the given variable is array or not?

We can use Array.isArray() to determine whether the passed value is an Array or not. However it will not run on IE8 and below. To support the old versions we can use, Object.prototype.toString.call(arr) === '[object Array]';

6. What are all the data types JavaScript supports?

JavaScript offers seven data types which are: Number, String, Boolean, null, undefined, Symbol (newly added in ECMAScipt 6) and Object.

7. What is variable hoisting in JavaScript? Give an example.

In JavaScript, variable declarations, wherever they occur, are processed before any code is executed. Declaring a variable anywhere in the code is equivalent to declaring it at the top. But the assignment happens at exactly where they are. This behavior is called “hoisting”.

console.log(num);
var num = 6;

When this script runs it will print undefined. This is because even though the variable is declared after the console.log, it will originally be declared before that. But the assignment will be done after the console.log. So it will simply print undefined.

8. How can you remove an element from an array? Or can you use delete to remove an element in an array or not?

First, we should not use delete to remove an element from an array. Because, delete removes only the value of the array element, not the entire element. So the index still have undefined. And the length does not change. delete is supposed to use on an Object to remove its property.

The best way to remove an element is using splice method. The syntax is: arr.splice(startIndex, deleteCount, itemToInser); and [1, 2, 3].splice(1, 1); result in [1, 3].

9. What is pass by value and pass by reference? Explain.

Those are referring how JavaScript handles the parameters we are passing into a function. When passing in a primitive type variable like a string, a boolean or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function.

Passing in an object or an array, however, passes it in by reference. In this case, any changes to this will affect the element and modify it.

10. What is Scope of variable? What is Global scope and Local scope?

Scope means a set of rules to the compiler to look for a variable in the program or how the parser resolves the value of a variable.

In JavaScript, we have two kinds of scopes: Local and Global. If we have created a variable outside a function it is a global variable and can access from anywhere in our program. A variable declared inside a function has local scope. And they can be accessed from within the function, but not from outside of it.

11. What are all the types of function? Or what are all the different ways you can declare a function and how they differ?

There are mainly three ways, we could define a function:

Function declaration: This is the straight-forward method. It uses a function keyword followed by the name of the function, list of parameters and a pair of curly braces to define function body. This type of definition is hoisted, means this block will be lifted up to the top of the scope and can be invoked before the declaration.

function isEven(num)
return num % 2 === 0;
}

Function expression or function assignment: In this way, we are declaring a function with or without a name and assign to a variable. This type of function is not hoisted means you cannot call this function before they are declaration happens.

var isEven = function(num) 
return num % 2 === 0;
};

Anonymous function: Anonymous functions are unnamed functions and run immediately. The function is executed as soon as the declaration happens. And you won’t call it again because there are no name. They are widely used to wrap our code in a closure and not affecting the outer scope.

(function(num) 
return num % 2 === 0;
})(2);

Or, the below is also the same.

(function(num) 
return num % 2 === 0;
}(2));

Other than these three methods, JavaScript has Function constructor which has the syntax of var isEven = new Function(arg1, arg2, 'return num % 2 === 0');. This is not used much because it does not have access to the current scope and always created in the global scope.

And finally we have Arrow functions and Generator functions which are newly added in ECMAScript 6.

12. What is Closure in JavaScript? What is it uses? Explain by example.

Closure in JavaScript means an inner function have access to the variables that are defined in the outer function. In JavaScript, the inner function remembers the environment in which they were created.

Whenever we are declaring a function inside another function we are actually creating closures.

function makeFunc() 
var name = 'Javascript';<br/>function displayName() 
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();

Running the above code results in displaying an alert box with the string ‘Javascript’. When running the outer function makeFunc, it completes its execution and returns the inner function. Then later, when we run the inner function displayName, it displays the alert box, even though the outer function has already finished its execution. The reason is the inner function still remembers the outer functions scope (i.e., variable name) and when executing later it displays the correct name. This is also an example for how closures work in JavaScript.

Closures have important role in callbacks and asynchronous programming. The famous nodejs, server side JavaScript environment relies heavily on closures and events.

13. What is OOP concept? How will you implement it in JavaScript?

OOP means Object Oriented Programming. The basic idea of OOP is that we use objects to model our data and provide a simple way of providing functionalities that would be easy to use. And we use objects as building blocks of our application.

OOPs concept provides some techniques namely,

14. What is prototype in Object? And what is constructor in Object?

JavaScript can be described as prototype-based language. Each object has prototype object which inherits methods and properties from another object.

Every function has a prototype property whose value is an object containing a constructor property. This constructor property points to the original constructor function.

15. What is strict mode in JavaScript?

Strict Mode is a new feature added in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This strict context prevents certain actions and throws more exceptions.

To enable a strict mode, just place "use strict"; at the start of the file or function. Since the syntax is simply a string, we won’t have any side effects in older versions.

It will throw errors in the following scenarios:

16. How to seal or freeze an object? How can you prevent an object from being overwritten? How to create immutable objects in JavaScript? What is immutable objects?

An immutable object is an object whose state or properties can not be changed after it is created.

Seal an Object: The Object.seal() method seals an object, and preventing new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable. Example:

var obj =  foo: "bar" };
Object.seal(obj);
obj.baz = "bar"; // This new property will not be added since the object is sealed.
Object.isSealed(obj) //true. Object is sealed now.
obj.foo = "baz" //obj.foo = baz. But you can still modify the existing properties.

Make a object property immutable: The Object.defineProperty allows addition of new property as well as configure it. Example:

var anObj = }; //Create an empty object
Object.defineProperty(anObj, 'myName',
enumerable:   false,   // cannot be shown in for loops or Object.keys();
configurable: false,   // cannot be deleted using delete.
writable:     false    // cannot be changed after this.value: 'Javascript'
});

Object.keys(anObj); //can not be enumerable
delete anObj.myName; //cannot deleted or configurable
anObj.myName = 'JS'; //cannot writable also

Object.freeze(): The Object.freeze() method freezes an object. We can not add new properties and we can not even change the existing properties as well.

var another =  name: 'myName' };
Object.freeze(another); //freezes an object.
Object.isFrozen(another); //true.
another.age = 22; //Not added. Fails silently or throw error in strict mode.
another.name = 'anotherName'; //can not be changed. Fails silently or throw error in strict mode.

17. How can you get the list of all properties in an Object?

The easy way is using Object.keys(). This will return an array of given object’s own enumerable properties.

If we want all properties, even not-enumerable properties also, we can use Object.getOwnPropertyNames().

18. What are events? And how they are handled in JavaScript?

Events are the beating heart of any JavaScript application. Without events there are no scripts. Because JavaScript is meant to add interactivity to the pages.

When the user does something or something happens in the page an event takes place. For example, load event or when the user types something in an input field. In JavaScript, we are attaching the event handlers to certain HTML elements or browser events. This will wait unitl a certain event takes place. When it happens, it handles the event by executing the JavaScript function that we have passed to it.

19. What is Event capturing and Event bubbling?

It defines in which order the event handler should be executed. For example, consider an element which has click event attached, and its parent also has the same event handler attached to it. Now if the children has been clicked, then:

Simply saying, the Event capturing is capturing the event handlers in top-down direction and Event bubbling is capturing the event handlers in bottom-top directions.

We can define which mode should be followed. In the EventListener syntax add the third parameter as true or false. The default value is false and the default execution phase is bubbling.

element.addEventListener('click', doSomething, true) //Event handler is set to capturing phase.
element.addEventListener('click', doSomething, false) //Event handler is set to bubbling phase.

20. What does async and defer attributes do? Why they are used in the script tag?

By default, when the script tag is executed in the browser, it will stop parsing the HTML and getting the script. The parsing will not be resumed until the script is received and validated.

When using async in <script> tag as <script async>, the browser will download the file and do the HTML parsing at the same time. Once the download completed, it will pause the HTML execution and run the script.

Now if we use defer as <script defer>, the browser downloads the script during the HTML parsing, but only execute the script after the parser has completed.

IE9 and below have some bugs in their implementation of defer such that the execution order isn’t guaranteed.


  1. Javasript Interview question and answers - Part 02
  2. Javasript Interview question and answers - Part 03
Back to Articles