Arunav Goswami
Data Science Consultant at almaBetter
Ace your next tech interview with our comprehensive guide on top 100 JavaScript interview questions, covering essential topics from easy to advanced concepts.
Welcome to our ultimate guide on the Top 100 JavaScript interview questions! Whether you're a seasoned developer looking to brush up on your skills or a newcomer entering the world of Web Development, this comprehensive resource is designed to help you stand out in your next JavaScript interview.
In this blog post, we have meticulously curated a list of questions that cover both basic JavaScript interview questions and JavaScript coding interview questions, providing you with a solid understanding of the language and its capabilities. So, buckle up and get ready to delve deep into the world of JavaScript, as we help you prepare to impress your future employers and secure your dream job in Web Development!
Q.1. What is the difference between “==” and “===”?
Solution: In JavaScript, the "==" operator checks whether two values are equal in value, disregarding their data type. On the other hand, the "===" operator is a stricter comparison that checks if the values are not only equal in value but also of the same data type. If the values are of different types, then "===" will return false.
Q.2. What is the difference between an alert box and a confirmation box?
Solution: In JavaScript, an alert box presents a message to the user with a single OK button. However, a confirmation box presents the user with two options, OK and cancel, to confirm or cancel an action. This allows for a more interactive and user-friendly experience in web applications.
Q.3. What are the different types of errors in JavaScript?
Solution: There are three types of errors:
Load time errors: Errors that come up when loading a web page, like improper syntax errors, are known as Load time errors and generate the errors dynamically.
Runtime errors: Errors that come due to misuse of the command inside the HTML language.
Logical errors: These are the errors that occur due to the bad logic performed on a function with a different operation.
Q.4. What is event bubbling?
Solution: Event bubbling is a method of event propagation in the HTML DOM API when an event is in an element inside another element, and both elements have registered a handle to that event. It is a process that starts with the element that triggered the event and then bubbles up to the containing elements in the hierarchy. In event bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.
Q.5. How is DOM utilized in JavaScript?
Solution: DOM stands for Document Object Model and is responsible for how various objects in a document interact with each other. DOM is required for developing web pages, which include objects like paragraphs, links, etc. These objects can be operated to include actions like add or delete. DOM is also required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over other existing models.
Q.6. What are unescape() and escape() functions?
Solution: unescape() and escape() are two functions in JavaScript that are used to encode and decode special characters in strings.
escape() function converts special characters to their hexadecimal Unicode equivalent, which allows them to be safely transmitted over networks or stored in databases. For example, the character "@" would be converted to "%40".
unescape() function is used to decode the string encoded with escape(). It converts the hexadecimal Unicode sequence back to the original character. For example, the string "%40" would be converted back to "@".
Q.7. Why should you not use innerHTML in JavaScript?
Solution: innerHTML content is refreshed every time and thus is slower. There is no scope for validation in innerHTML. Therefore, it is easier to insert rogue code in the document and make the web page unstable.
Q.8. What are Cookies in JavaScript?
Solution: A cookie is a piece of data stored on your computer to be accessed by your browser. You also might have enjoyed the benefits of cookies knowingly or unknowingly. Have you ever saved your Facebook password so that you do not have to type it every time you try to login? If yes, then you are using cookies. Cookies are saved as key/value pairs.
Q.9 What are the ways to define a variable in JavaScript?
Solution: The three possible ways of defining a variable in JavaScript are:
Var – The JavaScript variables statement is used to declare a variable and, optionally, we can initialize the value of that variable. Example: var a =10; Variable declarations are processed before the execution of the code.
Const – The idea of const functions is not allow them to modify the object on which they are called. When a function is declared as const, it can be called on any type of object.
Let – It is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it’s defined in.
Q.10. What is the difference between undeclared & undefined?
Solution: 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.
Q.11. What would be the result of 2+5+”3″?
Solution: Since 2 and 5 are integers, they will be added numerically. And since 3 is a string, its concatenation will be done. So the result would be 73. The ” ” makes all the difference here and represents 3 as a string and not a number.
Q.12. Mention the different types of functions that are supported by JavaScript. Define each of them.
Solution: There are two types of functions that are supported by JavaScript. They are -
Anonymous function- This type of function generally has no name and this is the difference between it and a normal function.
Named function- On the other hand, this function is named properly and specifically.
Q.13. What are the different scopes for variables in JavaScript?
Solution: JavaScript variables have different scopes. The scope of the variable is nothing but the functionality of the variable.
Global variables- Global variables consist of global scope whereas these variables can be utilized in the whole program repeatedly.
Local Variables- Local variables have no scope and are used only once in the whole program.
Q.14. What is closure?
Solution: The closure is a primary mechanism to private the data items. Closures give access to the outer function’s scope from the inner function's scope. Closures are created for every function in JavaScript. To define a closure, create a function inside another function to expose it.
Q.15. Explain the terms array slice() and array splice().
Solution:
Array slice() method removes the array items from the array and reforms the removed items into a new array. The selected items through an array slice() method are removed from the array and formed as another new array.
array splice() method removes the items of the selected array from the array and does not form another array.
Q.16. Explain the View state and Session state.
Solution:
View State- The particular point of time where the user spent on only a page of the session is called view state
Session State- Where the browser or user spends on all pages of the application is called session state.
Q.17. How would you read a cookie?
Solution: Reading a cookie using JavaScript is also very simple. We can use the document.cookie string that contains the cookies that we just created using that string.
The document.cookie string keeps a list of name-value pairs separated by semicolons, where ‘name’ is the name of the cookie, and ‘value’ is its value. We can also use the split() method to break the cookie value into keys and values.
Q.18. How would you delete a cookie?
Solution: To delete a cookie, we can just set an expiration date and time. Specifying the correct path of the cookie that we want to delete is a good practice since some browsers won’t allow the deletion of cookies unless there is a clear path that tells which cookie to delete from the user’s machine.
Q.19. Explain Hoisting in javascript.
Solution: In JavaScript, hoisting is a process where the interpreter moves all variable and function declarations to the top of their respective scopes, either local or global, during compilation. This means that variables and functions can be used before they are declared, as long as they are within the same scope. However, only the declarations are hoisted, and not their values.
Read our latest blog "History of JavaScript"
Q.20. What are the various data types that exist in JavaScript?
Solution: These are the different types of data that JavaScript supports:
Boolean - For true and false values
Null - For empty or unknown values
Undefined - For variables that are only declared and not defined or initialized
Number - For integer and floating-point numbers
String - For characters and alphanumeric values
Object - For collections or complex values
Symbols - For unique identifiers for objects
the development of network-based applications
Q.21. What are some of the built-in methods in JavaScript?
Some of the built-in methods in JavaScript are:
Built-in Method | Values |
---|---|
Date() | Returns the present date and time |
concat() | Joins two strings and returns the new string |
push() | Adds an item to an array |
pop() | Removes and also returns the last element of an array |
round() | Rounds of the value to the nearest integer and then returns it |
length() | Returns the length of a string |
Q.22. What is the difference between a deep copy and a shallow copy?
Solution: In JavaScript, when copying an object, there are two types of copying: deep copying and shallow copying.
A shallow copy creates a new object and then copies the values of the properties from the original object to the new object. However, if the property value is an object or an array, the reference to the original value is copied instead of creating a new copy. This means that any changes made to the original object will also affect the copied object.
On the other hand, a deep copy creates a completely new object and then copies the values of all properties, including those that are objects or arrays. This means that changes made to the original object will not affect the copied object.
Q.23. What are the conventions of naming a variable in JavaScript?
Solution: Following are the naming conventions for a variable in JavaScript:
Variable names cannot be similar to that of reserved keywords. For example, var, let, const, etc.
Variable names cannot begin with a numeric value. They must only begin with a letter or an underscore character.
Variable names are case-sensitive.
Q.24. What is Callback in JavaScript?
Solution: In JavaScript, functions are objects, and therefore, functions can take other functions as arguments and can also be returned by other functions. A callback is a Javascript function that is passed to another function as an argument or a parameter. This function is to be executed whenever the function that it is passed to gets executed.
Q.25. What is the difference between Function declaration and Function expression?
Function declaration | Function expression |
---|---|
Declared as a separate statement within the main JavaScript code | Created inside an expression or some other construct |
Can be called before the function is defined | Created when the execution point reaches it; can be used only after that |
Offers better code readability and better code organization | Used when there is a need for a conditional declaration of a function |
Example: | |
function abc() { | |
return 5; | |
} | |
Example: | |
var a = function abc() { | |
return 5; | |
} |
Q.26. How would you delete a cookie?
Solution: To delete a cookie, we can just set an expiration date and time. Specifying the correct path of the cookie that we want to delete is a good practice since some browsers won’t allow the deletion of cookies unless there is a clear path that tells which cookie to delete from the user’s machine.
Example:
function delete_cookie(name) {
document.cookie = name + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"
}
Q.27. What are Closures in JavaScript?
Solution: Closures provide a better, and more concise way of writing JavaScript code for developers and programmers. Closures are created whenever a variable that is defined outside the current scope is accessed within the current scope.
Example:
function hello(name) {
var message = "hello " + name;
return function hello() {
console.log(message);
};
}
//generate closure
var helloWorld = hello("World");
//use closure
helloWorld();
Q.28. What are the different ways an HTML element can be accessed in a JavaScript code?
Solution: Here are the ways an HTML element can be accessed in a JavaScript code:
getElementByClass(‘classname’): Gets all the HTML elements that have the specified classname.
getElementById(‘idname’): Gets an HTML element by its ID name.
getElementbyTagName(‘tagname’): Gets all the HTML elements that have the specified tagname.
querySelector(): Takes CSS style selector and returns the first selected HTML element.
Q.29. What are the ways of defining a variable in JavaScript?
Solution: There are three ways of defining a variable in JavaScript:
Var
This is used to declare a variable and the value can be changed at a later time within the JavaScript code.
Const
We can also use this to declare/define a variable but the value, as the name implies, is constant throughout the JavaScript program and cannot be modified at a later time.
Let
This mostly implies that the values can be changed at a later time within the JavaScript code.
Q.30. What are Imports and Exports in JavaScript?
Solution: Imports and exports help in writing modular code for our JavaScript applications. With the help of imports and exports, we can split JavaScript code into multiple files in a project. This greatly simplifies the application source code and encourages code readability.
Example:
calc.js
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
This file exports two functions that calculate the squares and diagonal of the input respectively.
main.js
import { square, diag } from "calc";
console.log(square(4)); // 16
console.log(diag(4, 3)); // 5
Therefore, here we import those functions and pass input to those functions to calculate square and diagonal.
Q.31. What is the difference between Document and Window in JavaScript?
Answer:
Document | Window |
---|---|
The document comes under the windows object and can also be considered as its property. | A window in JavaScript is a global object that holds the structure like variables, functions, location, history, etc. |
Q.32. What is the difference between Undefined and Undeclared in JavaScript?
Undefined | Undeclared |
---|---|
Undefined means a variable has been declared but a value has not yet been assigned to that variable. | Variables that are not declared or that do not exist in a program or application. |
Q.33. What is the difference between Undefined and Null in JavaScript?
Undefined | Null |
---|---|
Undefined means a variable has been declared but a value has not yet been assigned to that variable. | Null is an assignment value that we can assign to any variable that is meant to contain no value. |
Q.34. What is the difference between Session storage and Local storage?
Session storage | Local storage |
---|---|
The data stored in session storage gets expired or is deleted when a page session ends. | Websites store some data in local machines to reduce loading time; this data does not get deleted at the end of a browsing session. |
Q.35. What is the ‘this’ keyword in JavaScript?
Solution: In JavaScript, the keyword "this" refers to the current object and is used to assign values to its properties. It is often used in constructor functions to create new objects with specific properties. By using "this" within the constructor, you can set values for each instance of the object, allowing for greater flexibility and reusability in your code.
Q.36. What are generator functions?
Solution: Generator functions are declared with a special class of functions and keywords using function*. It does not execute the code. However, it returns a generator object and handles the execution.
Q.37. What is WeakSet?
Solution: In JavaScript, a WeakSet is a data structure that holds a collection of unique and ordered objects. Unlike a regular Set, a WeakSet only allows objects to be added and stores them weakly. This means that if there are no other references to an object, it will be automatically removed from the WeakSet during garbage collection. WeakSets can be useful for managing object references and preventing memory leaks in your code.
Q.38. What is the use of callbacks?
Solution: A callback can be used in the following ways:-
A callback function is used to send input into another function and is performed inside another function.
It also ensures that a particular code does not run until another code has completed its execution.
Q.39. What is a WeakMap?
Solution: A WeakMap is a JavaScript data structure that maps keys to values, but the keys are stored weakly. This means that if a key object has no other references, it will be automatically removed from the WeakMap during garbage collection. WeakMaps are useful for managing object references and can help prevent memory leaks in your code.
Q.40. What is Object Destructuring? (with examples)
Solution: Object destructuring is a method to extract elements from an array or an object.
Example 1: Array Destructuring
const arr = [1, 2, 3];
const first = arr[0];
const second = arr[1];
const third = arr[2];
Q.41. Explain Async/Await and Generators.
Solution:
Async/Await - Async-await functions are executed sequentially one after another in an easier way.
Async/Await function might throw an error when the value is returned.
Generators - Generator functions are executed with one output at a time by the generator’s yield by yield.
The ‘value: X, done: Boolean’ is the output result of the Generator function.
Q.42. What is the Strict mode in JavaScript?
Solution: Strict mode in JavaScript introduces more stringent error-checking in JavaScript code.
While in Strict mode, all variables have to be declared explicitly, values cannot be assigned to a read-only property, etc.
We can enable strict mode by adding ‘use strict’ at the beginning of a JavaScript code, or within a certain segment of code.
Q.43. How do you remove duplicates from a JavaScript array?
Solution: There are two ways in which we can remove duplicates from a JavaScript array:
By Using the Filter Method
To call the filter() method, three arguments are required. These are namely array, current element, and index of the current element.
By Using the For Loop
An empty array is used for storing all the repeating elements.
Q.44. Explain Higher Order Functions in javascript.
Solution: In JavaScript, a higher-order function is a function that takes another function as an argument or returns a function as its result. These functions are commonly used for abstraction, encapsulation, and composition, allowing for more concise and reusable code. Higher-order functions can be used for a variety of tasks, such as filtering arrays, transforming data, and handling asynchronous operations.
Q.45. What is currying in JavaScript?
Solution: In JavaScript, currying is a functional programming technique that transforms a function that takes multiple arguments into a sequence of functions that each take a single argument. This allows for greater flexibility and composition in your code and can simplify the process of creating reusable functions. By using currying, you can create more specialized functions that are tailored to specific use cases, making your code more modular and easier to understand.
Q.46. Mention some advantages of javascript.
Solution: There are many advantages of javascript. Some of them are:-
Javascript is executed on the client side as well as server-side also. There are a variety of Frontend Frameworks that you may study and utilize. However, if you want to use JavaScript on the backend, you'll need to learn NodeJS. It is currently the only JavaScript framework that may be used on the backend.
Javascript is a simple language to learn.
Web pages now have more functionality because of Javascript.
To the end-user, Javascript is quite quick
Q.47. What is memoization?
Solution: Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned.
Q.48. What is the distinction between client-side and server-side JavaScript?
Solution: Client-side JavaScript runs in a user's web browser and is responsible for handling the presentation and behavior of a web page. Server-side JavaScript runs on a web server and is responsible for handling tasks such as data processing, file manipulation, and interacting with databases.
Q.49. What is the use of promises in javascript?
Solution: Promises are used to handle asynchronous operations in javascript.
Before promises, callbacks were used to handle asynchronous operations. But due to the limited functionality of callbacks, using multiple callbacks to handle asynchronous code can lead to unmanageable code.
Q.50. What are the four states of promise object in Javascipt?
Solution: Promise object has four states -
Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.
Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed.
Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
Settled - This state represents that the promise has been either rejected or fulfilled.
Q.51. What is the difference between apply() and call() in JavaScript?
Solution: Both apply() and call() are JavaScript functions that allow you to invoke a function with a given this value and arguments provided as an array (for apply()) or as individual arguments (for call()). The primary difference between the two methods is how they accept arguments. call() method accepts arguments as a comma-separated list, whereas apply() accepts arguments as an array.
Q.52. What is the difference between synchronous and asynchronous code in JavaScript?
Solution: Synchronous code is executed in sequence, one line at a time, blocking the execution of further code until the current operation is completed. In other words, synchronous code executes in a single thread and waits for each operation to finish before moving on to the next one.
Asynchronous code, on the other hand, does not block the execution of the program while waiting for a particular operation to complete. Instead, asynchronous code allows the program to continue executing while it waits for a particular operation to finish. This is typically done by using callbacks or promises.
Q.53. What is the difference between debounce and throttle in JavaScript?
Both debounce and throttle are techniques used in JavaScript to limit the number of times a particular function is executed in response to an event such as scrolling or resizing. However, they work in slightly different ways.
Debounce ensures that a function is not called too frequently, by postponing its execution until after a certain period of inactivity. The idea is to wait for a certain time after the last event occurs, and then execute the function once
Throttle, on the other hand, ensures that a function is not executed too frequently by limiting the rate at which it can be called. The idea is to execute the function at a fixed interval, rather than waiting for a certain period of inactivity.
Q.54. What is the difference between a callback and a promise in JavaScript?
Solution: Both callbacks and promises are used in JavaScript to handle asynchronous code, but they differ in how they handle the results of the asynchronous operation.
A callback function is a function that is passed as an argument to another function and is executed when the first function completes. Callbacks are used to handle asynchronous code in JavaScript by defining a function that will be executed once the asynchronous operation has been completed.
Promises, on the other hand, are objects that represent the eventual completion (or failure) of an asynchronous operation and allow you to handle the result of the operation in a more structured way. A promise can be in one of three states: pending, fulfilled, or rejected. Once a promise is fulfilled or rejected, it cannot be changed
Q.55. What is the difference between a method and a function in JavaScript?
Solution: In JavaScript, a method and a function are similar in that they both can perform a set of operations and return a value. However, the key difference between them is the way they are called and the context in which they are executed.
A function in JavaScript is a standalone piece of code that can be called by name and executed. It can accept zero or more arguments and can return a value. Functions can be defined and invoked from anywhere in the code.
On the other hand, a method is a function that is associated with an object or a class. It is defined within the object or class definition and is called on an instance of that object or class. Methods have access to the properties of the object or class they are associated with and can manipulate them.
Q.56. How do you create a private variable in JavaScript?
Solution: In JavaScript, there is no native support for creating private variables or methods within a class or object. However, there are certain techniques that can be used to simulate private variables. Here are two commonly used approaches:
1. Using closures: In JavaScript, a closure is a function that has access to its own private variables as well as the variables in the outer function. This can be used to create private variables by defining them within the outer function and returning a function that can access them.
2. Using symbols: Symbols are a new primitive type in JavaScript that can be used to create unique keys for object properties. This can be used to simulate private variables by creating a symbol and using it as the key for the private variable.
Q.57. What are some common design patterns used in JavaScript?
Solution: Design patterns are reusable solutions to common problems that arise in software development. In JavaScript, there are several design patterns that are commonly used. Here are some examples of design patterns and how they can be implemented in JavaScript:
1. Singleton Pattern
2. Observer Pattern
3. Factory Pattern
4. Module Pattern
5. Decorator Pattern
Q.58. List some of the disadvantages of JavaScript.
Solution: Some of the disadvantages of JavaScript are:
No support for multithreading.
No support for multiprocessing.
Reading and writing files are not allowed.
No support for networking applications.
Q.59. If we want to return the character from a specific index which method is used?
Solution: The JavaScript string charAt() method is used to find out a char value present at the specified index. The index number starts from 0 and goes to n-1, where n is the length of the string. The index value can't be negative, greater than, or equal to the length of the string.
Q.60. What does the isNaN() function do?
Solution: In JavaScript, the isNaN() function is used to determine whether a given value is a valid number or not. It returns a boolean value of true if the value is not a number and false if it is. This can be useful when working with user input, as it allows you to validate input and handle errors more effectively in your code.
Q.61. In which location cookies are stored on the hard disk?
Solution: In Web Development, cookies are small text files that are stored on a user's computer by their web browser. The exact location of these files on the hard disk can vary depending on the user's operating system and browser. Cookies can be used to store user preferences, login information, and other data that can be accessed by the website that created them. However, they can also be used for tracking and advertising purposes, which has led to some concerns over privacy and security.
Q.62. What is the use of a Map object in JavaScript?
Solution: The JavaScript Map object is used to map keys to values. It stores each element as key-value pair. It operates the elements such as search, update and delete on the basis of a specified key.
Q.63.How does JavaScript implement inheritance, and how is it different from other object-oriented programming languages?
Solution: JavaScript implements inheritance through prototype-based inheritance, which is different from the class-based inheritance used in other object-oriented programming languages like Java and C++. In JavaScript, each object has an internal prototype object that it inherits properties and methods from.
When you create a new object, you can set its prototype to be another object, allowing it to inherit all of the properties and methods of that object. This is done using the Object.create() method
Q.64. What is the "call stack" in JavaScript?
Solution: The "call stack" is an important concept in JavaScript (and other programming languages) that helps keep track of the order in which functions are called and executed.
When a function is called, JavaScript creates a new execution context for that function and adds it to the top of the call stack. The execution context includes information about the function, such as its arguments, local variables, and any other relevant data.
When the function completes, its execution context is removed from the top of the call stack, and control is returned to the function that called it. The next function in the call stack is then executed, and this process continues until all functions have been executed and the call stack is empty.
Q.65. Can you explain the "event loop" in JavaScript?
Solution: In JavaScript, the event loop is a mechanism that allows for non-blocking code execution, meaning that the code can continue to run even while waiting for an external resource or operation to complete. The event loop is responsible for managing the execution of code in a way that is efficient and responsive**.**
Q.66. What is JSON and its common operations
Solution: 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 and it is basically just a text file with an extension of .json, and a MIME type of application/json.
Q.67. What is a first-class function
Solution: In Javascript, functions are first-class objects. First-class functions mean 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.
Q.68. What is a unary function
Solution: In computer science, a unary function is a type of function that accepts only one input, or argument. These functions are commonly used in programming languages, where they can be used to transform data or perform operations on individual elements within a larger data structure. Unary functions can be useful for simplifying code and improving efficiency, as they allow you to work with individual elements without having to loop through an entire collection of data.
Q.69. What is a pure function
Solution: 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.
Q.70. What is the Temporal Dead Zone
Solution: The Temporal Dead Zone is a behavior in JavaScript that occurs when declaring a variable with the let and const keywords, but not with var. In ECMAScript 6, accessing a let or const variable before its declaration (within its scope) causes a ReferenceError. The time span when that happens, between the creation of a variable’s binding and its declaration, is called the temporal dead zone.
Q.71. What is scope in javascript
Solution: 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.
Q.72. What is a service worker
Solution: 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, intercepting and handling network requests, and programmatically managing a cache of responses.
Q.73. What is web storage?
Solution: 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.
Q.74. What is a post message?
Solution: A 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 the same-origin policy(i.e, pages share the same protocol, port number, and host).
Q.75. What are the restrictions of web workers on DOM?
Solution: WebWorkers don't have access to the below javascript objects since they are defined in external files
Window object
Document object
Parent object
Q.76. Write a function to find the first non-repeating character in a string in JavaScript.
Solution: This code defines a function findFirstNonRepeatingChar that takes a string str as input and returns the first non-repeating character in the string. If there are no non-repeating characters in the string, the function returns null.
The function achieves this by iterating over each character in the string using a for loop. For each character, it checks whether the index of the character in the string is equal to the last index of the character in the string using the indexOf and lastIndexOf methods. If the two indexes are equal, it means that the character appears only once in the string, and the function returns that character.
Code:
function findFirstNonRepeatingChar(str) {
for (let i = 0; i < str.length; i++) {
if (str.indexOf(str[i]) === str.lastIndexOf(str[i])) {
return str[i];
}
}
return null;
}
Q.77. Write a function to check if a given string is a palindrome.
Solution: In this approach, we first convert the input string to lowercase and remove any whitespace. We then loop through the first half of the string and check if each character matches its corresponding character at the opposite end of the string. If we find a mismatch, we return false. If we reach the end of the loop without finding a mismatch, we return true.
Code:
function isPalindrome(str) {
// Convert string to lowercase and remove whitespace
str = str.toLowerCase().replace(/\s/g, '');
// Check if the string is equal to its reverse
for (let i = 0; i < str.length / 2; i++) {
if (str[i] !== str[str.length - 1 - i]) {
return false;
}
}
return true;
}
Q.78. Write a function to remove all duplicates from an array.
Solution: In the code snippet you provided, an array arr is defined containing several duplicate values. The removeDuplicates function is then called on this array, which returns a new array with all duplicate values removed. The resulting array is assigned to the variable result. Finally, the contents of the result are printed to the console using console.log
Code:
const arr = [1, 2, 3, 3, 4, 4, 5];
const result = removeDuplicates(arr);
console.log(result); // [1, 2, 3, 4, 5]
Q.79. Write a function to find the largest and smallest number in an unsorted array of integers.
Solution: The findMinMax function takes an array arr as input and returns an object containing the minimum and maximum values in the array.
The function first initializes two variables, min and max, to the value of the first element in the array, assuming the array is non-empty. It then iterates through the rest of the array using a for loop, checking each element against the current minimum and maximum values.
If an element is found that is smaller than the current min, the function updates the value of min to be that element. Similarly, if an element is found that is larger than the current max, the function updates the value of max to be that element.
Once the loop has finished iterating over the entire array, the function returns an object with the properties min and max, each of which contain the minimum and maximum values in the array, respectively.
Code:
function findMinMax(arr) {
let min = arr[0];
let max = arr[0];
for(let i = 1; i < arr.length; i++) {
if(arr[i] < min) {
min = arr[i];
}
if(arr[i] > max) {
max = arr[i];
}
}
return { min, max };
}
Q.80. Write a function to reverse a string.
Solution: This code defines a function reverseString that takes a string as an argument and returns the reversed version of that string.
Inside the function, a variable reversed is initialized with an empty string. Then a for loop is used to iterate over the characters of the string in reverse order. The loop starts at the index str.length - 1 and decrements the index until it reaches 0.
During each iteration of the loop, the character at the current index i is appended to the reversed string using the += operator.
Finally, the function returns the reversed string.
Code:
function reverseString(str) {
let reversed = "";
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
console.log(reverseString("hello")); // Output: "olleh"
Q.81. Write a function to find the sum of all even numbers in an array.
Solution: This code defines a function sumEven that takes an array of numbers as an argument and returns the sum of all even numbers in the array.
Inside the function, a variable sum is initialized with a value of zero. Then a for loop is used to iterate over each element of the array.
During each iteration of the loop, the current element at index i is checked if it is an even number by checking if the remainder of the element divided by 2 is zero using the modulus operator %. If the remainder is zero, it means that the element is even, so its value is added to the sum variable using the += operator. Finally, the function returns the sum of all even numbers.
Code:
function sumEven(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
sum += arr[i];
}
}
return sum;
}
console.log(sumEven([1, 2, 3, 4, 5, 6]));
Q.82. Write a function to find the largest number in an array.
Solution: This code defines a function findLargest that takes an array of numbers as an argument and returns the largest number in the array. Inside the function, the variable largest is initialized with the value of the first element in the array, which is arr[0]. Then a for loop is used to iterate over the rest of the elements in the array starting from index 1. During each iteration of the loop, the current element at index i is compared with the current largest value using the > operator. If the current element is greater than the current largest value, then the largest is updated with the value of the current element. Finally, the function returns the largest value.
Code:
function findLargest(arr) {
let largest = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
console.log(findLargest([3, 7, 2, 8, 4])); // Output:
Q.82. Write a function to reverse a given integer.
Solution: This code defines a JavaScript function called reverseInt that takes in one argument num. The purpose of this function is to reverse the digits of a given integer number and return the reversed number while preserving the sign of the original number.
The function first converts the input number into a string using the toString() method. Then it splits the string into an array of individual characters using the split('') method. Next, it reverses the order of the array elements using the reverse() method. Finally, it joins the reversed array elements back into a string using the join('') method. This results in a string that contains the reversed digits of the input number.
Code:
function reverseInt(num) {
let reversed = parseInt(num.toString().split('').reverse().join(''));
return reversed * Math.sign(num); // Preserve the sign of the original number
}
console.log(reverseInt(1234)); // Output: 4321
Q.83. Write a function to find the factorial of a given number.
Solution: This code defines a JavaScript function called factorial that takes in one argument num. The purpose of this function is to calculate the factorial of the given number num. The function first checks if the input number is less than 0. If so, it returns null, indicating that the input is invalid.
If the input number is 0 or 1, the function returns 1 because the factorial of 0 and 1 is 1. If the input number is greater than 1, the function initializes a variable called result to 1 and then uses a for loop to calculate the factorial of num. In each iteration of the loop, the loop variable i is multiplied by the result variable. This loop continues until i is equal to the input number num.
Finally, the function returns the calculated factorial value.
Code:
function factorial(num) {
if (num < 0) {
return null; // Invalid input
}
if (num === 0 || num === 1) {
return 1;
}
let result = 1;
for (let i = 2; i <= num; i++) {
result *= i;
}
return result;
}
console.log(factorial(5)); // Output: 120
Q.84. Write a function to sort an array of integers in ascending order.
Solution: This code defines a JavaScript function called sortArray that takes in one argument arr. The purpose of this function is to sort the elements of the input array arr in ascending order and return the sorted array.
The function uses the sort() method to sort the elements of the input array in place. The sort() method sorts the elements of an array in ascending order by default. However, to ensure that the elements are sorted in numerical order, a comparison function is passed as an argument to the sort() method.
The comparison function (a, b) => a - b subtracts the value of b from the value of a for each pair of elements being compared. If the result is negative, it means that a should come before b in the sorted array. If the result is positive, it means that b should come before a in the sorted array. If the result is zero, it means that a and b are equal and their relative order does not matter. The sort() method sorts the elements of the input array arr in place and returns the sorted array.
Code:
function sortArray(arr) {
return arr.sort((a, b) => a - b);
}
console.log(sortArray([3, 1, 4, 2, 5])); // Output: [1, 2, 3, 4, 5]
Q.85. Write a function to implement a binary search algorithm for finding an element in a sorted array.
Solution: This code defines a JavaScript function called binarySearch that takes in two arguments: an array of sorted elements arr and a target value to be searched in the array. The purpose of this function is to perform a binary search on the input array to find the index of the target value, if it exists in the array, and return the index. If the target value is not found in the array, the function returns -1.
Code:
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Element not found
}
console.log(binarySearch([1, 3, 5, 7, 9], 5)); // Output: 2
Q.86. Write a function to remove all falsy values from an array.
Solution: This code defines a JavaScript function called removeFalsy that takes in one argument arr. The purpose of this function is to remove all falsy values from the input array arr and return a new array with only the truthy values.
The function uses the filter() method to create a new array that contains only the truthy values of the input array. The Boolean function is passed as an argument to the filter() method, which acts as a callback function to test each element of the input array for truthiness.
Code:
function removeFalsy(arr) {
return arr.filter(Boolean);
}
Q.87. Write a function to rotate an array to the right by a given number of steps.
Solution: This is a JavaScript function that takes an array (arr) and a number of steps (steps) as input parameters.
The function checks if the steps input is 0. If it is, it simply returns the original array arr. If the steps are greater than 0, the function calculates the index of the "pivot" element using the modulus operator (%) and subtracting it from the length of the array. This index represents the point where the array will be rotated.
Finally, the function rotates the array by slicing it into two parts: the first part includes elements from the pivot index to the end of the array (arr.slice(pivot)), and the second part includes elements from the beginning of the array up to the pivot index (arr.slice(0, pivot)). Then it concatenates the two parts using the concat method and returns the rotated array.
Code:
function rotateRight(arr, steps) {
// If no steps are specified, just return the original array
if (steps === 0) {
return arr;
}
// Determine the index of the pivot element
const pivot = arr.length - steps % arr.length;
// Rotate the array by slicing it into two parts and swapping their order
return arr.slice(pivot).concat(arr.slice(0, pivot));
}
Q.88. Write a function called findDuplicate that takes an array of numbers as input and returns the first number that appears twice in the array. If no number appears twice, the function should return undefined.
Solution: The findDuplicate function creates an empty object called seen which will be used to store the numbers in the array as keys. It then loops through the array and checks if each number has already been added to the seen object. If it has, then the number is returned as the first duplicate. If not, the number is added to the seen object as a key with a value of true. If the loop completes without finding a duplicate, the function returns undefined.
Code:
function findDuplicate(arr) {
const seen = {};
for (let i = 0; i < arr.length; i++) {
if (seen[arr[i]]) {
return arr[i];
} else {
seen[arr[i]] = true;
}
}
return undefined;
}
Q.89. Write a function called sumPrimes that takes a number as input and returns the sum of all prime numbers up to and including that number.
Solution: This is a JavaScript function that takes a positive integer num as input and returns the sum of all prime numbers up to and including that number.
The function initializes a variable sum to 0. It then loops through all the numbers from 2 to num, checking each number to see if it is prime.
To check if a number is prime, the function loops through all the numbers from 2 to the number itself (i), and checks if i is evenly divisible by any of those numbers (j). If it is, the isPrime variable is set to false and the loop is broken using the break keyword. If isPrime is still true after the inner loop completes, the number is prime and its value is added to the sum variable. After the loop completes, the function returns the sum of all the prime numbers.
Code:
function sumPrimes(num) {
let sum = 0;
for (let i = 2; i <= num; i++) {
let isPrime = true;
for (let j = 2; j < i; j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
sum += i;
}
}
return sum;
}
Q.90. Given a string, reverse each word in the sentence
Solution: This code defines a function called reverseBySeparator which takes two arguments, a string and a separator. The function splits the string into an array of substrings using the separator, then reverses the order of the elements in the array, and finally joins the elements back into a string using the separator. The code then declares a variable called string and assigns it a value of "Welcome to this Javascript Guide!".
The code then calls the reverseBySeparator function twice with string as the first argument, and two different separators - an empty string in the first call and a space character in the second call.
The first call to reverseBySeparator reverses the entire sentence by using an empty string as the separator. The resulting string is stored in a variable called reverseEntireSentence.
The second call to reverseBySeparator reverses each word in the sentence by using a space character as the separator. The resulting string is stored in a variable called reverseEachWord. Finally, the code outputs the two resulting strings - reverseEntireSentence and reverseEachWord.
Code:
var string = "Welcome to this Javascript Guide!";
// Output becomes !ediuG tpircsavaJ siht ot emocleW
var reverseEntireSentence = reverseBySeparator(string, "");
// Output becomes emocleW ot siht tpircsavaJ !ediuG
var reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");
function reverseBySeparator(string, separator) {
return string.split(separator).reverse().join(separator);
}
Q.91. How would you check if a number is an integer?
Solution: A very simple way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1**.**
Code:
function isInt(num) {
return num % 1 === 0;
}
console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false
Q.92. Create a for loop that iterates up to 100 while outputting "fizz" at multiples of 3, "buzz" at multiples of 5 and "fizzbuzz" at multiples of 3 and 5.
Solution: The code uses a for loop to iterate through the numbers 1 to 100. For each number, the code checks whether it is divisible by 3 (using i % 3 == 0) and/or by 5 (using i % 5 == 0). If the number is divisible by 3, the variable f is set to true, and if the number is divisible by 5, the variable b is set to true.
The code then uses a ternary operator to output one of four possible values for each number:
If the number is divisible by both 3 and 5, the code outputs "FizzBuzz".
If the number is only divisible by 3, the code outputs "Fizz".
If the number is only divisible by 5, the code outputs "Buzz".
Otherwise, the code outputs the number itself.
The ternary operator used in the code is a shorthand way of writing an if/else statement. It takes a condition as its first operand, and two expressions as its second and third operands. If the condition is true, the operator evaluates to the second operand, otherwise, it evaluates to the third operand.
Code:
for (let i = 1; i <= 100; i++) {
let f = i % 3 == 0,
b = i % 5 == 0;
console.log(f ? (b ? 'FizzBuzz' : 'Fizz') : b ? 'Buzz' : i);
}
Q.93. Write a function that takes a number n as input and returns the first n numbers in the Fibonacci sequence.
Solution: This function takes a number n as input and returns an array of the first n numbers in the Fibonacci sequence.
The function initializes an array called fib with the first two numbers in the Fibonacci sequence (0 and 1). It then uses a for loop to calculate the remaining numbers in the sequence by adding the previous two numbers together. The loop starts at index 2, since the first two numbers in the sequence have already been added to the fib array.
Finally, the function returns the fib array, which contains the first n numbers in the Fibonacci sequence.
Code:
function fibonacci(n) {
let fib = [0, 1];
for (let i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib;
}
Q.94. Given an array of n unique integers from 0 to n, write a function that finds the missing number in the array.
Solution: This function takes an array of unique integers from 0 to n, where n is the length of the array minus one (to account for the missing number). It returns the missing number in the array.
function findMissingNumber(arr) {
const n = arr.length + 1; // add 1 to account for missing number
const expectedSum = (n * (n + 1)) / 2; // sum of first n numbers
const actualSum = arr.reduce((acc, curr) => acc + curr, 0); // sum of numbers in array
return expectedSum - actualSum; // difference is the missing number
}
Q.95. Write a function that takes an array of nested arrays and returns a flattened array. For example, if the input is [1, [2, [3, 4], 5], 6], the output should be [1, 2, 3, 4, 5, 6].
Solution: This function takes an array arr as input, and recursively flattens any nested arrays it contains. The reduce method is used to iterate over each element of the array, and concatenate it to the flattened array. If an element is an array, it is recursively flattened before being concatenated.
Code:
function flattenArray(arr) {
// Use recursion to flatten nested arrays
return arr.reduce(function(flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten);
}, []);
}
Q.96. Write a function that takes a sorted array and a target value as input, and returns the index of the target value in the array (or -1 if the value is not in the array) using binary search algorithm.
Solution: This function takes a sorted array arr and a target value target as input. It uses the binary search algorithm to search for the target value in the array. The left and right variables represent the left and right bounds of the search range. The while loop continues until the search range has been exhausted (i.e. left is greater than right). Inside the loop, the mid variable represents the midpoint of the search range. If the value at mid is equal to the target, the function returns the index of mid. If the value at mid is less than the target, the search range is narrowed to the right half of the array. If the value at mid is greater than the target, the search range is narrowed to the left half of the array. If the target value is not found in the array, the function returns -1.
Code:
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
Q.97. Write a function that takes two sorted arrays as input and returns a new sorted array that contains all the elements from both arrays.
Solution: This function takes two sorted arrays arr1 and arr2 as input. It merges the two arrays into a new sorted array called mergedArray. The i and j variables are used to keep track of the indices of the current elements in arr1 and arr2, respectively. The while loop continues as long as there are elements left in both arrays. Inside the loop, if the current element in arr1 is smaller than the current element in arr2, the current element in arr1 is added to mergedArray and i is incremented. Otherwise, the current element in arr2 is added to mergedArray and j is incremented. After the loop, any remaining elements in arr1 and arr2 are added to mergedArray.
Code:
function mergeSortedArrays(arr1, arr2) {
let mergedArray = [];
let i = 0;
let j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
mergedArray.push(arr1[i]);
i++;
} else {
mergedArray.push(arr2[j]);
j++;
}
}
while (i < arr1.length) {
mergedArray.push(arr1[i]);
i++;
}
while (j < arr2.length) {
mergedArray.push(arr2[j]);
j++;
}
return mergedArray;
}
Q.98. Write a function that takes an array of integers as input and returns the maximum sum of any contiguous subarray within the array.
Solution: This function uses Kadane's algorithm to solve the maximum subarray sum problem in O(n) time complexity. The idea is to keep track of the current sum and the maximum sum seen so far as we iterate over the array. We update the current sum by adding each element in the array, and we update the maximum sum if the current sum is greater than the maximum sum. If the current sum becomes negative, we reset it to zero, since any subarray that includes a negative sum can't be the maximum.
Code:
function maxSubarraySum(arr) {
let maxSum = 0;
let currentSum = 0;
for (let i = 0; i < arr.length; i++) {
currentSum += arr[i];
if (currentSum > maxSum) {
maxSum = currentSum;
}
if (currentSum < 0) {
currentSum = 0;
}
}
return maxSum;
}
Q.99. Write a function that takes a string as input and returns the most frequently occurring character in the string.
Solution: This function uses an object (i.e., a hash map) to keep track of the frequency of each character in the input string. We iterate over each character in the string, and for each character, we either increment its count in the character map (if it already exists) or initialize it to 1 (if it doesn't exist yet). After building the character map, we iterate over each character in the map, and we update the maxChar and maxCount variables if we find a character with a higher frequency count.
Code:
function mostFrequentChar(str) {
const charMap = {};
let maxChar = '';
let maxCount = 0;
for (let char of str) {
if (charMap[char]) {
charMap[char]++;
} else {
charMap[char] = 1;
}
}
for (let char in charMap) {
if (charMap[char] > maxCount) {
maxCount = charMap[char];
maxChar = char;
}
}
return maxChar;
}
Q.100. Write a function that takes an array of integers as input and returns the number of unique pairs of elements in the array that sum up to a given target value.
Solution: This function takes two parameters: an array of integers and a target value. It uses a set to keep track of the unique pairs that sum up to the target value, and another set to keep track of the complements of the numbers in the array that have been seen so far. It then loops through the array, checks if the complement of the current number is in the complement set, and if so, adds the current number and its complement to the pairs set. Finally, it returns the size of the pairs set, which is the number of unique pairs that sum up to the target value.
Code:
function countPairs(array, target) {
let count = 0;
let pairs = new Set();
let complementSet = new Set();
for (let num of array) {
if (complementSet.has(num)) {
let complement = target - num;
pairs.add([num, complement]);
}
complementSet.add(target - num);
}
count = pairs.size;
return count;
}
In conclusion, this ultimate guide on the Top 100 JavaScript interview questions has equipped you with the knowledge and confidence to tackle both basic and coding interview questions head-on. By mastering these concepts, you are now well-prepared to face your upcoming JavaScript interviews and showcase your expertise to potential employers.
Remember that practice is key, and reviewing these questions regularly will help you solidify your understanding of the language. As the world of Web Development continues to evolve, staying up-to-date with the latest trends and technologies will give you an edge in this competitive field.
Related Articles
Top Tutorials