JavaScript Interview Questions

1. What is JavaScript?

JavaScript is a client-side as well as server side scripting language that can be inserted into HTML pages and is understood by web browsers. JavaScript is also an Object based Programming language.


2. What is differences between Java and JavaScript?

Java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all inter-dependent and are designed for the different intent.  Java is an object – oriented programming (OOPS) or structured programming language like C++ or C whereas JavaScript is a client-side scripting language.


3. What is DOM? What is the use of document object?

DOM stands for Document Object Model. A document object represent the html document. When the browser renders the html page, It creates document object representing the html document which can be used to access and change the content of html.


4. What is the difference between == and ===?

The == operator checks equality only whereas === checks equality and data type i.e. value must be of same type.

 
let a = 10;
let b = "10";
console.log(a == b); // It will console true since the values of x and y is the equal.
 
console.log(a === b); // It will console false because the values of x and y is the equal but data type is different.
 

 


5. What are undeclared and undefined variables?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.


6. What are global variables? How are these variable declared?

Global variables are those that are available throughout the length of the code, that is, these have no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.

Example:

// Declare a global globalVariable = “Test”;

The problems that are faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.


7. What is Hoisting in JavaScript?

Javascript uses the concept of hoisting, It is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.It means  no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. Let's understand it with few examples how the code actually executes when using using variable, function declarations at the bottom:

Example 1

a = 15;

console.log(a);

var a;

 

The above code prints 15 in console, Because due to hoisting variable initialization moved to top.

Example 2

printMsg();

function printMsg(){

  console.log(" This is the message");

}

 
The above code prints the meesage over console without any warning, error due to hoisting of function declaration.
 
As mentioned in the definitiona of Hoisting, It works in both scope local as well as global, Below code will also work.

printMsg();

function printMsg(){

  a = 10;

  console.log(a);

  var a;

}

 
Above code will output 10.
 
Note 1. let  and const introduced in ES6 do not support hoisting anyway, See below example
 
a =10;
console.log(a);
let a;
 
The above code will output Uncaught ReferenceError: Cannot access 'a' before initialization at <anonymous>:1:3
 
Note 2. Only variable declarations are hoisted not the variable initializations.
 

console.log(num); // Returns undefined, as only declaration was hoisted, no initialization has happened at this stage
var num; // Declaration
num = 6; // Initialization

 
Note 3.To avoid hoisting, run javascript in strict mode by using “use strict” on top of the code.


8. How to write a comment in JavaScript?

We can write comments in JavaScript with below 2 ways:

Single Line Comment: It is represented by // (double forward slash)

// for Single line comments

 

Multi-Line Comment: Slash represents it with asterisk symbol as /* ... */

/* This is first line coment

This is second line comment.

....

*/


9. What are the different data types available in JavaScript?

In JavaScript, All the availalbe data types area categorised into two categories.

1. Primitive Data Types: Data type which is not an object and has no methods.The primitive data types are as follows:

Data Type Description
Number

It can be an integer, a floating point value, an exponential value, e.g.,

let a=250;  // an integer value

let b=25.5;  // a number containing a decimal

let c = 10e4 //  an exponential value which evaluates to 10*10000;

String

It can be group of characters enclosed by a single or double-quotes or by backticks, e.g.,

var str = “This is a string”;

Boolean It represents boolean value either true or false
Undefined It represents an undefined value
Null It represents null, which mean there no value

 

2. Non-primitive Data Types: These are the data types which if mostly of Object type. The non-primitive data types are as follows:

Date Type Description
Object represents an instance through which we can access members
Array represents a group of similar values
Function This is not a data type in JavaScript, But when we check the type of any function then we see Object.

 


10. What is the difference between Undefined and Null?

Both are data types of JavaScript.

  • Undefined: When a variable is only declared but not assigned any value in it then it is of Undefined data type.
  • Null: When any variable is assigned null value in it then it means there is no value in it. The same approach is used in Mysql tables where we set default value of any field as NULL.

 


11. What are the different ways to create objects in JavaScript?

Below are the common ways by which Objects can be created in JavaScript:

1.By object literal: This is most shortest way to create object in JavaScript.

Example: const user = {name:"Alax",age:25} ;

2. By Function constructor: Here we define a function and create object of that function.

function Greet(name, age){
  this.name=name;  
  this.age = age;  
}
var object = new Greet("Rohit",25);

 

3. By Object constructor:

