Fawzan Hussain
6 Jun 2022
•
15 min read
JavaScript interviews can be intimidating and complex, but they’re also some of the most important ones you’ll do on your job search. Below are the top 100 JavaScript interview questions that you can expect to be asked in any JavaScript job interview. Good luck!
JavaScript is a dynamic, interpreted programming language that is most commonly used for web browser scripting. The term JavaScript is not well-defined, but JavaScript's implementations all have common syntax elements that differentiate them from other programming languages: event handlers, array manipulation, object-oriented behavior, and DOM manipulation.
A prototype chain is an object-oriented programming technique that uses prototypical inheritance to achieve polymorphism. This allows a single base class, called a prototype, to be used as a template for creating multiple derived classes without using multiple inheritances.
Scope in JavaScript refers to where variables can be accessed and how long they exist. There are three types of scope: global, local, and function scopes.
Here’s an example of how scope works in JavaScript:
function greet() greet();
// What is your name?
var name = prompt(What is your name?);
var greeting = Hello, + name; console.log(greeting);
// Hello, Bob.
The eval() method evaluates a string as JavaScript code. The source for this interactive example is stored in a GitHub repository. Eg: console.log(eval(“1 + 2”)); // 3
JavaScript has a built-in regular expression engine that lets you use special characters and other syntax to denote classes of strings. You can use regular expressions anywhere you would use a string in JavaScript, including variable names and properties.
We use a pre-defined function for decoding or encoding URLs in javascript. For decoding, the function is decodeURI(), and for encoding URL is encodeURI().
For encode special character like /, ?, :, @, &, =, +, $, #, then we use encodeURIComponent().
Function scope is used to determine where in your code a variable can be accessed. For example, if you define a variable outside of a function, it has a global scope and can be accessed from anywhere in your application.
A global variable is a variable that can be accessed from anywhere in your program. Globals should be avoided because of potential naming conflicts and because they make code hard to follow.
There are many issues with using global variables. First of all, a function’s scope is global by default. This means that when you define a variable within a function and attempt to access it later, it will not exist.
When a global variable is declared, it can be accessed and altered from anywhere in a program. Therefore, avoiding global variables is important to writing good code. First, define a local variable instead of declaring a global variable.
The void operator is used when a JavaScript function returns nothing or is undefined. Using the void operator will ensure that a function can never return null.
JavaScript has a Function object that defines properties and methods for working with functions. A JavaScript function is an object, just like other objects in JavaScript. You create a new Function object by defining a function within another function or by using a Function constructor.
The scope of a JavaScript function is determined by: Lexical scoping Block scope Function parameters Object references returned from functions and methods. Global variables Scope chain, etc.
A function declaration is created using Function Declaration Syntax, and a function constructor is created using Function Constructor Syntax. The difference between these two types of syntax is that when you use Function Declaration Syntax, you do not have to declare what type of data type will be returned from your function.
Function Constructor
Var a = 500; Function createFunction() { var a = 200; return new Function(“return a;”); } console.log(createFunction() ()); // 500
Function Declaration:
var a = 500; function createFunction() { var a = 200; return function func() { return a; }; } console.log(createFunction() ()); // 200
A callback function is a function that is passed as an argument to another function, which expects to use later. Callback functions are commonly used in event-driven programs, such as Node.js and AJAX applications. They’re also used in asynchronous programming models such as Python’s Twisted framework and JavaScript frameworks like jQuery and AngularJS.
Strict mode is a way to override JavaScript’s default behavior. It can be used to enforce more strict error checking and warnings, as well as to disable certain language features.
The steps involved in returning false usage in JavaScript are as follows:
The first step is to create a variable that will store the result of the expression. This can be done by assigning a value to it using the assignment operator (=).
The second step is to use the logical operator "or" (||) to check if the variable has a value or not. If it has a value, then it should be returned, otherwise false should be returned.
Finally, you need to return the result of executing this expression and assign it back to your variable.
Byte Order Mark (BOM) is a character or sequence of characters at the start of an ASCII text file that helps determine how to interpret the bytes in that file. BOMs are used for example to distinguish between little-endian and big-endian storage formats in computer systems.
The purpose of JSON stringify() is to convert data into a JSON format. It can be used to create strings from objects or arrays, or it can be used to create a JSON text from scratch. It's often used in combination with parseJSON(), which converts JSON text back into an object or array.
The typeof operator is one of JavaScript’s many built-in operators. It allows you to determine a variable or an object’s data type. Eg:
typeof “Alexa Abraham”; // Returns “string”
typeof (1 + 2); // Returns “number”
The let keyword is used to declare block-scoped variables. A variable declared with let can only be accessed within its own function or within a nested function of that same scope. It cannot be accessed outside of its containing function, and it does not create a new variable in any surrounding scope.
Currying is a technique for translating functions of multiple arguments into functions of one argument.
Using memorization, programs can be sped up by storing values of functions and not having to recompute them every time.
Hoisting is a JavaScript behavior that allows you to access variables defined in a function before the function.
Closures allow us to create functions that can access variables from outside their scope. We can think of them as a way to define a function inside another function. Closures are also used to create private variables in JavaScript.
A service worker is a JavaScript file that can be installed on your browser to make your website work offline. It's like an app, but it's designed to run in the background. And it's not the same thing as an API or web server, which are usually separate things you need to set up and maintain.
IndexedDB is a JavaScript API that provides a way to store and retrieve data from a browser. It is designed to be indexed and accessed like a database.
Web Storage is a useful JavaScript feature. It allows you to store data on your users’ computers without having to use cookies, which are limited in size and have an expiration date.
We can access web storage by implementing this code: WindowLocalStorage and WindonSessionStorage.
localStorage.setItem(“logo”), document.getElemetById(“logo”).value); localStorage.getItem(“logo”);
A cookie is a JavaScript object that stores data on the user's computer. It is used to store data in web browsers and can be accessed from any website that the user visits. It is a small piece of information sent from a website and stored on the user's computer.
Cookies are used in order to track users and provide personalized content. They are also used for security reasons, such as authenticating users that have logged into a website with the same account before.
To delete cookies, follow these steps:
Open the "Tools" menu on your browser (e.g., Internet Explorer, Firefox) and click "Internet Options".
Go to "Privacy" tab and click on "Delete Cookies" button.
There are three types of cookies that you can use:
Check if Web Worker is supported by using typeof(Worker) in your JavaScript. If it's null or false, then it is not supported and you will have to use an alternative approach.
Web workers can be restricted by:
Callback hell happens when a programmer is using asynchronous callbacks to carry out a task. The programmer will need to use nested callbacks to ensure that the program runs in the right order and with the right data.
A callback is a JavaScript function that is executed after a certain event. The event can be an input, output, or any other type of action.
A promise is an object that represents the eventual result of an asynchronous operation. The Promise object lets you attach event handlers to it that are called asynchronously when the operation completes, either successfully or unsuccessfully.
Promises are often used in conjunction with the async/await pattern to make it easier to work with asynchronous code.
A promise can be in one of three states: pending, fulfilled, or rejected.
A promise can be resolved (or "fulfilled") when an operation completes successfully, such as accessing a web resource via HTTP GET.
A promise can be rejected when an operation fails, such as accessing a web resource via HTTP GET and receiving a 404 error from the server.
Promise chaining is a technique where you can chain promises together and execute them one after the other. The promise will be executed only when the previous promise is resolved.
The racing method is a technique that can be used to avoid race conditions in JavaScript. It is a solution to the problem of two or more threads trying to access the same data at the same time.
Strict mode is a new addition to JavaScript that helps you avoid certain errors and makes your code run faster. It's a good idea to use strict mode in most situations.
When you write code, you have to make sure that it will work in all the browsers. That’s why it’s important to use strict mode when writing JavaScript code.
Server-sent events allow for a more real-time experience for both the user and developer. This is because it eliminates the need for polling, which can be quite resource-intensive. It also allows developers to send data from their servers to their clients without having to make an additional HTTP request.
isNan is a built-in type of JavaScript that checks if a variable is not a number. You use it to check if something is NaN.
Arrow functions are a new syntax introduced in ES6. Arrow functions are lexically bound, anonymous, non-enumerable, lightweight, and faster than other function expressions. It does not bind this automatically, so you have to use a fat arrow if you want to keep this value. It also returns value by default so it can be used as an expression or statement.
This example will show you how to create and use arrow functions: var name = 'Ankit'; var getName = () => { return name; }; console.log(getName()); // Ankit console.log(name); // Ankit
In JavaScript, a Temporal Dead Zone is commonly referred to as a Temporal Dead Zone. In case you were wondering what that meant exactly: A Temporal Dead Zone is essentially an area of memory where no memory leaks can occur when using event listeners, but you have to make sure all events have been captured before allowing script execution past them. More specifically, a Temporal Dead Zone is set in place around code that executes event handlers; Code outside of it will not be able to run until all code inside it has been executed.
This ensures that if any event handlers are registered on elements within it, they won’t accidentally fire prematurely and cause memory leaks. It’s often used with functions like addEventListener() and removeEventListener(), which are used for attaching and removing event listeners from DOM elements.
Generator functions are special kind of functions that returns a Generator Object, generator object behaves like an iterator. You can use the next() method to iterate over a generator function. The difference between generator and normal function is, that whenever we call a normal function in JavaScript it returns a value while calling a generator function it doesn’t return any value until we call next() on it. If you call the .next() method without passing any argument then it will return the first result from an iterator and its execution stops there.
JavaScript has two global variables (exports & imports) which are used to export and import functions from one js file to another. We can read or write these values using require(), module.exports() and module.require(). Exporting means to share a value with other files that are not included in your file by default or want to import a value into your own file so that you can use it later on.
Recursion is a method of defining an operation within its own definition or calling an instance of itself. It is used when a problem involves self-similarity, where it can be defined in terms of simpler instances that are not yet solved.
Rest parameter and spread operator are used for destructuring assignment. Rest parameters is a way to represent an indefinite number of arguments as an array. The spread operator is used for expanding a list into individual elements.
Event handling in JavaScript is a very important concept to grasp. Let’s look at a few different ways you can handle events in JavaScript. Some events, like mouse clicks and key presses, happen on their own but there are other ways to create an event. You can also create custom objects that act as an event source by defining your own events for them.
Location object provides various properties like href, protocol, hostname, port, pathname, etc. These properties are used to represent and work with page location information. The href property represents the URL of the current page or link which is clicked by the user in the web browser. The protocol property represents the HTTP or HTTPS protocol of the current page or link which is clicked by the user in the web browser. The hostname property represents the domain name of the current page or link which is clicked by user in the web browser.
In JavaScript, Promises are objects which help with asynchronous programming. They are used to wrap a function that might take some time to complete and return its result. In order to use them in your code, you need to wait for that promise object’s then method to get called. Once it gets called, then you can continue with whatever task you wanted that function for in the first place!
MEAN is an acronym for MongoDB, ExpressJS, AngularJS, and Node.js and refers to a commonly used stack for full-stack JavaScript web development. The MEAN stack helps you quickly build scalable single-page applications (SPAs) by using powerful frameworks that are already in place on each layer of your application.
Using JavaScript, you can easily modify a URL without reloading a page. This is useful for tracking analytics and providing links to external pages. To do so, use document.location = newURL; on your code where newURL contains your desired URL string.
The console object provides debugging facilities for your web application. It allows you to inspect variables and objects, log messages, and interact with a script in real-time. The console object is implemented as a Web Worker so its API is only available inside of one. console.dir () will return an array containing all of an object's properties while console.log() will print out that object's stringified value (or null if it doesn't have one).
In JavaScript, a microtask is an asynchronous task that runs immediately in parallel to a scheduled microtask and then queues it as a task to be executed later.
JavaScript doesn’t have a native Garbage Collector like Java, C#, or other popular programming languages. But it has its own ways to free up unused memory. So let’s see how JavaScript Garbage Collector works? JS Garbage Collector follows the mark and sweeps algorithm to reclaim memory. This process is called garbage collection because these objects are no longer needed by an application and can be deleted from memory.
A proper tail call is a function that doesn’t return anything, but rather just calls another function. This is useful in many situations. For example, with tail recursion, you can emulate loops to avoid stack overflows or memory leaks.
Type coercion refers to changing a value from one type to another. For example, if you pass an object where a number is expected or vice versa. Type Coercion can be useful but it can also lead to errors.
JavaScript allows you to use escape characters in strings. These characters let you include new line and tab characters in a string without actually writing them. This can be useful for including multiline text or HTML in your strings.
The debuggers provide a window into what is going on inside your code as it executes. They allow you to watch variables, change values and step through your code one line at a time.
The main difference between attributes and properties is that property represents a data storage location in memory while attribute only provides metadata information about an object. Both can be created by declaring a data member of some kind, but they serve completely different purposes.
NEGATIVE_INFINITY is a special number in JavaScript, It is negative infinity. The value can be set by Math.abs(number) or it can be triggered as an exception.
An Event object can travel up and down through elements on a page as it's triggered by users interacting with that page. This process is known as event bubbling. Event Capturing, on the other hand, only allows an event to trigger handlers attached to its direct parent element.
Deferred scripts are scripts that have yet to be executed. Using deferred scripts in JavaScript allows for code to run asynchronously in a particular order, rather than all at once. This is often useful when you’re using asynchronous functions within your code.
JavaScript is case-sensitive in terms of variable names and property names, but not method and function names. The answer is no to your question.
JavaScript’s prototypal inheritance has some similarities to classical inheritance, but there are also many differences. Knowing both will help you choose what works best for your application.
Both call and apply are ways to execute a function with an array of arguments. Apply takes an array as its first argument and call take a reference to a function as its first argument. The key difference is that apply will create a new scope for any variables defined in its arguments, while calls will use whatever scope is currently active.
JavaScript has many advantages over other programming languages because it enables us to add interactivity to websites and applications, so users can actually interact with these products or websites.
JavaScript does not support method overloading. It's a language feature available in other languages, like Java and C++, where it means that a class or object can have multiple methods with the same name as long as they have different parameters.
When using external JavaScript files, it's important to make sure they are hosted on a different domain than your website. If you're creating a website with WordPress, you may be able to upload your scripts via FTP, which is outside of WordPress' control.
In computers and programming, a historical object is one that does not contain state. In JavaScript, for example, all objects have methods.
The scope of jobs in which JavaScript is used is very large, as you may know, it is considered a client-side scripting language. It helps in managing web pages and creating animations, complex user interfaces, etc. In this article, we learned the Top JavaScript Questions that help to crack your next interview. This is a detailed explanation of each and every question so that you can practice it in a better way.
Thanks for reading this article. If you found value in my post and want to return the favor, feel free to share it with your friends and colleagues on social media!
Fawzan Hussain
An SEO consultant and the CEO of Seooptimizekeywords.com. With over a decade of experience in the industry, I'm passionate about helping businesses achieve their online marketing goals through effective SEO strategies.
See other articles by Fawzan
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!