JavaScript is one of the most popular programming languages basically used for frontend development. It was developed by Brendan Eich in 1995 to create dynamic web pages. Since then, it has been widely used to develop web applications and is an essential skill for front-end developers. Therefore, to build a career in front-end development, you need to understand JavaScript in detail. Have a look at our compiled list of basic JavaScript interview questions and answers to help you understand the language well.
1. What is JavaScript?
JavaScript is a high-level, scripting language that can be used to create interactive and dynamic web pages. It can be written to HTML pages, enclosed in script tags, and the web browsers function as per the script. The scripting language can also act like an object-oriented language. However, it is not based on classes.
2. What are the benefits of using JavaScript?
The language can be chosen for development for multiple reasons.
- Ease of use.
- Modern Web Browsers Support.
- Useful for both Front-end and Back-end Development.
- Fast and responsive.
- Open-source language.
- Versatile to be used to many applications.
- Used for many modern frameworks, like React, and Angular.
3. What Data Types JavaScript has?
JavaScript has two main Data Types.
- Primitive Datatypes
- Non- Primitive Datatypes
4. What are the Primitive Data Types in JavaScript?
The primitive data types in JavaScript are:
- Undefined
- Null
- Boolean
- Number
- String
- Symbol (new in ECMAScript 6)
5. What is the difference between the main Data Types in JavaScript?
Primitive Datatypes | Non-Primitive Datatypes |
The string data type represents a sequence of characters or a combination of characters, For example the string “Hello World”. | Object data type represents instances through which we all can access members. |
Boolean data type represents a Boolean value that can be either true or false. | RegExp represents a Regular Expression. |
The number data type represents numeral values. like 2000, 500, etc. | Arrays represent a group of similar types of data. |
Undefined:-it Represents undefined value or not defined values. |
6. What is the difference between null and undefined in JavaScript?
Undefined and Null are both used to represent empty values in JavaScript, but they are not the same. Undefined is a value that represents the absence of any value. Whereas, null is a value that represents the absence of any object value.
7. What is the basic use of the NaN function in JavaScript?
The function will return true if the argument is not a number. However, if the argument is a number, then it returns as false.
8. What are the different types of operators used in JavaScript?
- Assignment operators (=, +=, -=, *=, /=, %=)
- Arithmetic operators (+, -, *, /, %)
- Comparison operators (==, ===, !=, !==, >, <, >=, <=)
- Logical operators (&&, ||, !)
- Bitwise operators (&, |, ^, ~, <<, >>, >>>)
9. What is a variable in JavaScript?
The named container can hold any value in JavaScript. A variable is used to store data that can be accessed and manipulated by the program.
10. What are the different types of variables in JavaScript?
There are namely three main types of variables can be used in Javascript.
- var
- let
- const
Each has their own scope and reason for usage.
11. What is the difference between the different variables in JavaScript?
All three are used to declare variables in JavaScript, but they have different scoping rules. Var has a function scope, i.e. it can be accessed anywhere within the function it is declared in. Let and const have block-scope, i.e. they can only be accessed within the block they are declared in. Moreover, Const is a constant variable whose value cannot be changed once it is declared.
12. What is the difference between a function declaration and a function expression in JavaScript?
A function declaration is a statement that declares a named function, whereas a function expression is an expression that creates an unnamed function. Therefore, the main difference between the two is that function declaration are hoisted, while function expressions are not.
13. What is hoisting in JavaScript?
Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their respective scopes before the code is executed. This allows variables and functions to be used before they are declared.
14. What are undeclared and undefined variables?
Undeclared Variables are the ones not declared in a program. This often leads to runtime errors. When a variable that is not declared is used in a program.
Undefined variables are the ones that are declared but hold no value. This happens when no value is passed to a variable. It may result in an ‘Undefined Variable’ error when the program wants to read the variables’ value.
15. What is the purpose of closures in JavaScript?
The powerful feature of JavaScript allows a function to access variables from its outer scope, even after the outer function has returned. Closures are useful for creating private variables and functions that cannot be accessed from outside the function.
16. What is the difference between call and apply methods in JavaScript?
The call and apply methods are used to invoke a function with a specific value for the “this” keyword. The main difference between the two is that call takes individual arguments, while apply takes an array of arguments.
17. What do you mean by Global variables in JavaScript?
The variable which is not bound to any scope or is available throughout the length of the code is called the Global variable.
18. How can you define a Global Variable in JavaScript?
For declaring a local variable, a var keyword is used. It is also applicable for declaring an object. When there is the commission of the var keyword, then the global variable is declared. It is preferable to declare global variables on top of a program.
19. How is the ‘this’ keyword in JavaScript?
The ‘this’ keyword is used to point to the current object in Java. However, in JavaScript, the ‘this’ keyword refers to the object from where it is called. Therefore, it refers to the object it belongs to.
20. How and where can the ‘this’ keyword be used in JavaScript?
The ‘this’ keyword has different values according to or depending upon where it is used.
- It can be used in a method, here it refers to the owner object.
- It is used in a function, then this refers to the global object
- It can be used in a function, in strict mode, here it remains undefined.
- It can be used in an event, here it refers to that respective element that receives the event.
- It can also be used alone, then it refers to the Global object.
Call() and apply() method refer ‘this’ to any object.
21. What are the basic timers used in JavaScript?
Timers are used to execute specific code snippets at a set time and repeat the bit of code in a given interval.
This is done by using the setTimeout, setInterval, and clear interval functions in JavaScript.
22. Explain the functioning of each timer in JavaScript.
The setTimeout function has a syntax like setTimeout(function, delay)
, and is used to start a timer, then call a particular function after the mentioned time delay.
The setInterval function has a syntax like setInterval(function, delay)
, and is used to repeatedly execute the given function inside with the mentioned time delay and only stops when it is canceled.
The clearInterval function has a syntax like clearInterval(id)
, and instructs or indicates the timer to stop (for stopping the given or mentioned function).
23. How can we comment code in JavaScript?
Single line comments: “//”.
Multi-line comments can be enclosed in: “/* commented code */”.
24. What are the different functions to remove array elements in JavaScript?
JavaScript has numerous functions for arrays. The ones to remove elements from an array are slice and spice. They may sound similar but have a different purposes.
25. What is the difference between slice and splice in JavaScript?
Slice returns a shallow copy of a portion of an array, while splice removes or replaces elements of an array in place.
26. What are the different types of loops used in JavaScript?
The scripting language used the basic looping structure, i.e for
, while
, and do-while
loop. Moreover, we can use a foreach
loop to go through each element in an array, and a for-in
loop to iterate over an object.
27. What is the difference between a for loop and a for-in loop in JavaScript?
A for
loop iterates over a block of code a specified number of times, while a for-in
loop iterates over the properties of an object.
28. What is the difference between a while loop and a do-while loop in JavaScript?
A while
loop checks the condition before the loop is executed, while a do-while
loop executes the loop at least once before checking the condition.
29. How to differentiate between a promise and a callback in JavaScript?
A promise is an object that represents a value that may not be available yet, while a callback is a function that is passed as an argument to another function and is executed when the other function is finished.
30. What is the difference between synchronous and asynchronous code execution in JavaScript?
Synchronous code execution means that the code is executed in a linear fashion, while asynchronous code execution means that the code is executed out of order, allowing other code to run in the meantime.
31. What is event bubbling in JavaScript?
Event bubbling is a behavior in which an event that is triggered on a child element is also triggered on its parent elements.
32. What is event delegation in JavaScript?
Event delegation is a technique in which events are handled by a parent element, rather than individual child elements.
33. What is the difference between == and === operators in JavaScript?
JavaScript has two equality operators, i.e. == and ===. Operators with three equals sign, i.e. === or !=== are called strict comparison operators. The strict operators take the type of variable into consideration, while non-strict operators make type corrections/conversions based on the values of variables. Find more details on the difference between the == and === operators.
34. How do we encode a URL in JavaScript?
We can use the encodeURI() function to encode a URL. The function takes in a string URL as the parameter and returns an encoded string.
35. How do we decode a URL in JavaScript?
We can use the decodeURI() function to decode a URL. The function takes in an encoded URL string as the parameter and returns a decoded string.
36. How can you create an object in JavaScript?
JavaScript supports Object concepts and allows you to create an object using the object literal as shown below.
var emp = {name: "Mary",age: 22};
37. How can we create an Array in JavaScript?
You can define arrays using the array literal as shown below.
var a = [];
var b = [10, 22, 35, 48, 52];
38. How can you find the length of an array of string in JavaScript?
The JavaScript built-in length() function can be used to find the length of a string or the number of elements in an array. Consider the code snippet below.
var b = [10, 22, 35, 48, 52];
console.log(b.length);
// outputs: 5
39. How is the Type Of Operator used in JavaScript?
The type of operator can be used to get the data type of its operand. The operand can either be a literal or a data structure such as a function, variable, or object. The unary operator is placed before its single operand, that can be of any type.
40. How can we create a cookie in JavaScript?
A simple way is to assign a value using the document.cookie object as shown below.
document.cookie = "key1 = a; key2 = b; expires = date";
41. How can we read a cookie using JavaScript?
We can simply read a cookie similar to how we write it. We can use the document.cookie object to read or write a cookie.
42. How can we access an HTML element in JavaScript?
We can use different methods to access HTML elements as shown below.
- getElementsByClass(‘classname’): retrieves the elements that can be read by the given class name.
- getElementById(‘idname’): retrieves the element by its ID name.
- getElementsByTagName(‘tagname’): retrieves all the elements that have the given tag name.
- querySelector(): The function takes the CSS style selector and returns the first selected element.
43. What is the main difference between innerHTML & innerText?
innerHTML: processes an HTML tag if found in a string.
innerText: will not process an HTML tag if found in a string
44. How to parse a string to an integer in JavaScript?
The parseInt() function converts numbers between different bases in JavaScript. It takes the first parameter as the string to be converted, while the second is the base of the string.
45. What is the purpose of exports and imports in JavaScript?
The export declaration can be used to export values from JavaScript. module. These values can then be imported into other programs using the import declaration.
46. What is a promise in JavaScript?
A promise is an object that can produce a single value at times in the future whereas a resolved value or a reason that it’s not resolved(for instance, a network error). A promise can be in either of one state, fulfilled, rejected, or pending.
47. Why do we need a promise in JavaScript?
Promises can handle asynchronous operations. They give an alternative approach for callbacks as they reduce the callback hell and write a cleaner code.
48. What is a Callback hell in JavaScript?
Callback Hell makes an anti-pattern with multiple nested callbacks that makes the code harder to read and debug when it deals with asynchronous logic.
49. What is the difference between window and document in JavaScript?
Window | Document |
The root level element of any page. | The direct child of the window object. Also referred to as the DOM (Document Object Model). |
Window object is available implicitly on the page. | You can access it via window.document or document method. |
Uses methods like window.alert()or window.confirm and has properties like window.location. | It has methods like document.getElementById, document.getElementsByTagName, or document.getElementsByClassName. |
50. What is the purpose to use the strict mode?
The mode is useful to write ‘secure’ JavaScript code and makes bad syntax turn into real errors.
51. What is the purpose of the delete operator in JavaScript?
The delete keyword helps to delete a property and its value. Consider the code snippet below.
var user = { name: "Alice", age: 25 };
delete user.age;
console.log(user); // {name: "Alice"}
Let’s have a look at some Advanced JavaScript Questions and Answers that will help you crack your interview!
51. What is the strict mode in JavaScript?
Strict Mode is a new JavaScript feature that allows one to place a program, or a function, in a “strict” operating context. Therefore, it prevents taking some actions and throws exceptions. The “use strict
” expression is used for this.
52. What are Escape Characters in JavaScript?
JavaScript escape characters enable us to write special characters without breaking an application. You can use Escape characters (Backslash) when working with special characters like single quotes, double quotes, apostrophes, and ampersands. Placing a backslash before the characters can help them display without breaks.
53. How can we create a key-value pair in JavaScript?
We can use two different ways to create key-value pairs in JavaScript. Consider the code snippets below.
Method 1:
var object = {
key1: v1,
key2: v2,
};
Method 2:
Using the dot notation
object.key3 = "v3";
Method 3:
Using the square bracket notation.
obj["key3"] = "v3";
54. How to generate random integers in JavaScript?
The Math.random() and Math.floor()functions. helps return random integers.
55. How to use a Regular Expression in JavaScript?
A regular expression defines a sequence of characters that helps match a specific pattern. We can use it to validate a string. Most useful to validate emails and contact details.
56. Which string methods can be used in Regular expressions?
The two string methods of search()
and replace()
can be used with regular expressions. The search()
method uses an expression to search for a match while the replace method returns a modified string while replacing the pattern.
57. What modifiers are used in regular expression in JavaScript?
Modifiers are useful to perform case-insensitive and global searches. Consider the modifiers as shown below.
Modifier | Detail |
g | For a global match rather than stopping at the first match |
i | For case-insensitive matching |
m | For multiline matching |
58. What details are added in regular expression patterns?
Regular Expressions contain a group of patterns to match characters. They are categorized into 3 main types.
- Brackets are used for a range of characters. For example [0-9] for numerals 0 to 9 or [abc] for characters a, b, and c.
- Metacharacters have a special meaning. For example, \d is used to find a digit, \b. to match the start or end of a word or \s. for a. whitespace character.
- Quantifiers are used to define quantities like n+-to match strings that have at least one n or n? for strings that contain a 0 or single occurrence of an n character.
59. What does the exec method does in JavaScript?
The exec method is similar to test methods, but it also does a search to find a match for a specific string pattern or a result array.
60. How can we change the style of an HTML element using JavaScript?
We can refer to the element by using the document.getElementById method and apply any styling as shown below.
document.getElementById("title").style.fontSize = "25px";
61. How to add inline css in JavaScript for any element?
We can pass styling for an element in JavaScript and create a styling node in JavaScript for that element.
62. How can we detect a mobile browser without regexp?
We can detect mobile browsers by running through a list of devices and checking if a user agent matches anything. Consider the code snippet as shown below.
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPod/i) ||
navigator.userAgent.match(/BlackBerry/i) ||
navigator.userAgent.match(/Windows Phone/i)
63. How do we make a synchronous HTTP request in JavaScript?
An XMLHttpRequest object can be used to make synchronous HTTP requests in JavaScript. Consider the code snippet as shown below.
function httpGet(theUrl) {
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open("GET", theUrl, false); // false for synchronous request
xmlHttpReq.send(null);
return xmlHttpReq.responseText;
}
64. How do we make an asynchronous HTTP request in JavaScript?
An XMLHttpRequest object can be used to make an asynchronous HTTP request in JavaScript by passing a 3rd parameter as true. Consider the code snippet as shown below.
function httpGetAsync(theUrl, callback) {
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
callback(xmlHttpReq.responseText);
};
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
65. How can we convert a date into a different timezone using JavaScript?
The toLocaleString() method converts dates from one timezone to another. For example, to convert the current date to British English timezone, you can write the code as shown below.
console.log(event.toLocaleString("en-GB", { timeZone: "UTC" })); //29/06/2019, 09:56:00
66. How can we get the size of a window?
The innerWidth, innerHeight, clientWidth, and clientHeight of windows, document body objects, or document element helps find the size of a window or a document.
67. What is the conditional or ternary operator in JavaScript?
The only JavaScript operator that takes three operands and acts as a shortcut for if statements. Consider the code snipper below.
var isAuthenticated = false;
console.log(
isAuthenticated ? "Hello, welcome" : "Sorry, you are not authenticated"
); //Sorry, you are not authenticated
68. How can we execute a JavaScript code snippet after page load?
We can define whether to load a script before or after a page or browser loads. To make a JavaScript code snippet load before page load, write the code as shown below.
window.onload = code snippet ...
69. What is the freeze method in JavaScript?
The method helps to freeze an object and allows the addition of new properties to an object. In addition, it also helps remove. and prevent changing reconfigurability, enumerability, or writability. or any other existing properties.
70. When should we use the freeze method in JavaScript?
In the Object-oriented paradigm, an existing API contains certain elements that are not intended to be extended, modified, or re-used outside of their current context. Therefore, it works as the final
keyword which is used in various languages.
71. How can we use the assign method in JavaScript?
The main applications of Object.assign() method are:
- To cloning an object.
- To merge objects with the same properties.
72. What is a proxy object in JavaScript?
The Proxy object helps define custom behavior for fundamental operations like property lookup, enumeration, assignment, function invocation, etc. Consider the code snippet below to use a proxy object.
73. How to use the seal method in JavaScript?
The Object.seal() method helps to seal an object, prevents new properties from being added to it, and marks all existing properties as non-configurable. For example, consider the code snippet below on how to use the sealing method in JavaScript.
const object = {
property: "Welcome JS world",
};
Object.seal(object);
object.property = "Welcome to object world";
console.log(Object.isSealed(object)); // true
delete object.property; // You cannot delete when sealed
console.log(object.property); //Welcome to object world
74. What are the uses of the seal method in JavaScript?
The main applications of Object.seal() method in JavaScript are as follows.
- To seal objects and arrays.
- To make an object immutable.
75. What is the main difference between seal and freeze methods in JavaScript?
If an object is frozen using the Object.freeze() method then its properties become immutable and no changes can be made to them whereas if an object is sealed using the Object.seal() method then the changes can be made in the existing properties of the object.
Let’s have a look at some Coding related JavaScript Questions and Answers that will help you practice your practical questions!
78. How will you reverse each word in a sentence for any string. in JavaScript?
Suppose ‘Welcome to this Javascript Guide’ should become ‘olleH dlroW’. You will write the code snippet as shown below.
var string = "Welcome to this Javascript Guide!";
// Output becomes !ediuG tpircsavaJ siht ot emocleW
var reverseString = reverseBySeparator(string, "");
// Output becomes emocleW ot siht tpircsavaJ !ediuG
var reverseEachWord = reverseBySeparator(reverseString, " ");
function reverseBySeparator(string, separator) {
return string.split(separator).reverse().join(separator);
}
79. How can you check if a number is an integer in JavaScript?
The simple code snippet is to divide a decimal or integer by 1 and check the remainder left behind, as shown below.
function isInt(num) {
return no % 1 === 0;
}
console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false
80. What is the output of the code given below?
(function() {
var a = b = 15;
})();
console.log(b);
The above code will give an output of 15 even though it seems as if the variable was declared within a function and can’t be accessed outside of it. This is because var a. = b = 15 is interpreted as var a = b, which makes b = 15. Even though b
is not declared anywhere in the function using var or any other keyword, it is declared as a global variable with a value of 15.
81. Write a function to multiply two variables.
We can write a closure function that returns a specific value. We will write two functions, one inner and one outer as shown in the code snippet below.
function multiply(x) {
return function(y) {
return x * y;
}
}
multiply(10)(2);
82. How can we empty an array in JavaScript?
Consider the code snippet as shown below.
var array = ["10","12","18","20"];
var newArray = array;
console.log(newArray); // ["10","12","18","20"]
array = []; // empties the array
OR
array.length = 0; // empties the array
OR
83. How can we dynamically add new elements.
<html>
<head>
<title>t1</title>
<script type="text/javascript">
function addNode() {
var newElem = document.createElement("p");
var textNode = document.createTextNode("This is a new text node");
newElem.appendChild(textNode); document.getElementById("firstElem").appendChild(newElem); }
</script>
</head>
<body>
<p id="firstElem">First Element<p>
</body>
</html>
84. Write a code snippet that can forcibly load another page.
<script language="JavaScript" type="text/javascript" >
<!-- location. href="https://www.scratchcoding.dev/javascript-interview-questions-answers.html"; //-->
</script>
85. Write a code snippet on how to use escape characters with backslashes.
document.write "I m a "good" programmer."
document.write "I m a \"good\" programmer.
Escape characters (Backslash) work with special characters like single quotes, double quotes, ampersands, and apostrophes. You can place a backslash before the characters to make it display properly.
86. How does the pop() method works in JavaScript. Explain using code samples.
var subjects = ["Maths", "Science", "English"];
subjects.pop();
//Now subjects will have Maths, Science
87. How can we assign properties to objects?
We can either use the dot or bracket notation to assign properties to an object. For example, consider the code snippet below.
objectA ["class"] = 12;
or
objectA.class = 12;
88. How can you get the status of a checkbox?
The status variable returns true if the checkbox with id ‘elementCheck’ is checked or else false.
var status = document.getElementById('elementCheck').checked;
89. How to use the unshift() method on an array in JavaScript?
var name = ["alice", "mary"];
name.unshift("charlie");
console.log(name);
// outputs ["alice", "mary", "charlie"];
90. Write a code snippet to handle nulls in JavaScript.
A variable may contain a null value or even some whitespaces. This can affect validation and variable values. Therefore, it is a good practice to add a check for both null and whitespaces as shown below.
if((source_name != "") && (source_name != " ")){
console.log("a valid source name is entered");
// do something
}
Here are more details to handle nulls and white spaces.
91. How can you find the current timezone of your location in JavaScript?
The DataTimeFormat()
function as shown below helps retrieve a user’s current time zone.
const current_timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(current_timezone); // example Asia/Dubai
Find here complete details to retrieve the current timezone.
92. How to use arrow functions in JavaScript?
The function below func_name
, will accept arguments arg1..argN
, and then evaluate the expression on the right side using the arguments and returns a result.
const func_name = (arg1, arg2, ..., argN) => expression;
Find here complete details on how to use arrow functions.
93. How to use the array method push()
in JavaScript?
We can add new elements to an array using the push
or unshift
methods. The code snippet below shows how we can use the push method.
const subjects = ["English", "Maths"]
subjects.push("Science");
console.log(subjects);
// prints ["English", "Maths", "Science"] now
94. How does the fill method works in JavaScript?
The fill method passes (fills) to all elements in an array with a static value and returns the new modified array. For example, when creating a new array, you may fill all positions with the same value as shown below.
const arr = new Array(5)
console.log(arr);
// prints ['', '', '', '', ''] initially
arr.fill(8);
console.log(arr);
// prints ['8', '8', '8', '8', '8'] now
95. How can we use the join() method in JavaScript?
The join
method concatenates all array methods to make a new string. For example, consider the code snippet below.
const arr = ["c", "a", "d", "s", "l", "i", "s", "t"]
arr.join('');
console.log(arr)
// prints cadslist
96. How can we check if a specific string includes a specific character in JavaScript?
The method checks if an array includes an element that has a specific value passed in the include function, and returns Boolean results. For example, consider the code sample given below.
const arr = ["c", "a", "d", "s", "l", "i", "s", "t"]
arr.includes(c); // returns true
arr.includes(r); // returns false
97. How can we apply specific criteria to array elements?
We can use the map function for this, as shown below.
const arr = ["10", "90", "18", "7", "6", "3"];
const mapped_arr = arr.map(element => element - 10);
console.log(mapped_arr);
// prints [0, 80, 8, -3, -4, -7]
98. How can we search for specific elements in an array?
The filter method searches specific results from an array and creates a new array with the filtered results.
const arr = ["10", "90", "18", "7", "6", "3"];
const filtered_arr = arr.filter(element => element < 10 || element === 90);
console.log(filtered_arr);
// prints [7, 6, 3, 90]
99. How to use memoization in JavaScript?
Memoization is a caching technique that will return the value of a function based on its parameters.
function addTo500(num){
return num + 256;
}
addTo500(20); // Returns 520
addTo500(40); // Returns 540
addTo500(20); // Returns 520
100. What will be the output of the following code snippet?
var x = 23;
(function(){
var x = 43;
(function random(){
x++;
console.log(x);
var x = 21;
})();
})();
The output of this function is NaN.
The random() function has a functional scope of x. You can declare and hoist it in the functional scope.
Find Interview Questions for Laravel here.