JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms.
In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview questions on every difficulty level This was sufficient to ace any online assessment test or interview questions.
JavaScript Interview Questions for Freshers
Let’s discuss some common questions that you should prepare for the interviews. These questions will help clear the interviews, especially for the frontend development role.
1. How to concatenate two strings in JavaScript?
we can concatenate two strings using the "+" operator as code below:
JavaScript
let str1 = "Hello";
let str2 = "World";
let result = str1 + str2;
console.log(result);
2. What would be the result of 3+2+"7"?
JavaScript
let result = 3 + 2 + "7";
console.log(result);
Output:
57
3 + 2
is evaluated first, and since both are numbers, it results in 5
.- Then,
5 + "7"
is calculated. Since one of the operands is a string ("7"
), JavaScript converts the number 5
to a string and concatenates it with "7"
, resulting in "57"
.
3. Are JavaScript and Java related?
No, there names sounds similar but they are not related in any terms, below are some key differences:
Java | JavaScript |
---|
Java is a strongly typed language and variables must be declared first to use in the program. In Java, the type of a variable is checked at compile-time. | JavaScript is a loosely typed language and has a more relaxed syntax and rules. |
Java is an object-oriented programming language primarily used for developing complex enterprise applications. | JavaScript is a scripting language used for creating interactive and dynamic web pages. |
Java applications can run in any virtual machine(JVM) or browser. | JavaScript code used to run only in the browser, but now it can run on the server via Node.js. |
Objects of Java are class-based even we can't make any program in java without creating a class. | JavaScript Objects are prototype-based. |
To learn more you can refer to difference between Java and JavaScript.
4. What is the difference between JavaScript and TypeScript?
JavaScript is a Dynamically Typed language which means the developers do not have to provide data types of variables. Dynamically typed languages have advantages like easy to learn, flexible and faster development. However, there are disadvantages also like slowness and runtime errors. TypeScript is a superset of JavaScript that primarily uses static typing and has support for dynamic typing. TypeScript is developed and maintained by Microsoft, it compiles down to plain JavaScript, making it compatible with all JavaScript environments, including web browsers and Node.js.
5. What is a Variable Scope in JavaScript?
In JavaScript, we have each variable are accessed and modified through either one of the given scope:
- Global Scope: Outermost level (accessible everywhere).
- Local Scope: Inner functions can access variables from their parent functions due to lexical scoping.
- Function Scope: Variables are confined to the function they are declared in.
- Block Scope: Variables declared with
let
or const
are confined to the nearest block (loops, conditionals, etc.).
6. What the difference between Lexical and Dynamic Scoping?
Lexical Scoping (Static Scoping)
- Definition: The scope of a variable is determined by its position in the source code at the time of writing.
- JavaScript uses lexical scoping.
- The inner function looks up variables in the outer function where it was defined, not where it was called.
Dynamic Scoping (Not in JS)
- Definition: The scope is determined by the call stack at runtime, not where the function is written.
- Languages like older versions of Lisp or Bash use dynamic scoping.
- The function uses variables from the function that called it, even if it was defined else.
7. What is the use of the isNaN function?
The number isNan function determines whether the passed value is NaN (Not a number) and is of the type "Number". In JavaScript, the value NaN is considered a type of number. It returns true if the argument is not a number, else it returns false.
8. What does this code log?
JavaScript
const arr = [1, 2, 3];
arr[10] = 99;
console.log(arr.length);
Output:
11
Explanation: When you assign to arr[10]
you create empty slots from index 3 to 9, making the new length
one more than the highest index: 10 + 1 = 11
.
9. What is negative infinity?
The negative infinity is a constant value represents the lowest available value. It means that no other number is lesser than this value. It can be generate using a self-made function or by an arithmetic operation. JavaScript shows the NEGATIVE_INFINITY value as -Infinity.
10. Is it possible to break JavaScript Code into several lines?
Yes, it is possible to break the JavaScript code into several lines in a string statement. It can be broken by using the '\n' (backslash n).
Example:
console.log("A Online Computer Science Portal\n for Geeks")
The code-breaking line is avoid by JavaScript which is not preferable.
JavaScript
let gfg= 10, GFG = 5,
Geeks =
gfg + GFG;
console.log(Geeks)
11. What are "truthy" and "falsy" values in JavaScript
- Falsy: false, 0, "" (empty string), null, undefined, NaN.
- Truthy: Everything else (e.g., any non-empty string, any non-zero number, objects, arrays).
12. What are undeclared and undefined variables?
- Undefined: It occurs when a variable is declare but not assign any value. Undefined is not a keyword.
- Undeclared: It occurs when we try to access any variable which is not initialize or declare earlier using the var or const keyword. If we use 'typeof' operator to get the value of an undeclare variable, we will face the runtime error with the return value as "undefined". The scope of the undeclare variables is always global.
13. What will be the result of this expression?
JavaScript
console.log(null ?? 'default');
console.log(undefined ?? 'default');
console.log(false ?? 'default');
Output:
default
default
false
Explanation:
The nullish coalescing operator ??
returns the right-hand side only if the left is null
or undefined
. So:
null ?? 'default'
→ 'default'
undefined ?? 'default'
→ 'default'
false ?? 'default'
→ false
(because false
is neither null
nor undefined
)
14. Write a JavaScript code for adding new elements dynamically.
html
<html>
<head>
</head>
<body>
<button onclick="create()">
Click Here!
</button>
<script>
function create() {
let geeks = document.createElement('geeks');
geeks.textContent = "Geeksforgeeks";
geeks.setAttribute('class', 'note');
document.body.appendChild(geeks);
}
</script>
</body>
</html>
15. What are global variables? How are these variables declared, and what are the problems associated with them?
In contrast, global variables are the variables that define outside of functions. These variables have a global scope, so they can be used by any function without passing them to the function as parameters.
Example:
javascript
let petName = "Rocky"; // Global Variable
myFunction();
function myFunction() {
console.log("Inside myFunction - Type of petName:", typeof petName);
console.log("Inside myFunction - petName:", petName);
}
console.log("Outside myFunction - Type of petName:", typeof petName);
console.log("Outside myFunction - petName:", petName);
OutputInside myFunction - Type of petName: string
Inside myFunction - petName: Rocky
Outside myFunction - Type of petName: string
Outside myFunction - petName: Rocky
It is difficult to debug and test the code that relies on global variables.
16. What do you mean by Null in JavaScript?
The null value represents that no value or no object. It is known as empty value/object.
17. How to delete property-specific values?
The delete keyword deletes the whole property and all the values at once like
let gfg={Course: "DSA", Duration:30};
delete gfg.Course;
18. What will be the output of this code?
JavaScript
let x = 0;
console.log(x++);
console.log(++x);
Output:
0
2
Explanation:
x++
returns the current value (0), then increments → x
becomes 1.++x
increments first (1 → 2), then returns the new value (2).
19. What is the difference between null and undefined in JavaScript?
undefined:
- A primitive value automatically assigned to:
- Uninitialized variables
- Missing function arguments
- Missing object properties
- It means: "value not assigned yet"
let x;
console.log(x); // undefined
function foo(a) {
console.log(a); // undefined if no argument is passed
}
foo();
null:
- A primitive value that you assign intentionally to represent:
- "no value", "empty", or "non-existent"
- It means: "value is deliberately empty"
let user = null; // explicit assignment
console.log(user); // null
20. What is the output of this snippet?
JavaScript
const a = [1, 2, 3];
const b = [1, 2, 3];
console.log(a == b, a === b);
Output:
false
false
Explanation: Arrays are objects and compared by reference. a
and b
are distinct objects, so both loose (==
) and strict (===
) comparisons yield false
.
21. What is a prompt box?
The prompt box is a dialog box with an optional message prompting the user to input some text. It is often used if the user wants to input a value before entering a page. It returns a string containing the text entered by the user, or null.
22. What is the 'this' keyword in JavaScript?
Functions in JavaScript are essential objects. Like objects, it can be assign to variables, pass to other functions, and return from functions. And much like objects, they have their own properties. 'this' stores the current execution context of the JavaScript program. Thus, when it use inside a function, the value of 'this' will change depending on how the function is defined, how it is invoked, and the default execution context.
23. Explain the working of timers in JavaScript. Also explain the drawbacks of using the timer, if any.
The timer executes some specific code at a specific time or any small amount of code in repetition to do that you need to use the functions setTimout, setInterval, and clearInterval. If the JavaScript code sets the timer to 2 minutes and when the times are up then the page displays an alert message "times up". The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
24. What will be logged by this code?
JavaScript
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), i * 100);
}
Output:
0 1 2
Explanation: Using let i
in the loop gives each callback its own i
binding. The timeouts fire after 0ms, 100ms, and 200ms, logging 0
, then 1
, then 2
.
25. What is the difference between ViewState and SessionState?
- ViewState: It is specific to a single page in a session.
- SessionState: It is user specific that can access all the data on the web pages.
You can use document.form[0].submit()method to submit the form in JavaScript.
27. Does JavaScript support automatic type conversion?
Yes, JavaScript supports automatic type conversion.
28. What is a template literal in JavaScript?
A template literal in JavaScript is a way to define strings that allow embedded expressions and multi-line formatting. It uses backticks (`
) instead of quotes and supports ${}
for embedding variables or expressions inside the string.
29. What is a higher-order function in JavaScript?
A higher-order function in JavaScript is a function that either takes one or more functions as arguments, or returns a function as its result. These functions allow for more abstract and reusable code, enabling functional programming patterns
For example, map() and filter() are higher-order functions because they take callback functions as arguments.
30. What are all the looping structures in JavaScript?
- while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
- for loop: A for loop provides a concise way of writing the loop structure. Unlike a while loop, for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
- do while: A do-while loop is similar to while loop with the only difference that it checks the condition after executing the statements, and therefore is an example of Exit Control Loop.
31. What is lexical scope in JavaScript?
Lexical scope in JavaScript refers to the way variables are resolved based on their location in the source code. A variable's scope is determined by the position of the code where it is defined, and it is accessible to any nested functions or blocks. This means that functions have access to variables in their own scope and the outer (lexical) scopes, but not to variables in inner scopes.
JavaScript
let outer = "I am outside!";
function inner() {
console.log(outer);
}
inner();
In this example, inner() can access the outer variable because of lexical scoping.
32. How does lexical scoping work with the this
keyword in JavaScript?
In JavaScript, lexical scoping primarily applies to variable resolution, while the behavior of the this keyword is determined by how a function is called, not by its position in the code. The value of this is dynamically determined at runtime based on the function’s context (e.g., whether it’s called as a method, in a global context, or with call, apply, or bind).
JavaScript
const obj = {
name: "JavaScript",
greet: function () {
console.log(this.name);
}
};
obj.greet(); // "JavaScript"
Here, this refers to obj because the function is called as a method of the object. Lexical scoping affects variable lookups but doesn’t alter how this behaves.
33. Explain how to read and write a file using JavaScript?
The readFile() functions is used for reading operation.
readFile( Path, Options, Callback)
The writeFile() functions is used for writing operation.
writeFile( Path, Data, Callback)
34. What is called Variable typing in JavaScript?
The variable typing is the type of variable used to store a number and using that same variable to assign a “string”.
Geeks = 42;
Geeks = "GeeksforGeeks";
35. What is hoisting in JavaScript?
Hoisting in JavaScript is the behavior where variable and function declarations are moved to the top of their containing scope during compilation, before the code is executed.
This means you can reference variables and functions before they are declared in the code. However, only declarations are hoisted, not initializations.
JavaScript
console.log(a); // undefined
var a = 5;
In this case, the declaration of a is hoisted, but its value (5) is not assigned until the code execution reaches that line. Hoisting applies differently for var, let, const, and function declarations.
36. How to convert the string of any base to integer in JavaScript?
In JavaScript, parseInt() function is used to convert the string to an integer. This function returns an integer of base which is specified in second argument of parseInt() function. The parseInt() function returns Nan (not a number) when the string doesn’t contain number.
37. Explain how to detect the operating system on the client machine?
To detect the operating system on the client machine, one can simply use navigator.appVersion or navigator.userAgent property. The Navigator appVersion property is a read-only property and it returns the string that represents the version information of the browser.
38. What are the types of Pop up boxes available in JavaScript?
There are three types of pop boxes available in JavaScript.
39. What is the use of void(0) ?
The void(0) is used to call another method without refreshing the page during the calling time parameter “zero” will be passed.
40. What are JavaScript modules, and how do you import/export them?
JavaScript modules allow you to split your code into smaller, reusable pieces. They enable the export of variables, functions, or objects from one file and the import of them into another. To export an element, you use export (either named or default). To import it, you use import.
JavaScript
// In file1.js
export const greet = () => "Hello";
// In file2.js
import { greet } from './file1';
console.log(greet());
Modules help organize code and avoid global namespace pollution. They are natively supported in modern JavaScript through import and export statements.
41. What are WeakMap and WeakSet, and how are they different from Map and Set?
A WeakMap is a collection of key-value pairs where keys are objects and the values can be any data type. The key-value pairs in a WeakMap are "weakly" held, meaning if no other references to a key exist, the entry can be garbage collected. A WeakSet is a collection of unique objects, and like WeakMap, the objects are weakly held.
The main difference from Map and Set is that in Map and Set, entries are strongly held, meaning they prevent garbage collection, while in WeakMap and WeakSet, entries can be garbage collected if no other references to the objects exist.
In Node.js, the setImmediate()
function schedules a callback to be executed in the next iteration of the event loop, specifically after the current event loop phase (which includes I/O events). It's commonly used for deferring tasks to be executed once the current operation completes.
The key difference between setImmediate()
and setTimeout()
is that setImmediate()
runs after the current event loop iteration, following I/O events but before any timers (such as setTimeout()
). On the other hand, setTimeout()
schedules tasks to run after a specified delay, which might not be precise if the event loop is busy, meaning it can be delayed by I/O or other tasks. While setTimeout()
schedules tasks with a minimum delay, setImmediate()
executes as soon as the event loop reaches a free point in the "check" phase, after I/O events have been processed.
JavaScript Interview Questions for Experienced
43. What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict Mode is a new feature in ECMAScript 5 that allows you to place a program or a function in a “strict” operating context. This strict context prevents certain actions from being taken and throws more exceptions. The statement “use strict” instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript.
44. What are the advantages and disadvantages of using async/await
over traditional callbacks or promises?
Advantages of async/await:
- Improved Readability : Async/await makes asynchronous code look like synchronous code, making it easier to read and maintain.
- Simplified Error Handling : With try/catch, error handling is more straightforward compared to .catch() with promises or callback-based error handling.
- Avoids callback hell : It eliminates deeply nested callbacks, reducing complexity in asynchronous logic.
Disadvantages of async/await:
- Requires modern JavaScript : It’s supported in ES2017 and above, so older environments may need transpiling.
- Limited concurrency control : Unlike promises with .all() or .race(), async/await can be less flexible for handling multiple parallel tasks.
45. How to explain closures in JavaScript and when to use it?
The closure is created when a child functions to keep the environment of the parent’s scope even after the parent’s function has already executed. The Closure is a locally declared variable related to a function. The closure will provide better control over the code when using them.
JavaScript
function foo() {
let b = 1;
function inner() {
return b;
}
return inner;
}
let get_func_inner = foo();
console.log(get_func_inner());
console.log(get_func_inner());
console.log(get_func_inner());
46. What is the difference between call() and apply() methods ?
Both methods are used in a different situation
- call() Method: It calls the method, taking the owner object as argument. The keyword this refers to the ‘owner’ of the function or the object it belongs to. We can call a method that can be used on different objects.
- apply() Method: The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array.
47. How to target a particular frame from a hyperlink in JavaScript ?
This can be done by using the target attribute in the hyperlink. Like
<a href="/https/www.geeksforgeeks.org/geeksforgeeks.htm" target="newframe">New Page</a>
48. Write the errors shown in JavaScript?
There are three different types of errors in JavaScript.
- Syntax error : A syntax error is an error in the syntax of a sequence of characters or tokens that are intended to be written in a particular programming language.
- Logical error: It is the most difficult error to be traced as it is the error on the logical part of the coding or logical error is a bug in a program that causes to operate incorrectly and terminate abnormally.
- Runtime Error : A runtime error is an error that occurs during the running of the program, also known as an exception.
49. What is the difference between JavaScript and Jscript?
JavaScript
- It is a scripting language developed by Netscape.
- It is used to design client and server-side applications.
- It is completely independent of Java language.
JScript
- It is a scripting language developed by Microsoft.
- It is used to design active online content for the word wide Web.
50. How many ways an HTML element can be accessed in JavaScript code?
There are four possible ways to access HTML elements in JavaScript which are:
51. What is an event bubbling in JavaScript?
Consider a situation an element is present inside another element and both of them handle an event. When an event occurs in bubbling, the innermost element handles the event first, then the outer, and so on.
52. Explain the concept of memoization in JavaScript?
Memoization in JavaScript is an optimization technique that stores the results of expensive function calls and reuses them when the same inputs occur again. This reduces the number of computations by caching the results. Memoization is typically implemented using an object or a map to store function arguments and their corresponding results. When the function is called with the same arguments, the cached result is returned instead of recalculating it. This improves performance, especially for functions with repeated calls and expensive computations.
53. What is the difference between ==
and ===
in JavaScript?
In JavaScript, ==
is the loose equality operator, which compares two values for equality after performing type coercion if necessary. This means it converts the operands to the same type before comparing.
===
is the strict equality operator, which compares both the values and their types, without performing type conversion.
54. Explain the concept of promises and how they work.
A Promise in JavaScript is an object that represents the result of an asynchronous operation. It can be in one of three states: pending, fulfilled (resolved), or rejected. You create a promise using new Promise(), passing an executor function with resolve and reject callbacks. When the operation succeeds, resolve() is called; if it fails, reject() is used. Promises are handled with .then() for success and .catch() for failure. They can be chained to handle sequences of asynchronous tasks in a more readable way.
55. What is the difference between a shallow copy and a deep copy?
A shallow copy creates a new object but copies references to the original nested objects, meaning changes to the nested objects affect both the original and the copy. A deep copy, on the other hand, creates a new object and recursively copies all nested objects, ensuring that the original and the copy are completely independent. In a shallow copy, nested objects are shared, while in a deep copy, they are fully duplicated.
56. Explain the concept of the event loop and the call stack in JavaScript. How does JavaScript handle asynchronous code execution?
In JavaScript, the event loop manages the execution of code, handling both synchronous and asynchronous operations. The call stack stores function calls and executes them in a Last In, First Out (LIFO) order. When asynchronous code (e.g., setTimeout, promises) is encountered, it’s offloaded to the callback queue once its execution context is ready. The event loop continuously checks the call stack and moves tasks from the callback queue to the stack when it’s empty, allowing asynchronous code to run without blocking the main thread.
57. What are Web Workers, and how do you use them to run scripts in the background?
Web Workers are JavaScript threads that run in the background, separate from the main thread, allowing long-running scripts to be executed without blocking the user interface. You can create a Web Worker using the Worker
constructor, passing a JavaScript file as an argument. Once created, the worker can perform tasks asynchronously, and you can communicate with it via postMessage and onmessage events, ensuring the main thread remains responsive.
Debouncing and throttlingare techniques used to optimize performance by limiting the frequency of function executions in response to events like scrolling or resizing.
- Debouncing ensures that a function is only executed after a certain amount of idle time, i.e., it delays the execution until the event stops triggering for a specified time (e.g., for search input).
- Throttling limits the number of times a function can be executed in a given period, ensuring it runs at regular intervals (e.g., during scroll or window resizing).
JavaScript MCQ Coding Interview Questions
59. Which of the following is a JavaScript data type?
Options:
- number
- string
- boolean
- All of the above
Answer:
4
Explanation:
- JavaScript has several built-in data types, and number, string, and boolean are all valid types.
- A number represents numeric values, a string represents sequences of characters, and a boolean represents either true or false. All of these are fundamental data types in JavaScript.
60. What is the result of the following code?
JavaScript
let a = [1, 2, 3];
let b = a;
b[0] = 100;
console.log(a);
Options:
- [100, 2, 3]
- [1, 2, 3]
- [100, 100, 100]
- undefined
Answer :
1
Explanation :
- The code snippet represents two arrays [100, 2, 3] and [1, 2, 3] being compared using the equality operator (==).
- In JavaScript, arrays are reference types, meaning each array is a reference to an object in memory.
61. What is the output of the following code?
JavaScript
Options:
null
- undefined
- ''
- []
Answer :
3
Explanation:
- The
+
operator concatenates two empty arrays, which results in an empty string ''
.
62. What will be the output of the following code?
JavaScript
(function() {
var a = b = 5;
})();
console.log(typeof a);
console.log(typeof b);
Options:
typeof a: "undefined"
typeof b: "number"
- typeof a: "number"
typeof b: "number" - typeof a: "undefined"
typeof b: "undefined" - typeof a: "number"
typeof b: "undefined"
Answer:
1
Explanation:
- Inside the IIFE,
b = 5
is treated as a global variable (since no var
, let
, or const
keyword is used). - However,
a
is declared with var
and is local to the function, so it is undefined
outside.
63. What will be logged in the console?
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
Options:
true, true
true, false
false, true
false, false
Answer:
2
Explanation:
1 < 2 < 3 is evaluated as (1 < 2) < 3, which becomes true < 3. In JavaScript, true is treated as 1, so 1 < 3 is true.
- 3 > 2 > 1 becomes (3 > 2) > 1, which results in true > 1. Since true is 1, the comparison becomes 1 > 1, which is false.
64. What will be the output of the following code?
const obj1 = { a: 1 };
const obj2 = { a: 1 };
console.log(obj1 == obj2);
console.log(obj1 === obj2);
Options:
true, true
true, false
false, true
false, false
Answer:
4
Explanation:
- In JavaScript, objects are compared by reference, not by value. Since obj1 and obj2 point to different memory locations, both == and === comparisons return false.
65. What will be the result of the following code?
let x = 10;
let y = (x++, x + 1, x * 2);
console.log(y);
Options :
22
12
21
20
Answer:
22
Explanation:
- The comma operator ( , ) evaluates all expressions but returns the value of the last one.
- x++ increments x to 11, but the result of this expression is the original 10.
- x + 1 becomes 11 + 1 = 12, and the final expression x * 2 evaluates to 11 * 2 = 22, which is assigned to y.
66. What will be the output of this asynchronous JavaScript code?
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
Options:
A D B C
A B C D
A D C B
A C D B
Answer:
3
Explanation:
- The synchronous code runs first, logging 'A' and 'D'.
- Promise callbacks (microtasks) are executed before setTimeout (macrotasks). So 'C' is logged before 'B'.
67. What will be the output of this recursive function?
function foo(num) {
if (num === 0) return 1;
return num + foo(num - 1);
}
console.log(foo(3));
Options:
3
6
7
10
Answer:
3
Explanation:
- The function works recursively:
- foo(3) → 3 + foo(2)
- foo(2) → 2 + foo(1)
- foo(1) → 1 + foo(0)
- foo(0) → 1
- So, the total is 3 + 2 + 1 + 1 = 7.
68. What will be printed in the following code?
let a = [1, 2, 3];
let b = a;
b.push(4);
console.log(a);
console.log(b);
Options:
[1, 2, 3]
[1, 2, 3, 4]
- [1, 2, 3, 4]
[1, 2, 3, 4] - [1, 2, 3]
[1, 2, 3] - [1, 2, 3, 4]
[1, 2, 3]
Answer:
2
Explanation:
- In JavaScript, arrays are reference types. Both a and b point to the same array in memory. Modifying b also affects a.
69. What will be logged by the following code?
function test() {
console.log(this);
}
test.call(null);
Options:
null
- undefined
- Window or global object
- TypeError
Answer:
3
Explanation:
- In non-strict mode, calling a function with this set to null defaults to the global object (Window in browsers or global in Node.js).
JavaScript Interview Questions and AnswersJavaScript Tricky Coding Interview Questions
In Interviews sometimes interviewer ask some tricky output based JS questions to test your grasp on concepts. Let's see some of tricky questions that may ask in your upcoming interview.
Note: we recommend you should guess first then confirm your output by hit on run.
70.
JavaScript
let a = 5;
let b = '5';
if (a == b) {
console.log('Equal');
} else {
console.log('Not Equal');
}
Explanation: The ==
operator performs type coercion, converting both operands to the same type before comparison. Here, '5'
is coerced to a number, making the comparison 5 == 5
, which evaluates to true
. To avoid such issues, it's recommended to use the strict equality operator ===
, which checks both value and type without coercion.
71.
JavaScript
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, 100);
}
Explanation: Due to JavaScript's function scoping with var
, the variable i
is shared across all iterations. By the time the setTimeout
callbacks execute, the loop has completed, and i
equals 3
. To capture the value of i
at each iteration, you can use let
(which has block scope) or pass i
as an argument to an immediately invoked function expression (IIFE).
72.
JavaScript
function arrayFromValue(item) {
return
[item];
}
console.log(arrayFromValue(10)); // ???
Explanation: JavaScript's automatic semicolon insertion adds a semicolon after the return
statement, causing the function to return undefined
instead of the intended array. To fix this, ensure the return statement is on the same line as the array:
73.
JavaScript
const car = {
name: 'Toyota',
getName: function() {
return this.name;
},
};
const getCarName = car.getName;
console.log(getCarName()); // ???
Explanation: When getCarName
is called, it's no longer in the context of the car
object. Therefore, this
refers to the global object (or undefined
in strict mode), not the car
object. To maintain the correct context, you can use .bind(car)
:
const getCarName = car.getName.bind(car);
console.log(getCarName()); // 'Toyota'
74.
JavaScript
console.log(a); // ???
console.log(b); // ???
var a = 2;
let b = 2;
Explanation: Variables declared with var
are hoisted and initialized with undefined
, so console.log(a)
outputs undefined
. Variables declared with let
are hoisted but not initialized, leading to a ReferenceError
when accessed before their declaration.
75.
JavaScript
console.log(typeof null); // ???
Explanation: This is a well-known quirk in JavaScript. Despite null
being a primitive value representing the intentional absence of any object value, the typeof
operator returns "object"
. This behavior is considered a bug in JavaScript that has been maintained for backward compatibility.
76.
JavaScript
let arr = new Array(3).fill([]);
arr[0].push(10);
console.log(arr); // ???
Explanation: The fill
method fills all elements of the array with the same reference to the same array. Therefore, when you modify one element (e.g., arr[0].push(10)
), all elements reflect this change because they all point to the same array in memory.
77.
JavaScript
const obj = { x: 1 };
const { x, x: y } = obj;
console.log(y); // ???
Explanation: In this destructuring assignment, x
is first assigned the value 1
from the object. Then, x: y
creates a new variable y
and assigns it the value of x
. Since x
is 1
, y
also becomes 1
. This demonstrates how destructuring can assign values to multiple variables from the same property.
78.
JavaScript
console.log(typeof undeclaredVar); // ???
console.log(typeof y); // ???
let y = 1;
Explanation: The first console.log
outputs "undefined"
because undeclaredVar
is not declared at all. The second console.log
throws a ReferenceError
because y
is declared with let
and is in a "temporal dead zone" from the start of the block until the declaration is encountered. During this period, accessing y
results in a ReferenceError
.
Common JavaScript Interview Questions
1. What are the different data types in JavaScript?
JavaScript has two types of data: primitive and non-primitive.
- Primitive data types:
string
, number
, boolean
, undefined
, null
, symbol
, bigint
- Non-Primitive data types:
objects,
arrays and functions.
2. What is the difference between ==
and ===
in JavaScript?
==
(loose equality): They compares only the values, allowing type coercion (i.e., converts types if necessary).- ==
=
(strict equality): They compares both value and type, without type conversion.
3. What is the difference between let
, const
, and var
?
var
: Function-scoped, can be re-assigned and redeclared within its scope.let
: Block-scoped, can be reassigned but not redeclared within the same scope.const
: Block-scoped, cannot be reassigned or redeclared, and the value assigned to it remains constant.
4. Explain hoisting in JavaScript.
Hoisting is JavaScript's default behavior of moving all variable and function declarations to the top of their containing scope during the compile phase. However, only the declarations are hoisted, not the initialization.
5. What is the difference between null
and undefined
in JavaScript?
null
: Represents an intentional absence of any object value. It is explicitly assigned to indicate "no value."undefined
: Indicates that a variable has been declared but has not yet been assigned a value.
let a = null; // Explicitly assigned nulllet b; // Variable declared but not assigned, hence undefined
6. What are promises in JavaScript and how do they work?
A promise is an object representing the eventual completion or failure of an asynchronous operation. Promises are used to handle asynchronous operations like API calls, ensuring cleaner code compared to callbacks. It has three states:
pending
: The initial state.fulfilled
: The operation completed successfully.rejected
: The operation failed.
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation was successful");
}
else {
reject("Operation failed");
}});
myPromise.then(result => console.log(result)).catch(error => console.log(error));
7. What is the event loop in JavaScript?
The event loop is a mechanism that allows JavaScript to handle asynchronous operations (like I/O, timers, etc.) without blocking the main thread. It continuously checks the call stack for any code to execute and moves tasks from the callback queue to the call stack when the stack is empty.
8. What are closures in JavaScript?
A closure is a function that retains access to its lexical scope (the scope in which it was created) even after that scope has finished execution. Closures allow functions to access variables from an outer function after the outer function has returned.
JavaScript
function outer() {
let x = 10;
return function inner() {
console.log(x);
}
}
const closureFunc = outer();
closureFunc(); // prints 10
9. Explain the concept of this
in JavaScript.
In JavaScript, the this
keyword refers to the context in which a function is called. It is used to refer to the object that is executing the current piece of code.
The value of this
can change depending on how the function is called. Here are the different scenarios where this
behaves differently:
- Global context: In non-strict mode,
this
refers to the global object (window
in browsers). - Object method:
this
refers to the object the method belongs to. - Constructor function:
this
refers to the instance of the object being created. - Arrow functions: In arrow functions,
this
is lexically bound to the surrounding context.
10. What is a callback function in JavaScript?
A callback function in JavaScript is a function that is passed as an argument to another function and is executed after the completion of that function. Callback functions are primarily used for handling asynchronous operations, such as API requests or timeouts, ensuring that certain code runs only after a specific task is completed.
JavaScript
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayGoodbye() {
console.log("Goodbye!");
}
greet("Anjali", sayGoodbye);
OutputHello Anjali
Goodbye!
Practice JavaScript with Quizzes
Apart from these questions you can also practice JavaScript Quiz for better understanding of every topic to enhance your knowledge and helping you in the interviews.
- Basic JavaScript
- Variables and Data Types
- Operators
- Control Flow
- Functions
- Objects
- Arrays
- DOM and BOM
- Event Handling
- Classes and Inheritance
- Modern JavaScript (ES6+)
- Advanced JavaScript
- Regular Expressions and JSON
- Asynchronous JavaScript
- Error Handling and Debugging
Conclusion
In conclusion, after going through this article, you should now have a solid understanding of the key JavaScript interview questions that are commonly asked in web development interviews. Remember, JavaScript often includes a few tricky questions, so be sure not to skip that part of your preparation. Whether you're preparing for a front-end or back-end role, it’s always helpful to check out our specialized interview question guides(1. Frontend Interview Questions 2. Backend Interview Questions 3. Full-Stack Interview Questions) for both areas. Stay well-prepared and confident, and you'll be ready to tackle your interview with ease!
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
JavaScript Basics
Introduction to JavaScriptJavaScript is a versatile, dynamically typed programming language that brings life to web pages by making them interactive. It is used for building interactive web applications, supports both client-side and server-side development, and integrates seamlessly with HTML, CSS, and a rich standard libra
4 min read
JavaScript VersionsJavaScript is a popular programming language used by developers all over the world. Itâs a lightweight and easy-to-learn language that can run on both the client-side (in your browser) and the server-side (on the server). JavaScript was created in 1995 by Brendan Eich.In 1997, JavaScript became a st
2 min read
How to Add JavaScript in HTML Document?To add JavaScript in HTML document, several methods can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file.Inline JavaScriptYou can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or other ev
3 min read
JavaScript SyntaxJavaScript syntax refers to the rules and conventions dictating how code is structured and arranged within the JavaScript programming language. This includes statements, expressions, variables, functions, operators, and control flow constructs.Syntaxconsole.log("Basic Print method in JavaScript");Ja
6 min read
JavaScript OutputJavaScript provides different methods to display output, such as console.log(), alert(), document.write(), and manipulating HTML elements directly. Each method has its specific use cases, whether for debugging, user notifications, or dynamically updating web content. Here we will explore various Jav
4 min read
JavaScript CommentsComments help explain code (they are not executed and hence do not have any logic implementation). We can also use them to temporarily disable parts of your code.1. Single Line CommentsA single-line comment in JavaScript is denoted by two forward slashes (//), JavaScript// A single line comment cons
2 min read
JS Variables & Datatypes
Variables and Datatypes in JavaScriptVariables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, getting a good grasp of these concepts is important for writing code that works well and is easy to understand.Data TypesVariabl
6 min read
Global and Local variables in JavaScriptIn JavaScript, understanding the difference between global and local variables is important for writing clean, maintainable, and error-free code. Variables can be declared with different scopes, affecting where and how they can be accessed. Global VariablesGlobal variables in JavaScript are those de
4 min read
JavaScript LetThe let keyword is a modern way to declare variables in JavaScript and was introduced in ECMAScript 6 (ES6). Unlike var, let provides block-level scoping. This behaviour helps developers avoid unintended issues caused by variable hoisting and scope leakage that are common with var.Syntaxlet variable
6 min read
JavaScript constThe const keyword in JavaScript is a modern way to declare variables, introduced in (ES6). It is used to declare variables whose values need to remain constant throughout the lifetime of the application.const is block-scoped, similar to let, and is useful for ensuring immutability in your code. Unli
5 min read
JavaScript Var StatementThe var keyword is used to declare variables in JavaScript. It has been part of the language since its inception. When a variable is declared using var, it is function-scoped or globally-scoped, depending on where it is declared.Syntaxvar variable = value;It declares a variable using var, assigns it
7 min read
JS Operators
JavaScript OperatorsJavaScript operators are symbols or keywords used to perform operations on values and variables. They are the building blocks of JavaScript expressions and can manipulate data in various ways.There are various operators supported by JavaScript:1. JavaScript Arithmetic OperatorsArithmetic Operators p
5 min read
Operator precedence in JavaScriptOperator precedence refers to the priority given to operators while parsing a statement that has more than one operator performing operations in it. Operators with higher priorities are resolved first. But as one goes down the list, the priority decreases and hence their resolution. ( * ) and ( / )
2 min read
JavaScript Arithmetic OperatorsJavaScript Arithmetic Operators are the operator that operate upon the numerical values and return a numerical value. Addition (+) OperatorThe addition operator takes two numerical operands and gives their numerical sum. It also concatenates two strings or numbers.JavaScript// Number + Number =>
5 min read
JavaScript Assignment OperatorsAssignment operators are used to assign values to variables in JavaScript.JavaScript// Lets take some variables x = 10 y = 20 x = y ; console.log(x); console.log(y); Output20 20 More Assignment OperatorsThere are so many assignment operators as shown in the table with the description.OPERATOR NAMESH
5 min read
JavaScript Comparison OperatorsJavaScript comparison operators are essential tools for checking conditions and making decisions in your code. 1. Equality Operator (==) The Equality operator is used to compare the equality of two operands. JavaScript// Illustration of (==) operator let x = 5; let y = '5'; // Checking of operands c
5 min read
JavaScript Logical OperatorsLogical operators in JavaScript are used to perform logical operations on values and return either true or false. These operators are commonly used in decision-making statements like if or while loops to control the flow of execution based on conditions.In JavaScript, there are basically three types
5 min read
JavaScript Bitwise OperatorsIn JavaScript, a number is stored as a 64-bit floating-point number but bitwise operations are performed on a 32-bit binary number. To perform a bit-operation, JavaScript converts the number into a 32-bit binary number (signed) and performs the operation and converts back the result to a 64-bit numb
5 min read
JavaScript Ternary OperatorThe Ternary Operator in JavaScript is a conditional operator that evaluates a condition and returns one of two values based on whether the condition is true or false. It simplifies decision-making in code, making it more concise and readable. Syntaxcondition ? trueExpression : falseExpressionConditi
4 min read
JavaScript Comma OperatorJavaScript Comma Operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. JavaScriptlet x = (1, 2, 3); console.log(x); Output3 Here is another example to show that all expressions are actually executed.JavaScriptlet a = 1, b = 2, c = 3; l
2 min read
JavaScript Unary OperatorsJavaScript Unary Operators work on a single operand and perform various operations, like incrementing/decrementing, evaluating data type, negation of a value, etc.Unary Plus (+) OperatorThe unary plus (+) converts an operand into a number, if possible. It is commonly used to ensure numerical operati
4 min read
JavaScript in and instanceof operatorsJavaScript Relational Operators are used to compare their operands and determine the relationship between them. They return a Boolean value (true or false) based on the comparison result.JavaScript in OperatorThe in-operator in JavaScript checks if a specified property exists in an object or if an e
3 min read
JavaScript String OperatorsJavaScript String Operators are used to manipulate and perform operations on strings. There are two operators which are used to modify strings in JavaScript. These operators help us to join one string to another string.1. Concatenate OperatorConcatenate Operator in JavaScript combines strings using
3 min read
JS Statements
JS Loops
JavaScript LoopsLoops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as long as a specified condition is true. This makes code more concise and efficient.Suppose we want to print 'Hello World' five times. Instead of manually writing the print statement repeatedly, we can u
3 min read
JavaScript For LoopJavaScript for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. Syntaxfor (statement 1 ; statement 2 ; statement 3){ code here...}Statement 1: It is the initialization of
4 min read
JavaScript While LoopThe while loop executes a block of code as long as a specified condition is true. In JavaScript, this loop evaluates the condition before each iteration and continues running as long as the condition remains true.Syntaxwhile (condition) { Code block to be executed}Here's an example that prints from
3 min read
JavaScript For In LoopThe JavaScript for...in loop iterates over the properties of an object. It allows you to access each key or property name of an object.JavaScriptconst car = { make: "Toyota", model: "Corolla", year: 2020 }; for (let key in car) { console.log(`${key}: ${car[key]}`); }Outputmake: Toyota model: Corolla
3 min read
JavaScript for...of LoopThe JavaScript for...of loop is a modern, iteration statement introduced in ECMAScript 2015 (ES6). Works for iterable objects such as arrays, strings, maps, sets, and more. It is better choice for traversing items of iterables compared to traditional for and for in loops, especially when we have bre
3 min read
JavaScript do...while LoopA do...while loop in JavaScript is a control structure where the code executes repeatedly based on a given boolean condition. It's similar to a repeating if statement. One key difference is that a do...while loop guarantees that the code block will execute at least once, regardless of whether the co
4 min read
JS Perfomance & Debugging
JS Object
Objects in JavascriptAn object in JavaScript is a data structure used to store related data collections. It stores data as key-value pairs, where each key is a unique identifier for the associated value. Objects are dynamic, which means the properties can be added, modified, or deleted at runtime.There are two primary w
4 min read
Introduction to Object Oriented Programming in JavaScriptAs JavaScript is widely used in Web Development, in this article we will explore some of the Object Oriented mechanisms supported by JavaScript to get the most out of it. Some of the common interview questions in JavaScript on OOPS include: How is Object-Oriented Programming implemented in JavaScrip
7 min read
JavaScript ObjectsIn our previous article on Introduction to Object Oriented Programming in JavaScript we have seen all the common OOP terminology and got to know how they do or don't exist in JavaScript. In this article, objects are discussed in detail.Creating Objects:In JavaScript, Objects can be created using two
6 min read
Creating objects in JavaScriptAn object in JavaScript is a collection of key-value pairs, where keys are strings (properties) and values can be any data type. Objects can be created using object literals, constructors, or classes. Properties are defined with key-value pairs, and methods are functions defined within the object, e
5 min read
JavaScript JSON ObjectsJSON (JavaScript Object Notation) is a handy way to share data. It's easy for both people and computers to understand. In JavaScript, JSON helps organize data into simple objects. Let's explore how JSON works and why it's so useful for exchanging information.const jsonData = { "key1" : "value1", ...
3 min read
JavaScript Object ReferenceJavaScript Objects are the most important data type and form the building blocks for modern JavaScript. The "Object" class represents the JavaScript data types. Objects are quite different from JavaScriptâs primitive data types (Number, String, Boolean, null, undefined, and symbol). It is used to st
4 min read
JS Function
Functions in JavaScriptFunctions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9)); // output: 15Function Syntax
4 min read
How to write a function in JavaScript ?JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
4 min read
JavaScript Function CallThe call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). This allows borrowing methods from other objects, executing them within a different context, overriding the default value, and passing arguments. Syntax: cal
2 min read
Different ways of writing functions in JavaScriptA JavaScript function is a block of code designed to perform a specific task. Functions are only executed when they are called (or "invoked"). JavaScript provides different ways to define functions, each with its own syntax and use case.Below are the ways of writing functions in JavaScript:Table of
3 min read
Difference between Methods and Functions in JavaScriptGrasping the difference between methods and functions in JavaScript is essential for developers at all levels. While both are fundamental to writing effective code, they serve different purposes and are used in various contexts. This article breaks down the key distinctions between methods and funct
3 min read
Explain the Different Function States in JavaScriptIn JavaScript, we can create functions in many different ways according to the need for the specific operation. For example, sometimes we need asynchronous functions or synchronous functions. Â In this article, we will discuss the difference between the function Person( ) { }, let person = Person ( )
3 min read
JavaScript Function Complete ReferenceA JavaScript function is a set of statements that takes inputs, performs specific computations, and produces outputs. Essentially, a function performs tasks or computations and then returns the result to the user.Syntax:function functionName(Parameter1, Parameter2, ..) { // Function body}Example: Be
3 min read
JS Array
JavaScript ArraysIn JavaScript, an array is an ordered list of values. Each value is called an element, and each element has a numeric position in the array, known as its index. Arrays in JavaScript are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.Array in JavaScriptWhy Use
6 min read
JavaScript Array MethodsTo help you perform common tasks efficiently, JavaScript provides a wide variety of array methods. These methods allow you to add, remove, find, and transform array elements with ease.Javascript Arrays MethodsLearn More on JavaScript Array1. JavaScript Array length The length property of an array re
8 min read
Best-Known JavaScript Array MethodsAn array is a special variable in all programming languages used to store multiple elements. JavaScript array come with built-in methods that every developer should know how to use. These methods help in adding, removing, iterating, or manipulating data as per requirements.There are some Basic JavaS
6 min read
Important Array Methods of JavaScriptJavaScript arrays are powerful tools for managing collections of data. They come with a wide range of built-in methods that allow developers to manipulate, transform, and interact with array elements.Some of the most important array methods in JavaScript areTable of Content1. JavaScript push() Metho
7 min read
JavaScript Array ReferenceJavaScript Array is used to store multiple elements in a single variable. It can hold various data types, including numbers, strings, objects, and even other arrays. It is often used when we want to store a list of elements and access them by a single variable.Syntax:const arr = ["Item1", "Item2", "
4 min read