Open In App

Basic JavaScript Interview Questions and Answers

Last Updated : 12 Sep, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript (JS) is the language that adds logic and interactivity to the web. It turns static pages into apps—handling clicks, forms, data fetching, and real-time updates. Learning JS is essential for both frontend and backend work.

ygfds
  • Works Everywhere: Browsers, servers (Node.js), mobile, desktop.
  • Saves Time: Huge ecosystem of libraries and frameworks (React, Vue, Express).
  • Easy Updates: Change logic once and reuse it across components and pages.
  • Fast & Responsive: Async features (Promises, async/await) keep UIs smooth.

1. 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.

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. What’s new in ECMAScript 2025 (ES2025)?

ECMAScript 2025 (ES2025) Key Features

  • Promise.withResolvers() → Returns a promise with its resolve and reject, simplifying async control.
  • Immutable Array Methods → New methods like findLast(), toReversed(), and toSorted() return new arrays instead of mutating originals.
  • RegExp v flag → Adds better Unicode handling in regular expressions.
  • Hashbang grammar → Officially allows #! at the start of JS files for CLI scripts.

4. Is JavaScript compiled or interpreted?

JavaScript is mostly interpreted, but modern browsers also compile it just-in-time (JIT) to make it faster.

  • The browser reads your JavaScript code line by line and runs it directly.
  • Modern browsers (like Chrome’s V8 engine) first translate parts of your code into machine code while running it, so the computer can execute it much faster.

5. Are JavaScript and Java related?

No, there names sounds similar but they are not related in any terms, below are some key differences:

JavaJavaScript
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.

6. 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:

7. What’s the return-value difference between x++ and ++x?

Both increment, but return different values.

  • x++: post-increment → returns the old value, then increments.
  • ++x: pre-increment → increments first, then returns the new value.

8. What’s the difference between var, let, and const and what is the Temporal Dead Zone?

JavaScript provides three ways to declare variables: var, let, and const, but they differ in scope, hoisting behaviour, and re-assignment rules.

  • var: Declares variables with function or global scope and allows re-declaration and updates within the same scope.
  • let: Declares variables with block scope, allowing updates but not re-declaration within the same block.
  • const: Declares block-scoped variables that cannot be reassigned after their initial assignment.
JavaScript
// var: function or global scope, can be re-declared and updated
var x = 10;
var x = 20; // re-declaration allowed
console.log("var:", x); // 20

// let: block scope, can be updated but not re-declared in same block
let y = 30;
// let y = 40; Error (can't re-declare in same block)
y = 40; // update allowed
console.log("let:", y); // 40

// const: block scope, cannot be reassigned
const z = 50;
// z = 60; Error (can't reassign)
console.log("const:", z); // 50

Temporal Dead Zone (TDZ): It’s the period between entering a scope and the point where a let or const variable is declared. During this time, accessing the variable causes a ReferenceError, because the variable exists but hasn’t been initialized yet.

JavaScript
// TDZ example
console.log(x);            // ReferenceError (x in TDZ)
let x = 10;

console.log(y);            // undefined (var is initialized at hoist time)
var y = 10;

9. 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.).

10. What the difference between Lexical and Dynamic Scoping?

Lexical Scoping (Static Scoping)

  • 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)

  • 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.

11. What is the use of isNaN, and how is it different from Number.isNaN?

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.

  • Number.isNaN(x) → returns trueonly ifx is the NaN value. No coercion.
  • isNaN(x) → converts x to a number then checks if that result is NaN.
JavaScript
Number.isNaN(NaN)             // true
Number.isNaN("foo")           // false  (string, not NaN)
isNaN("foo")                 // true   (coerces "foo" → NaN)

Number.isNaN(undefined)     // false
isNaN(undefined)             // true   (undefined → NaN)

Number.isNaN("")             // false
isNaN("")                    // false  ("" → 0)

Number.isNaN(0/0)            // true   (is NaN)
isNaN(0/0)                   // true

12. 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.

13. 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.

14. Why is typeof null === "object"?

It’s a long-standing historical bug in the original typeof tag encoding that can’t be fixed without breaking the web.

  • null is a primitive, but typeof null returns "object".
  • Practical tip: check for null using value === null or value == null (to match null or undefined intentionally).

15. 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)

16. 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).

17. 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.

18. What will be theresult 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)

19. Write a JavaScript code for adding newelements 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>

20. 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);

Output
Inside 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.

21. 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.

22. 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;

23. 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).

24. 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

25. What are template literals and when do you use them?

Backtick strings that support interpolation, multi-line text, and tagged processing.

  • ${expr} interpolation without manual concatenation.
  • Preserve newlines/indentation as written.
  • Tagged templates for advanced parsing (e.g., sanitization, i18n).
JavaScript
const name = "Geeks";
const msg = `Hello, ${name}!
Your total is $${(19.99 * 2).toFixed(2)}.`;

26. 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.

27. Can closures leak memory?

JavaScript closures capture variables from their outer scope, but if not managed properly, they can sometimes lead to memory leaks.

Memory Leak Possibility: Closures can leak memory when they unintentionally keep references to variables or objects that are no longer needed. This prevents the garbage collector fro5 freeing that memory.