const user = new Object();

user.name="Aman";  

user.age=25;

 


12. What is a Cookie?

It's peace of information which is stored on users local machine when any website is visited. It is stored by the web browser when any website is visited. It is mainly stored in name-value pair separated with semi-colon.

Cookie can be creted like below:

document.cookie = "uid=142987561";

 

Read the cookie with JavaScript

const x = document.cookie;


13. What is the use of a Cookie?

Website uses the Cookie to streamline the user experience when a user is visitiing same website frequently. Very common reasons to use cookie are:

  1.  Session management: cookies helps the website to recognize users and recall their stored information and preferences like user id, user first name, user last name.
  2. Personalization: Websites uses cookies to show you the customized ads as per your preferances.
  3. Tracking: E-commerce sites uses your recent searches and accordingly suggests you items that user may interested to buy.

 


14. How can we delete a Cookie in JavaScript?

Different ways to delete a Cookie:

  • Using expire attribute  (document.cookie="name=Martin Roy;  expires=Sun, 20 Aug 2000 12:00:00 UTC")
  • Using max-age attribute (document.cookie="name=Martin Roy;max-age=0")
  • Using a web browser (Go to history through menu of the Browser)


15. What are the differences between cookie, local storage and session storage

Cookie localStorage sessionStorage
Lifetime:As configured using Expires option until deleted until tab is closed or deleted
SSL support: Supported Not Supported Not Supported
Maximum data size: 4KB 5MB 5MB
Accessed: Both client-side & server-side only Client side Only Client side

 


16. What is localStorage in JavaScript?

localStorage is a property which allows JavaScript web application/sites to store key/value pairs data in a web browser without expiration date. The data stored in the web browser will stay even after the browser window is closed.


17. What are the methods available on localStorage in JavaScript?

There are mainly 5 methods available which are:

  1. localStorage.setItem(): It adds key and value to localStorage
  2. localStorage.getItem(): It is used to get items from localStorage
  3. localStorage.removeItem(): It removes an item by key from localStorage
  4. localStorage.clear(): It clears all the data saved in localStorage
  5. localStorage.key(): It is used to retrieve the key of a localStorage


18. What is the use of a constructor functions in javaScript?

As we know this is also a type to create new object in JavaScript. But if we talk about the reusability then it is most used way of creating object because if it is needed to create multiple objects with similar properties and function then this approach is used.

Example:


function Student(name,age,marks){
  this.name = name;
  this.age = age;
  this.marks = marks;
}


const student1 = new User("Alax", 76, 90);
console.log(student1);

var student2 = new Person("John", 34, 97);
console.log(student2);

 

With the above approach, Any number of object can be created of type Student.

 


19. What is the use of a strict mode in JavaScript?

The use of "use strict" is to indicate that the code should be executed in "strict mode". Strict mode changes some previously-accepted mistakes into errors.

Without "use strict"

a=10;    

console.log(a); // Output: 10

 

with "use strict"

"use strict";    

a=10;    

console.log(a);  // Output: Uncaught ReferenceError: a is not defined


20. What is the difference between null and undefined

Null Undefined
It is the value assigned to a variable which means the variable has no value in it. Any variable retruns undefined when variable is declared but any value is not assigned in it.
It's type is Object It's type is undefined
While performing primitive operations, It converts to zero While performing primitive operations, It converts to NaN

 


21. What is eval() function?

This function mainly evaluates JavaScript code represented as a string, Which can be a JavaScript expression, variable, statement, or sequence of statements.

Example:

eval('2 + 2'); // returns 4


22. What is BOM?

The Browser Object Model also known as BOM allows JavaScript to "talk to" the browser. There are no official standards for the Browser Object Model (BOM), It can behave defferently based on different browsers.. It consists of the objects navigator, history, screen, location and document which are children of the window.


23. Explain Window Object?

The Window Object is used to control the browser window lifecycle and perform various operations on it. The window object is supported by all browsers. It represents the browser's window.

All global JavaScript objects, functions, and variables automatically become members of the window object. Document object is a property of the window object. See example below:

// Both are same

window.document.getElementById("p1");

document.getElementById("p1");


24. Explain Documet Object?

The document object represents the whole html document. In the browser when html document is loaded, it becomes a document object. It is the root element of the loaded html document. It is part/child of window object.


25. What is the difference between window and document?

