Top 30 JavaScript Interview Questions
JavaScript has emerged as a frontrunner in the field of web development, commanding an unparalleled presence across the digital landscape. And with its ever-increasing demand, mastering JavaScript opens doors to exciting career opportunities and boundless potential.
Here, you will find the top JavaScript interview questions and expertly crafted answers that will help you conquer the most challenging technical interviews with ease. Whether you're an experienced developer or an aspiring developer looking to kickstart your career, this guide is for you.
To excel in JavaScript, you must grasp its core concepts with a reliable web developer course. Acquiring a strong foundation in JavaScript frameworks and libraries like React, Angular, or Node.js will elevate your skills to new heights, making you an invaluable asset in the software development landscape. So, let’s get started and learn about the interview questions on JavaScript (JS).
JavaScript Interview Questions for Experienced
In JavaScript, currying is a special feature that allows you the change the way to invoke a method. When a function of an argument is changed into functions of one or more arguments, it is known as currying.
So, it eagles you to concert a specific function with y arguments into y functions with one or less than one argument. Please remember currying doesn’t change the working of functions but only changes the way it is invoked.
Example:
function add (a) {
return function(b){
return a + b;
}
}
add(3)(4)
So, function f(a, b) will be transformed to f(a)(b) after currying.
In JavaScript, memoization is a caching technique used by developers. When a return value of a function is cached according to its parameters, it is known as memoization. It speeds up the application, especially for complex and time-consuming functions.
When a function is called without changing the parameters, it returns the cached version without computing the value.
Hence, making the script more time efficient and optimal. However, memoization is not as useful a concept as it seems. It needs a significant amount of memory for caching and storing a value. Also, it is mostly used for expensive function calls.
There are three possible ways to define a variable in JavaScript:
-
Var: This statement is used to declare a variable, and we can change the value later within the JS code. We must declare a variable before executing the code.
-
Const: This is another way to define a variable, but the value is constant through the program. So, you can’t modify the value later. When you declare a function as a constant, it is possible to call it on any type of object.
- Let: It implies that the value can be changed or reassigned later within the program. Also, it signals that a variable is used within the block it is defined.
Anonymous function in JavaScript is a special type of function that is declared without a name. Generally, we use a function keyword followed by the name of the function. However, in an anonymous function, there is no function name but just the function keyword.
Moreover, it can’t be accessed anywhere in the script apart from after its declaration because to implement this function; we need to use the function expression, which doesn’t support hoisting.
Anonymous function declaration
var disp = function(){
alert(“This is anonymous function”);
};
disp();
As an anonymous function doesn’t have a name, we use a variable name to invoke it. This function may seem similar to function expression, but there is a difference between the two.
An anonymous function has only one expression in the body, whereas the function expression can have multiple expressions. However, they both can have multiple arguments.
The scope of a variable in JavaScript determines the accessibility of functions and variables in different parts of code. So, it tells us about the functions and variables we can or can’t access at a specific part of the code. It implies where a variable is declared or defined in a JS program.
There are mainly two types of scopes:
Global Scope-
Functions or variables declared in a global namespace have global scope, so they are available everywhere and can be accessed from anywhere within the code.
Local Scope-
Functions and variables declared within a function have local scope. So, they are accessible and visible only within the function in which they are defined and not outside of it. Function parameters are always local to that particular function.
NaN, or Not a Number, compares unequal to numbers. It indicates an error condition for a function that must return a valid number. We see NaN when a string or anything else is converted into a number.
The prototype design pattern, also known as a prototype or property pattern, is used to produce different objects and prototypes replicated from a template with a value. So, as the name suggests, this design pattern is used to create prototypes.
One great example of where a prototype design pattern can come in handy is a business object with parameters matching the default setting of the database. The prototype object stores the default setting of the newly introduced business object.
This pattern is rarely used in traditional languages but is popular for the development of new objects and templates in JS, a prototypal language.
Promises handle asynchronous operations in JavaScript, such as server requests. Before the introduction of promises, we used callbacks to handle these operations. However, callbacks had limited functionality and using it can result in unmanageable code. Therefore, JavaScript came up with premises.
Promises have four states, which are as follows:
To create a promise, the promise constructor is used, which takes in a callback function with two parameters, namely resolve and reject.
The resolve function is invoked when the async operation is fulfilled.
The reject function is called when the async operation fails or there is some error.
-
Var: This statement is used to declare a variable and initialise the value of that variable, but this is optional. Also, the variable declaration is made before executing the code.
-
Const: The const functions don’t allow them to modify the objects o which they are called. Once a function is declared const, you can call it on any type of object.
-
Let: Let is a signal indicating that a variable may be reassigned, such as a value swap in an algorithm or counter in a loop. It also shows that you can use a variable only in the block it is defined in.
Recursion is a key concept in programming and is supported by almost every programming language. It is a programming technique to iterate over an operation while a function calls itself again and again until we achieve the result.
This function calling can be direct or indirect, and the function involved in recursion is known as a recursive function. For example,
If you want to calculate the sum of the first 10 numbers, you can use a simple loop, i.e., 1+2+3+4+...+n. However, there is another way known as recursion that you can use to solve a problem without much effort and efficiently.
int sum(int n){
if(n < 1)
return 0;
else {
return n + sun(n-1);
}
}
So, whenever you solve such problems, we would recommend using recursion if possible, as it is considered a better and clean way of programming.
-
Var has been used in JavaScript programming from the beginning, whereas let was added in 2015 in JS.
-
Var keyword has a function scope, which means we can perform functions using var. Any variable specified using the var keyword is accessible. However, let provides a limited scope of a declared variable to the block in which it is declared.
-
Let was hoisted in ECMAScript 2015 but was not initialized. When you reference a variable in a block before declaring a variable, it results in a ReferenceError, as that variable is in a temporal dead zone from the beginning of the block until the declaration is completed.
Similar to other programming languages, JavaScript also has escape characters that enable you to write special characters without affecting or breaking the application.
They are used while working with special characters, such as double quotes, single quotes, ampersands, and apostrophes. You need to put a backslash or escape character before these special characters to display them.
JavaScript lets the system know that a different character must be printed. The escape character in JavaScript is a backslash ‘\’.
For example
document.write, "This is “my” name."
Now, in the given statement, we want to print the string my with double quotes, but this will confuse the compiler, and it will show an error thinking that a double quote before ‘my’ is the final quote for the first double quote used before ‘This’.
And the compiler will think that the string has ended. So, to print my with double quotes, we will use a backslash as shown below:
document.write "This is \"my\" name"
In general, type conversion allows developers to convert a specific data type into another data type. For example, you can convert numbers to strings through the following statement:
String();
Here, a can be any number.
The following statements are also used for conversions:
-
Converting Dates to Numbers- Number(a);
-
Converting Strings to Numbers- Number(a);
-
Converting Dates to Strings- String(a);
Both ‘==’ and ‘==== operators are used for comparison, but there are a few differences between the two.
‘==’ is used to compare values while ‘===’ is used to compare values along with data types of variables.
‘==’ compares variables through type correction. So, if you compare a string with a numeric literal, it will support it. However, ‘===’ doesn’t support it as it checks the values and data types of two variables. So, if the variables are not of the same type, it will return false.
Many programming languages support ‘==’ but ‘===’ is supported by limited programming languages, JavaScript is one of them.
Example:
var a = 5;
var b = "5";
(a == b) //Returns true as the value of both a and b is the same
(a === b) // Returns false as the type of a is "number" and typeof b is "string"
The call() is a predefined method in JavaScript that invokes a function with a ‘this’ value. It takes individual arguments.
Syntax
fun.call(thisArg[, arg1[, arg2[, ...]]])
The apply() method is almost similar to the call() method, but the difference is it takes arguments as an array. It also invokes a function with ‘this’ value.
Syntax
fun.apply(thisArg, [argsArray])
ECMAScript 5 introduced a new feature called JavaScript Strict mode that ensures more stringent checking in a JS code. It enables you to write code or function in a strict operational environment. JavaSript is not particularly strict in throwing errors, but with the Strict mode, it throws all types of errors, even silent errors. Hence, making debugging easier and reducing the chances of errors that a programmer can make.
In the Strict mode, all variables are declared explicitly, and values can’t be assigned to a read-only property. To enable the Strict mode, add ‘use strict’ at the start of your JS code or within a section of code.
Features of the Strict mode in JavaScript
-
The ‘use strict’ keyword defines the Strict mode at the beginning of the script.
-
All browsers support this mode.
-
You can’t use the JavaScript keyword as a function name or parameter in the Strict mode.
-
Engineers can’t create global variables in this mode.
JavaScript Interview Questions for Freshers
JavaScript, also known as JS, is a popular scripting programming language used for client-side and server-side development. It works best when integrated with front-end language, such as HTML and is compatible with only browsers. You can insert the JavaSCript code into HTML pages, understood and executed by web browsers. It also supports object-oriented programming abilities, such as objects.
JavaSript and Java may sound similar, but they are two different programming languages. Both of them are designed for different purposes. JavaScript is a client-side scripting language, while Java is a backend language.
JS must be integrated with some sort of front-end language like HTML, whereas Java is an independent language. Moreover, JavaScript is a scripting language and doesn’t completely support OOP concepts. On the other hand, Java is an object-oriented programming language that deeply supports OOPs concepts.
Here is a table showing the difference between JavaScript and Java in detail:
Know more about Java in this Java Tutorial.
There are several data types that JavaScript supports, which are listed below:
-
Boolean: For true and false values
-
Undefined: For variables that are declared rather than defined or initialized
-
Object: For collections or complex values
-
Number: For integers and floating-point numbers
-
Null: For empty or unknown values
-
String: For characters and alphanumeric values
-
Symbols: For unique identifiers for objects
JavaScript offers the following advantages over other programming languages:
-
Rich User Interface: Programmers use JavaScript to include elements, such as drag-and-drop features and sliders, adding a rich user interface to your web applications and making them look much better.
-
Frameworks: JavaScript is known for its countless libraries and frameworks that are used for developing different types of web applications and games.
-
Server Interaction: It allows you to validate user input before you send the web pages off to the server. This helps save the server traffic, which puts less load on the server.
-
Instant Feedback: When running JavaScript, visitors don’t have to wait for the page to reload to see if they have missed entering something, such as form input validation.
-
Interactivity: JS allows you to create interactive interfaces that react as you activate them using the keyboard or hover over them using the mouse.
The ‘this’ keyword in JavaScript means the object that the function belongs to. It refers to the currently calling object and is used in constructors to assign values to properties of objects. The ‘this’ keyword can have different values based on where it is used and the object invoking the function.
In a method, ‘this’ signifies the owner object, whereas in a function, ‘this’ means the global object.
The following are the features of JavaScript language:
-
It is a lightweight, interpreted programming language.
-
It is integrated with Java and other front-end technologies.
-
It offers cross-platform compatibility.
-
It is an open-source scripting language.
-
It is specifically used to develop network-based applications.
-
It supports object-oriented programming but is not entirely like Java.
-
It is complementary to Java.
-
Pass by value
In JavaScript, ‘pass by value’ allows you to invoke functions by just passing a value of a variable as an argument. When you use this concept, functions create a different copy of the variable.
Hence, any changes in the value of a variable will not affect its actual value. For example, Var a is passed as an argument to a function sum(). So, sum() will first create a copy of variable a and then when the function sum() will modify the value of the variable, there will be no changes in a.
-
Pass by reference
In JavaScript, pass by reference enables you to invoke a function by passing the address of a variable as an argument. Any changes or modifications in the value of an argument will be reflected in the actual variable.
For example, if var a is passed as an argument using the pass-by-reference and there are any modifications in the variable using method sum(), variable a will also have the impact of the modification.
We have listed conventions for naming a variable in JavaScript, which are as follows:
-
You can’t use a reserved word, also known as a keyword, as a variable name. For example, boolean or break as variable names are invalid.
-
In JavaScript, variable names are case-sensitive. For example, test and Test are considered two different variable names.
-
Names of variables can’t start with a numeral (0-9). The names should start either with a letter or an underscore character. For example, you can’t use 123variable as it is invalid but can use _123variable or variable123.
In JavaScript, functions are treated as objects, so they can take other functions as arguments and can also be returned by other functions. There is a function known as hoisting, which considers all declarations as a top priority and executes them in the first place.
To counter this effect, JavaScript has introduced a concept known as callback. It is a JavaScript function passed to another function as an argument. The function is automatically executed after another function is executed completely. That is why it is called callback.
Closures offer a better and more concise way of writing code in JavaScript. They are created whenever a variable defined outside the current scope is accessed within the inner scope. It allows access to the outer function scope from within an inner function.
Every time a function is created, closures are created as well. If you want to use a closure, define a function within another function and expose it.
function hello(name) {
var message = "hello " + name;
return function hello() {
console.log(message);
};
}
//generate closure
var helloWorld = hello("World");
//use closure
helloWorld();
A cookie is a small amount of data sent from a website and stored on users’ systems by a web browser used to access that website. Cookies remember information that can be used later and also records the browsing activity on a website.
A simple way to create a cookie is by assigning a string value to the document.cookie object. We have shown this in detail below:
document.cookie = "key1 = value1; key2 = value2; expires = date";
Reading a cookie is as simple as creating a cookie as the value of the document.cookie object is a cookie. So, to access a cookie, you can use the document.cookie string containing the cookies that you just created using the same string.
The document.cookie keeps the list of name-value pairs separated by using semicolons. Here, the name refers to the name of the cookie, and value refers to its string value. Moreover, you can use the split() method to break a string into keys and values.
To delete a cookie so the subsequent attempts to read a cookie return nothing, you simply need to set the expiration date and time. Make sure to define the cookie path properly so that you delete the right cookie.
Also, mentioning the correct path of a cookie that you want to delete is a good practice, as some browsers don’t allow you to delete cookies unless you specify a clear path that indicates which cookie must be deleted from the machine.
function delete_cookie(name) {
document.cookie = name + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}