28. Does JavaScript allow multiple inheritance?

JavaScript does not support multiple inheritance in the traditional sense, but it provides ways to reuse and combine functionality.

  • Classes: JavaScript classes only allow single inheritance, meaning a class can extend only one parent class.
  • Prototypes: Objects can inherit from one prototype at a time, not multiple.
  • Mixins: To achieve similar behavior to multiple inheritance, JavaScript uses mixins—functions or objects that copy properties and methods into a class or object.

29. Is JavaScript statically typed or dynamically typed?

JavaScript is dynamically typed because we don’t have to tell JavaScript what kind of data (number, text, true/false, etc.) a variable will hold when you create it. The type is decided automatically when the program runs.

30. 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.

JavaScript
// 1. Global scope
console.log(this); // window (in browser)

// 2. Inside an object method
const obj = {
  name: "JS",
  say() {
    console.log(this.name);
  }
};
obj.say(); // "JS"

// 3. Regular function
function test() {
  console.log(this);
}
test(); // window (or undefined in strict mode)

// 4. Arrow function
const arrow = () => console.log(this);
arrow(); // inherits from outer scope (global -> window)

// 5. Constructor function
function Person(name) {
  this.name = name;
}
const p = new Person("Alice");
console.log(p.name); // "Alice"

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.

31. Explain the working of timers in JavaScript. Also explain the drawbacks of using the timer, if any.

JavaScript provides timers to schedule tasks after a delay or at regular intervals. These are not part of the JS engine itself, but come from the browser (Web APIs) or Node.js environment.

1. setTimeout:

Executes a function once after a specified delay (in milliseconds).

JavaScript
setTimeout(() => {
  console.log("Runs after 2 seconds");
}, 2000);

2. setInterval:

Executes a function repeatedly at a specified interval until cleared.

JavaScript
let count = 0;
const intervalId = setInterval(() => {
  count++;
  console.log("Runs every 1 second");
  if (count === 3) clearInterval(intervalId); // stop after 3 runs
}, 1000);

3. clearTimeout / clearInterval:

Used to stop a scheduled timer.

C++
const id = setTimeout(() => console.log("Won't run"), 3000);
clearTimeout(id); // cancels the timer

Timers in JS (setTimeout, setInterval) let you schedule tasks asynchronously. But they are not precise (due to event loop delays), can waste resources if misused, and should be cleared properly to avoid leaks.

32. 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.

33. 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.

34. How to submit a form using JavaScript?

You can use document.form[0].submit() method to submit the form in JavaScript.

35. Does JavaScript support automatic type conversion? 

Yes, JavaScript supports automatic type conversion.

36. 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.

37. 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.

38. 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.

39. Is JavaScript single-threaded or multi-threaded

JavaScript is single-threaded, but it uses asynchronous features to handle multiple tasks efficiently.

  • JavaScript runs on a single main thread, meaning it executes one command at a time in a sequence.
  • It was designed this way to simplify programming for the browser and avoid issues like race conditions when accessing the DOM.

40. 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.

41. What is the this keyword, and how does the call-site affect it?

JavaScript uses the this keyword as a reference to the object that is currently executing the code, but its value depends on the call-site (how and where the function is invoked).

  • Global/Function context: In non–strict mode, this refers to the global object (window in browsers). In strict mode, it is undefined.
  • Object method: When a function is called as a method of an object, this refers to that object.
  • Constructor function / class: When used inside a constructor or class, this refers to the newly created instance.
  • Explicit binding: Using call(), apply(), or bind(), you can explicitly set what this refers to.
  • Arrow functions: Unlike normal functions, arrow functions don’t have their own this; instead, they capture this from their surrounding (lexical) scope.

42. 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.

43. 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)

44. 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";

45. 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.

hoisting

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.

46. 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.

For more, read here: Detect Operating System on the Client Machine using JavaScript

47. What are the types of Pop up boxes available in JavaScript?

There are three types of pop boxes available in JavaScript.

48. 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.

49. 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.

50. How do call, apply, and bind change this?

JavaScript lets you control this using call, apply, and bind. They set what this points to when a function runs, and differ in when they run and how they accept arguments.

  • call: Invokes the function immediately, setting this to the first argument; remaining arguments are passed one-by-one.
  • apply: Invokes the function immediately, like call, but takes the arguments as a single array.
  • bind: Does not run immediately; returns a new function with this permanently set (and optionally some arguments pre-filled).JavaScript lets you control this using call, apply, and bind. They set what this points to when a function runs, and differ in when they run and how they accept arguments.

51. 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.

52. 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.

53. 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());

Output
1
1
1

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.

  1. Basic JavaScript
  2. Variables and Data Types
  3. Operators
  4. Control Flow
  5. Functions
  6. Objects
  7. Arrays
  8. DOM and BOM
  9. Event Handling
  10. Classes and Inheritance
  11. Modern JavaScript (ES6+)
  12. Advanced JavaScript
  13. Regular Expressions and JSON
  14. Asynchronous JavaScript
  15. Error Handling and Debugging

Explore