Window Document
It is the root level element in any window over browser Also known as Document Object Model(DOM), is the direct child of the window object
alert(), confirm() and properties like document, location are the methods available in this object getElementById, getElementByTagName, createElement etc are the methods available in it
window object is available implicitly in the page It can accessed via window.document or document.

 


26. What is the use of history in javascript?

The window.history object contains the browser's history.Previous and next URLs can loaded in the history using window.history.back() and window.history.forward() methods.

 


27. What is the use of Void(0)?

Used to prevent the page from refreshing it and parameter "zero" is passed while calling. Void(0) is used to call another method without refreshing the page.


28. What are global variables?

Global variables are the variable that are available throughout the entire code of the script without any scope. To declare JavaScript global variables inside function, you need to use window object i.e., window.value=90


29. How to submit a form using JavaScript?

The form can be submitted using below ways in JavaScript:

  • document.getElementById("myForm").submit();
  • document.form[0].submit()


30. Is JavaScript a compiled or interpreted language?

JavaScript is an interpreted language, not a compiled language. Programing languages such as C++ or Java needs to be compiled before it is run. The browser's interpreter reads the complete JavaScript code, interprets each line, and runs it. But these days modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.


31. What is tree shaking?

Tree shaking is a form of dead code elimination. It used to reduce the bundle size of any application. For Example, While working with Angular we install many packages in the application but while creating its bundle tree shaking helps to pick only few part of that packages from node_modules which have been used in our code. Tree shaking is implemented in Rollup and Webpack bundlers.


32. What is a Pure function?

Pure function always returns the same result if the same arguments passed in it. It does not change on external changes like any state, or data, changes during the program execution. It only depends on the arguments. Also it not produces any observable related effects such as network requests, data mutation, etc.


33. What are Arrow functions?

Arrow functions were introduced in ES6. An arrow function expression is a shorter way to define a function, but is limited and can't be used in all situations. It does not have its own scope or this, It receives the scope of the context where it is defined.

// before 

hello = function() {
  return "Hello World!";

// with ES6

hello = () => {
  return "Hello World!";
}


34. What is ECMAScript?

ECMAScript (or ES) is a general-purpose programming language, JavaScript is a subset of ECMAScript. It is a JavaScript standard meant to ensure the interoperability of Web pages across different Web browsers.


35. What is the benefit of using let keyword?

The let statement declares a block-scoped local variable, Which means if any variable is declared in any if block then it is only accessible inside that block only. Earlier when any variable was declared using the var keyword then its scope was function level. With the help of let we can have a variable with multiple values as per their scope.

let a = 100;
if (condition===true) {
  let a = 120;
  console.log(a); // Output: 120
}
console.log(a); // Outpur: 100 


36. What is the difference between let and var keywords?

let

  • It has scope inside the block
  • Introduced as part of ES6
  • Hoisted but not initialized

var

  • It has scope inside the function
  • It is available from the beginning of JavaScript
  • Variables are hoisted


37. What are closures?

A closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. It is combination of a function and the lexical environment within which that function was declared.

 

function user(message) {
  function greetUser() { // greetUser() is the inner function, a closure
    console.log(message+' '+name); // message variable declared in the parent function
  }
  return greetUser();
}
let func = user();

func('Hello');

func('Good morning');

 

As per the above code, the inner function(greetUser) has access to the variables in the outer function scope(user) due to closure in javascript.


38. What is a Web Worker?

When scripts executes in an HTML page, the page becomes unresponsive until the script is finished.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.


39. Is JavaScript a case-sensitive language?

Yes, JavaScript is a case sensitive language.


40. Who developed JavaScript?

JavaScript was developed by Netscape, in collaboration with Sun Microsystems. Before JavaScript, web browsers were fairly basic pieces of software capable of displaying hypertext documents. JavaScript was later introduced to add some extra spice to web pages and to make them more interactive. The first version, JavaScript 1.0, debuted in Netscape Navigator 2 in 1995


41. What is the use of preventDefault method?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when:

Clicking on a link, prevent the link from following the URL

Clicking on a "Submit" button, prevent it from submitting a form


42. What is the use of setTimeout?

This method is used to call a function or evaluate an expression after a specified number of milliseconds. For example, Want to show any alert or hide any error message after 2 seconds using setTimeout method,

setTimeout(function(){ alert("Request sent to server"); }, 2000);


43. What is the use of setInterval?

This method is used to perform any task or call any function after a fixed interval. Want to show message in every 5 seconds, the it can be done like beow:

setInterval(function(){ console.log("Hello World!"); }, 5000);


44. What do you mean by Progressive web applications (PWAs)?

Progressive Web Apps are web apps that use emerging web browser APIs and features along with traditional progressive enhancement strategy to bring a native app-like user experience to cross-platform web applications.

A Progressive web application should have the following features:

Secure contexts (HTTPS): The web application must be served over a secure network

Service workers: A service worker is a script that allows intercepting and control of how a web browser handles its network requests and asset caching. With service workers, web developers can create reliably fast web pages and offline experiences.

Manifest file: A JSON file that controls how your app appears to the user and ensures that progressive web apps are discoverable. It describes the name of the app, the start URL, icons, and all of the other details necessary to transform the website into an app-like format.


45. what are the tools/techniques you use for debugging JavaScript code?

  • Browser Devtools
  • debugger statement
  • Good old console.log statement


46. How can we get query string values in JavaScript?

Let's say the URL is https://jsonworld.com/javascript-articles?page=4 and we want the value of 4 then below code can be used.

const urlParams = new URLSearchParams(window.location.search);
const page = urlParams.get('page'); 

console.log(page); // Output: 4


47. What is difference between Parameters and Arguments?

  • Function parameters are the names listed in the function's definition.
  • Function arguments are the real values passed to the function.
  • Parameters are initialized to the values of the arguments supplied.


48. What is a polyfill in JavaScript?

A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.

For example, a polyfill could be used to mimic the functionality of a text-shadow in Internet Explorer 7(ID7) using proprietary IE filters, or mimic rem units or media queries by using JavaScript to dynamically adjust the styling as appropriate, or whatever else you require.


49. What is an anonymous function?

The anonymous function is a function that is without a name. These functions are mainly assigned to a variable name or used as a callback function. For example,

const greetUser = function(){ //Anonymous function assigned to a variable
  //do something
};

['a','b','c'].map(function(element){ //Anonymous function used as a callback function
  //do something
});


50. What is TypeScript?

TypeScript is an open-source language that builds on JavaScript, one of the world’s most used tools, by adding static type definitions. Developers working on bigger projects are recommended to use TypeScript over JavaScript.


51. What are the differences between JavaScript and TypeScript?

Key Differences:

  • Language paradigm: TypeScipt is an Object-oriented programming language and superset of JavaScript but JavaScript is a Scripting language.
  • Typing Support: TypeScript Supports static typing whereas JavaScript supports dynamic typing.
  • Compilation: Typescript code needs to be compiled while JavaScript code doesn’t need to compile.
  • Prototyping: Typescript supports a feature of prototyping while JavaScript doesn't support this feature.
  • Project type: Typescript is a powerful type system, including generics & JS features for large size project whereas JavaScript is an ideal option for small size project.


52. What is a prompt box?

A prompt box is a box which allows the user to enter input by providing a text box. Label and box will be provided to enter the text or number.


53. What is this keyword in JavaScript?

In Simple we can say, 'This' keyword refers to the object from where it was called.


54. How can the style/class of an element be changed using DOM?

It can be done like below:

// Change Style

document.getElementById("p").style.fontSize = "16";

// Change Class

document.getElementById("myText").className = "form-style";


55. What are the different types of Pop up boxes available in JavaScript?

  • Alert
  • Confirm
  • Prompt


56. Which keywords are used to handle exceptions in JavaScript?

We can use 'Try… Catch---finally' to handle exceptions in the JavaScript.

Try{
  Write your Code here
}
Catch(exp){
    Write your Code to throw an exception
}
Finally{
    Code runs either it finishes successfully or after catch
}


57. Which keyword is used to print the text in the screen?

document.write("Hello World!") is used to print the text – 'Hello World!' in the screen.


58. Explain window.onload and onDocumentReady?

The onload function do not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.

onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.


59. What is web storage?

Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user's browser, in a much more intuitive fashion than using cookies. Web storage provides two mechanisms for storing data on the client.

Local storage: It stores data for current origin with no expiration date.

Session storage: It stores data for one session and the data is lost when the browser tab is closed.


60. Define event bubbling?

JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child is clicked, the handler of parent will also work as if it were clicked too.


61. What keyword do you need to use to insert a debug breakpoint?

debugger


62. What is an event?

An event is an action that a user or system may trigger, such as pressing a key, a mouse click, etc.