Frequently asked: JavaScript Interview Questions and Answers

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

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

Q3. 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 falseif any of them is in different type.

Q4. 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”.

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.

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

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

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.

Q7. 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,

  • Class — A class is a blueprint for an object. It tells us how the object has been constructed and what are all the properties and methods it will have. JavaScript actually does not have class mechanism but we can use functions to act as class which will construct on object when called with new keyword.
  • Encapsulation — Encapsulation means hiding the object properties from outside. This secure our internal functionalities and preventing from any unknown changes. JavaScript does not have private or access modifiers. But we can take advantage of the JavaScript lexical scope where a function’s variable is not accessible from outside.
  • Inheritance — This means an object can inherit methods and properties from a parent object. JavaScript is using different inheritance system where the parent object functionalities are not copied to the children object. But rather they are prototypically linked to their parent. So, we can still use the properties and functions that are not defined in the children object but declared in the parent.
  • Polymorphism — is the ability to create a variable, a function, or an object that has more than one form.

Q8. 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:

  • Attempt to assign a value to the variable when it is not declared. foo = "bar";, when foo was not declared with var.
  • Deleting a variable, a function, or an argument will result in an error.
  • Defining a property more than once in an object literal will cause an exception. var obj = { foo: true, foo: false };
  • Using eval and with statement is prohibited in strict mode and will throw error.
  • Any attempt to overwrite a freezed or sealed property in an object will throws error.

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

Q10. What is shift() and push? How they are differing from each other?

The shift() removes the first element from an array and return it. On the otherhand, unshift() adds the given element at the start of an array.

The push() adds the given element at the end of the array. And, pop() removes the last element from an array.

Q11. What is new operator in JavaScript?

The new operator is used to construct a user-defined object from a function. The this inside the function is set to the new object. So any assignments we are not with the this will be added as a property to this object.

If we explicitly return something inside the function, then the this binding will be ignored and an empty object will be assigned to the caller variable.

Q12. What is this keyword in JavaScript? Explain in details.

By simply saying, this refers to the object that is bind to the function at the runtime. To understand which object will be bound to the function, we should consider below situations:

Default binding: This happens when a function is invoked in stand alone.

When invoking the printNumber(), the system prints 5. Because, here this resolves to the global object window. So window.num yields 5 here.

Implicit binding: In this case, when the function has a context-object, this resolves to the owning object or containing object. The below example illustrates this.

When we call the object obj's printNumber method, obj.printNumber(), we will get 6. Because the obj is the this for the printNumber().

Explicit binding: By this way we are forcing a function to use an object to resolve the this. This can be achieved by using call and apply.

In the above code, we are invoking the printNumber function with call and explicitly binding the obj object to it. So the result will be 6.

The methods call and apply are identical, but they behave differently with their parameters. apply expects the parameters to be in array format, where callexpects separately.

new binding: The new binding is invoked when the function is invoked with new keyword. We are using new keyword in JavaScript to construct an object out of a function.

When we call a function with new keyword, a new object is constructed and set this newly constructed object to this in the function.

Final Note: this is referring the object to be bound for an executing function, but determining the object is based on from where and how the function was called. Other than this, ES6 arrow functions have lexical scope, in which they refer the enclosing function. Additionally, in event handlers the this is set to the element which fired the event.

Q13. When is JavaScript synchronous? And when is asynchronous?

JavaScript is always synchronous and single-threaded. If we are executing a block of code in JavaScript, then no other code will run at the given same time.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. In that case, JavaScript make the Ajax request and will run with other code and does not block the execution for return value. Upon the call returns a value, JS will run the callback and no other code will run at this point.

JavaScript’s setTimeout and setInterval also operates with this same kind of callback. So it's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.

jQuery Ajax has an options to make the calls synchronous. But this is problematics and allows to more traditional programming.

Q14. What are all the best practices for writing JavaScript Code? How do you write better code?

This has many different answers. Some of the best ways are:

  • Always initialize the variables before you use them.
  • Always use === equals instead of ==.
  • Wrapping code that could thrown errors at run time and feature-based code in try...catch block.
  • Don’t pollute global scope and don’t use global variables.
  • Always use "use strict";.
  • Use lint tools to validate JavaScript code and avoid any potential risks.
  • Wrap your code in an anonymous function or Immediately Invoked Function Expressions (IIFE), so that it will affect the global scope.
  • Give clear name for variables and functions.
  • Give comments wherever needed so that the other developer understands the code better.
  • Place all your scripts at end.
  • Reduce DOM manipulations and if you need to add large dom elements by script, use document.createDocumentFragment.

Q15. What is ECMAScript 6? What are the new features?

ECMAScript was created to standardize JavaScript. The latest standardized JavaScript version is called ECMAScript 6 also known as ECMAScript 2015.

ES6 includes the following new features:

  • arrow function
  • Template strings
  • rest and spread operators
  • Symbols data type
  • Promises
  • generators

Q16. What is Ajax?

AJAX stands for Asynchronous JavaScript And XML. AJAX’s most appealing characteristic is its “asynchronous” nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.

The two major features of AJAX allow you to do the following:

  • Make requests to the server without reloading the page
  • Receive and work with data from the server

Q17. What is Call Stack in JavaScript?

JavaScript’s functions forms a stack of frames. These are called Call Stack.

When we call bar, the first frame is created in the Call Stack with the functions arguments and local variables. The bar function calls foo from itself, which will create another frame and pushed to the top of the Call Stack. This stack also contains the foo's arguments and local variables. When foo returns a value or complete execution, it is removed from the Stack and when bar returns the Stack is empty.

For more Interview Questions and answer from JavaScript, React JS, TypeScript and Angular try our Android App: