Javascript Interview Questions and Answers

Are you preparing for a JavaScript interview? Look no further! This comprehensive guide covers the most common and crucial JavaScript interview questions you’re likely to encounter. From basic concepts to advanced topics, we’ve got you covered. Boost your confidence and increase your chances of landing that dream job with our expertly curated list of JavaScript interview questions.

1. What is JavaScript?

JavaScript is a high-level, interpreted programming language used to create interactive and dynamic web content. It is a versatile, lightweight, and event-driven language that can run on both the client and server sides.

console.log("Hello,Javascript!");

2. What are the data types supported by JavaScript?

JavaScript supports the following data types:

  • Primitive Types: String, Number, BigInt, Boolean, Undefined, Null, Symbol.
  • Non-Primitive Types: Object (including arrays, functions).
let num=42;
let name=True
let isstudent="siva"
let undef;
let obj={key:"value"};

3. What is the difference between let, const, and var?

  • var: Function-scoped, allows redeclaration, hoisted with undefined.
  • let: Block-scoped, no redeclaration, hoisted but not initialized.
  • const: Block-scoped, no redeclaration, and must be initialized during declaration.

4. Explain how == and === differ.

  • == checks for value equality with type coercion.
  • === checks for strict equality without type coercion

5.What is a closure?

A closure is a function that retains access to its outer scope variables even after the outer function has executed.

function outer(){
let count=0;
return function inner(){
count++;
return count;
};
}
const counter=outer();
console.log(counter());
console.log(counter());

6. What is hoisting?

Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope during compilation.

7.Explain the concept of this in JavaScript.

this refers to the context in which a function is executed. Its value depends on how the function is called.

const obj={
name:"siva",
greet(){
console.log(this.name);
},
};
obj.greet();

8. What are JavaScript prototypes?

Prototypes allow objects to inherit properties and methods from other objects.

function person(name){
this.name=name;
}
Person.prototype.greet=function () {
return `hello, ${this.name};
};
const person=new person("siva");
console.log(Person.greet());

9.What is the difference between null and undefined?

  • null: : A deliberate non-value.
  • undefined: A variable declared but not assigned a value.
let x=null; let y; console.log(x); console.log(y);

10.How does JavaScript handle asynchronous operations?

JavaScript uses the event loop with callbacks, promises, and async/await for asynchronous operations.

Example: using a callback

function fetchdata(callback){
settimeout(()=>{
callback("Data Fetched");
},2000);
}
fetchdata((data)=>{
console.log(data);
});

Example: Using a Promise

function fetchdata(){
return new Promise((resolve)=>{ settimeout(()=>{
callback("Data Fetched");
},2000)});
};etchdata().then((data)=>{
console.log(data);
});

Example: Using async/await

function fetchdata(){
return new promise((resolve)=>{
setTimeout(()=>{
resolve("Data Fetched");
},2000);
});
}
async function getData(){
const data = await fetchData();
console.log(data);
}
getData();
Front End Interview Questions for Freshers

11.What is a promise?

A promise represents the eventual completion or failure of an asynchronous operation.

const promise = new promise((resolve,reject)=>{
setTimeout(()=>resolve("success"),1000);
});
promise.then(console.log);

12.. What are async/await functions?

async/await allows writing asynchronous code that looks synchronous.

async function fetchData(){
const data=await fetch("https://api.example.com");
return data.json();
}

13.Explain event delegation in JavaScript.

Event delegation allows you to handle events for multiple child elements at the parent level.

document.getElementById("parent").addEventListener("click",(e)=>{
if(e.target.tagName==="BUTTON"){
console.log("Button clicked!");
}
});

14.What are JavaScript modules?

Modules allow you to organize code into reusable files using import and export

export const greet=()=>"Hello, Module!";
import {greet} from "./module.js"
console.log(greet());

15. How can you prevent a function from being called multiple times?

You can use a debounce function.

function debounce(func,delay){
let timeout;
return (...args)=>{
clearTimeout(timeout);
Timeout = setTimeout(()=>func(...args),delay);
};
}

Book Demo Classes of Full-Stack Development Course

16.What is the event loop?

The event loop processes tasks from the queue and stack for asynchronous operations.

console.log("start");
setTimeout(()=>console.log("Timeout"),0);
console.log("End");

17.What is the difference between apply() and call() methods?

  • call(): Invokes a function with a specific this value and arguments passed individually.
  • apply(): Similar to call(), but arguments are passed as an array
function greet(greeting,punctuation){
return `${greeting},${this.name}${punctuation}`;
}
const person = {name:"siva"};
console.log(greet.call(person,"Hello","!"));
console.log(greet.apply(person,["Hi","."]));

18. What is bind() method used for?

The bind() method creates a new function with a specific this value and optional arguments.

const obj={name:"siva"};
function greet(greeting){
return `${greeting},${this.name}`;
}
const boundgreet=greet.bind(obj);
console.log(boundgreet("hello"));

19. What is a prototype chain

Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language. i.e, When you create an object using a constructor function or a class, the created object inherits properties from a prototype object. The prototype on object instance is available through Object.getPrototypeOf(object) or __proto__ property whereas prototype on constructor function is available through Object.prototype.totype chain

20.What is JSON and its common operations

JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. It is useful when you want to transmit data across a network. It is basically just a text file with an extension of .json, and a MIME type of application/json.

Upcoming Full Stack Course Batches (With 3 Real Time Projects)

Java Full Stack Development Course(Online Batch & Offline Batch)

Python Full Stack Development Course (Online Batch & Offline Batch)

React JS Course (Online Batch & Offline Batch)

21.What is the purpose of the array slice method

The slice() method returns the selected elements in an array as a new array object. It selects the elements starting at the given start argument, and ends at the given optional end argument without including the last element. If you omit the second argument then it selects till the end of the array. This method can also accept negative index which counts back from the end of the array.

22.What is the purpose of the array splice method

The splice() method adds/removes items to/from an array, and then returns the removed item. The first argument specifies the array position/index for insertion or deletion whereas the optional second argument indicates the number of elements to be deleted. Each additional argument is added to the array.

23.What are lambda expressions or arrow functions

An arrow function is a shorter/concise syntax for a function expression and does not have its own this, arguments, super, or new.target. These functions are best suited for non-method functions, and they cannot be used as constructors.

24. What is a first class function

In Javascript, functions are first class objects. First-class functions means when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. For example, in the below example, handler functions assigned to a listener

25.What is a first order function

A first-order function is a function that doesn’t accept another function as an argument and doesn’t return a function as its return value.

26.What is a higher order function

A higher-order function is a function that accepts another function as an argument or returns a function as a return value or both. The syntactic structure of higher order function will be as follows.

27. What is the currying function

Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Currying is named after a mathematician Haskell Curry. By applying currying, an n-ary function turns into a unary function

28.What is a pure function

A Pure function is a function where the return value is only determined by its arguments without any side effects. i.e, If you call a function with the same arguments 'n' number of times and 'n' number of places in the application then it will always return the same value

29.What is the purpose of the let keyword

The let statement declares a block scope local variable. Hence the variables defined with let keyword are limited in scope to the block, statement, or expression on which it is used. Whereas variables declared with the var keyword used to define a variable globally, or locally to an entire function regardless of block scope.

What is the reason to choose the name let as a keyword

let is a mathematical statement that was adopted by early programming languages like Scheme and Basic. It has been borrowed from dozens of other languages that use let already as a traditional keyword as close to var as possible.

31.How do you decode or encode a URL in JavaScript?

encodeURI() function is used to encode an URL. This function requires a URL string as a parameter and return that encoded string. decodeURI() function is used to decode an URL. This function requires an encoded URL string as parameter and return that decoded string.

32.What is memoization

Memoization is a functional programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache. Let's take an example of adding function with memoization.

33.What is Hoisting?

Hoisting is a JavaScript mechanism where variables, function declarations and classes are moved to the top of their scope before code execution

34.What are closures?

A closure is the combination of a function bundled(enclosed) together with its lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables, functions and other data even after the outer function has finished its execution. The closure has three scope chains

35.What is scope in javascript

Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.

36.What is a service worker?

A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don't need a web page or user interaction. Some of the major features of service workers are Rich offline experiences(offline first web application development), periodic background syncs, push notifications, intercept and handle network requests and programmatically managing a cache of responses.

37.How do you manipulate DOM using a service worker

Service worker can't access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM.

38.How do you reuse information across service worker restarts

The problem with service worker is that it gets terminated when not in use, and restarted when it's next needed, so you cannot rely on global state within a service worker's onfetch and onmessage handlers. In this case, service workers will have access to IndexedDB API in order to persist and reuse across restarts.

39.What is IndexedDB

IndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.

40.What is a post message?

Post message is a method that enables cross-origin communication between Window objects.(i.e, between a page and a pop-up that it spawned, or between a page and an iframe embedded within it). Generally, scripts on different pages are allowed to access each other if and only if the pages follow same-origin policy(i.e, pages share the same protocol, port number, and host).

41.What is the main difference between localStorage and sessionStorage?

LocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets cleared when the page session end

42.How do you access web storage?

The Window object implements the WindowLocalStorage and WindowSessionStorage objects which has localStorage(window.localStorage) and sessionStorage(window.sessionStorage) properties respectively. These properties create an instance of the Storage object, through which data items can be set, retrieved and removed for a specific domain and storage type (session or local).

43.Why do you need web storage?

Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Also, the information is never transferred to the server. Hence this is a more recommended approach than Cookies.

44.Why do you need a promise?

Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.

45.What are server-sent events

Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only. This has been used in Facebook/Twitter updates, stock price updates, news feeds etc.

46.What is a strict mode in javascript

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This way it prevents certain actions from being taken and throws more exceptions. The literal expression "use strict"; instructs the browser to use the javascript code in the Strict mode.

47.Why do you need strict mode

Strict mode is useful to write "secure" JavaScript by notifying "bad syntax" into real errors. For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object.

48.What are global variables

Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable.

49.What is an event flow

Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event for each of its parent elements first, starting at the top with the global window object.

50.What is event bubbling

Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element(i.e, global window object).

Java Interview Questions and Answers