JavaScript Interview Questions For Fresher - Interview Questions and Answers

JavaScript is a high-level, interpreted scripting language primarily used for adding interactive behavior to web pages. It runs in browsers as well as on servers (with Node.js).

Using the <script> tag either inline (<script>console.log('Hi');</script>) or by referencing an external file (<script src="script.js"></script>).

var is function-scoped and hoisted with undefined initialization; let and const are block-scoped and not accessible before declaration (temporal dead zone). const creates a constant reference (cannot be reassigned), while let allows reassignment.

Primitive types: string, number, boolean, undefined, null, symbol, bigint. Non-primitive: object (including arrays, functions, dates, etc.).

== checks for equality with type coercion; === checks for strict equality without type coercion. It is recommended to use === to avoid unexpected coercion.

false, 0, '' (empty string), null, undefined, and NaN are falsy; all other values are truthy.

NaN stands for Not-a-Number, a result of invalid numeric operations. Use Number.isNaN(value) (preferred) or isNaN(value) (looser) to check if a value is NaN.

undefined means a variable has been declared but not assigned a value. null is an assignment value representing “no value” or “empty”.

Hoisting moves declarations of variables (var) and function declarations to the top of their scope before code execution. Variables declared with let/const are hoisted but not initialized until their declaration is evaluated.

A function expression that runs immediately after being defined: (function(){ /* ... */ })();. It creates a private scope.

Function declarations (function foo(){}) are hoisted entirely. Function expressions (const foo = function(){} or arrow) are not usable before they are assigned.

A closure is when an inner function retains access to variables from its outer (enclosing) function’s scope even after the outer function has finished executing.

function outer() {
  let count = 0;
  return function() {
    count++;
    console.log(count);
  };
}
const fn = outer();
fn(); // 1
fn(); // 2

this refers to the object context in which a function is executed. In a method, it’s the owning object; in a standalone function (non-strict), it is the global object (undefined in strict mode); in event handlers, it’s the element; in arrow functions, this is lexically bound from the outer scope.

Arrow functions do not have their own this; they inherit this from the enclosing (lexical) context.

Event bubbling is when an event triggered on a child element propagates up through its ancestors in the DOM tree, invoking handlers on parent elements unless propagation is stopped.

Call event.stopPropagation() to prevent further propagation in the bubbling (or capturing) phase.

Attaching a single event listener to a parent element to handle events for multiple child elements via event bubbling, improving performance and dynamic element handling.

Use element.addEventListener('eventName', handler); avoid inline onclick attributes.

Call event.preventDefault() inside the event handler.

Document Object Model; a programming interface that represents HTML or XML documents as a tree of objects, allowing scripts to read/manipulate structure, style, and content.

Methods include document.getElementById(), document.getElementsByClassName(), document.getElementsByTagName(), document.querySelector(), document.querySelectorAll().

querySelector accepts any CSS selector and returns the first match; getElementById only finds by ID, often faster for that use.

JSON (JavaScript Object Notation) is a text format for data interchange. Use JSON.stringify(obj) to convert to string and JSON.parse(str) to convert to object.

Use localStorage or sessionStorage for key-value pairs (strings). Also cookies for small data.

localStorage persists until explicitly cleared; sessionStorage persists only for the session (cleared when tab/browser is closed).

Synchronous code runs sequentially, blocking further execution until completion. Asynchronous code allows non-blocking operations (e.g., callbacks, promises), so other code can run while waiting for results.

Functions passed as arguments to other functions to be executed later, often after an asynchronous operation completes.

“Callback hell” refers to deeply nested callbacks making code hard to read/maintain. It can be mitigated by using named functions, modularizing code, or using Promises/async-await.

Promises represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They have states: pending, fulfilled, or rejected.

const p = new Promise((resolve, reject) => {
  // async operation
  if (success) resolve(result);
  else reject(error);
});
p.then(result => { /*...*/ }).catch(err => { /*...*/ });

Syntactic sugar over Promises to write asynchronous code in a synchronous-looking style. An async function returns a Promise; await pauses execution until the Promise resolves or rejects.

The mechanism that handles asynchronous callbacks: it processes tasks from the call stack and task queues (microtask/macrotask) so non-blocking operations can complete.

Microtasks (e.g., Promise callbacks) run after the current call stack but before rendering and before macrotasks (e.g., setTimeout callbacks). Understanding this helps predict execution order.

Schedules a callback to run after at least the specified delay (in milliseconds). The callback is queued as a macrotask; exact timing depends on event loop and other tasks.

Use the Fetch API: fetch(url).then(response => response.json()).then(data => { … }).catch(err => { … }). You can also use async/await with fetch.

Cross-Origin Resource Sharing; a browser security feature that restricts cross-origin HTTP requests unless the server allows them via response headers like Access-Control-Allow-Origin.

== null is true for both null and undefined (due to type coercion), whereas === null is true only for null.

Activated with "use strict";. It enforces stricter parsing and error handling (e.g., disallowing use of undeclared variables, silent errors become thrown, changes to this in functions).

Place "use strict"; at the top of a script or function.

Every object has an internal link to a prototype object. The prototype holds properties/methods that are shared among instances created from a constructor function.

When accessing a property on an object, JS looks at the object itself; if not found, it follows the internal [[Prototype]] chain to look up properties/methods in ancestor prototypes.

Several ways: object literal (const obj = {}), constructor function with new, Object.create(proto), or ES6 class syntax (class MyClass { } and new MyClass()).

Object.create(proto) creates a new object with its prototype set to proto directly. Constructor functions set up the prototype via Function.prototype and may initialize properties inside the function body.

A concise syntax for function expressions: const add = (a, b) => a + b;. They have lexical this, cannot be used as constructors, and do not have their own arguments object.

You can assign default values to function parameters: function fn(a = 1, b = 2) { … }. If an argument is undefined, the default is used.

Syntax function fn(...args) collects remaining arguments into an array args. Useful for variable-arity functions.

Syntax ... can spread elements of an iterable into function arguments or array literals ([...arr]), or spread object properties ({ ...obj }).

Several ways: arr.slice(), [...arr], Array.from(arr), or arr.concat().

For shallow copy: Object.assign({}, obj) or { ...obj }. For deep copy of simple objects: JSON.parse(JSON.stringify(obj)), noting it fails for functions, Dates, etc.

Syntax to unpack values from arrays or properties from objects:

const [a, b] = [1, 2];
const { x, y } = { x: 10, y: 20 };

Backtick-delimited strings allowing embedded expressions: const msg = `Hello ${name}`;. They support multiline strings directly.

forEach, map, filter, reduce, find, some, every, includes, slice, splice, etc.

map returns a new array with the result of applying the callback to each element; forEach simply iterates and returns undefined.

Returns a new array containing elements that satisfy the callback’s condition (returning truthy).

Accumulates array elements into a single value by applying a callback with accumulator and current element, optionally with an initial value.

for...in iterates over enumerable property keys of an object; on arrays, keys (indices) are returned. for...of iterates over iterable values (e.g., array elements, strings).

Using in operator ('prop' in obj) or obj.hasOwnProperty('prop') to check own properties.

Own properties are defined directly on the object; inherited come from its prototype chain.

Accessing a non-existent property returns undefined. However, a property explicitly set to undefined also returns undefined; to distinguish, use hasOwnProperty or in.

typeof NaN returns "number".

It is a long-standing bug/quirk in JavaScript; null is not an object, but typeof reports "object" for legacy reasons.

Primitive types are immutable and compared by value; reference types (objects, arrays, functions) are compared by reference, and variables hold references to memory locations.

Direct comparison (obj1 === obj2) checks reference equality. To compare contents, iterate properties or use deep-equality utilities.

A function that takes another function as an argument or returns a function.

A function passed as an argument to another function to be called later, often after an asynchronous operation or event.

Variables declared with var have function scope; let and const have block scope (inside {}).

Functions are executed using the variable scope in which they were defined, not where they are called.

Using try { ... } catch (err) { ... } finally { ... } to catch exceptions. For promises, use .catch() or try/catch with async/await.

Synchronous errors are caught via try/catch. Asynchronous (Promise-based) errors require .catch() or try/catch inside async functions.

Use console.log, breakpoints with browser devtools (Sources panel), debugger statement, and inspecting call stack or variable values.

NaN === NaN is false. Use Number.isNaN to check for NaN.

parseInt(string, radix) parses until a non-numeric character, returning an integer. Number(string) converts the entire string to a number or returns NaN if invalid.

Use Number(str), parseInt(str, 10), parseFloat(str), or unary plus +str.

Use String(num), num.toString(), or template literal: ${num}.

Using if (!value) checks for all falsy values, not just false. Explicit === comparison checks for strict equality to a specific value.

A shorthand for if statements: condition ? exprIfTrue : exprIfFalse.

switch (value) {
  case 'a':
    // ...
    break;
  case 'b':
    // ...
    break;
  default:
    // ...
}

Sequentially calling .then() on a promise, where each .then can return another promise or value, enabling ordered asynchronous operations.

A modern interface for making HTTP requests returning Promises: fetch(url, options).then(response => ...).

fetch(url)
  .then(response => {
    if (!response.ok) throw new Error('Network error');
    return response.json();
  })
  .then(data => { /* use JSON data */ });

async function getData() {
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error('Error');
    const data = await response.json();
    return data;
  } catch (err) {
    // handle error
  }
}

Browser blocks cross-origin requests without proper headers. Fix by enabling appropriate Access-Control-Allow-Origin on the server or using a proxy.

A function provided to handle the event when it occurs, e.g., button.addEventListener('click', () => { /*...*/ }).

addEventListener allows attaching multiple handlers and specifying options (capture, once), while onclick assigns a single handler, overriding previous ones.

It indicates loading status of the document: "loading", "interactive", or "complete". Can be used to run code when DOM is ready.

Use document.addEventListener('DOMContentLoaded', () => { /*...*/ }); to run code after initial HTML is parsed.

Small pieces of data stored by the browser, accessible via document.cookie, used for session management, preferences, etc. They have size limits and security considerations.

document.cookie = "username=Bob; expires=Fri, 31 Dec 2025 12:00:00 GMT; path=/";
// To read: parse document.cookie string manually or with helper functions.

Typically around 5–10 MB per origin, depending on the browser.

In strict mode, certain silent errors throw exceptions; this in functions is undefined instead of the global object; you can attempt problematic code (e.g., assigning to undeclared variable) to see if it throws.

Returns a string indicating the type of a value, such as "string", "number", "boolean", "undefined", "object", "function", or "symbol".

Use Array.isArray(value). typeof returns "object" for arrays, so use Array.isArray.

Result of invalid numeric operations, e.g., 0/0. It propagates through arithmetic: any operation with NaN yields NaN.

Using callbacks (e.g., passing callback functions into async methods), leading to nested structures often called callback hell.

A legacy technique to request cross-origin data by injecting a <script> tag; requires server support and has security limitations. Mostly replaced by CORS.

Technique to limit how often a function is called by delaying execution until a certain inactivity period; commonly used in handling frequent events like resizing or typing. (Implementation often done via setTimeout.)

Technique to ensure a function is called at most once in a specified time interval; helps control event frequency. (Also implemented using timers.)

innerHTML sets or returns HTML markup as string (parsed into elements), while textContent sets or returns text only, escaping HTML.

Use document.createElement('tagName'), set properties or attributes (e.g., elem.textContent = 'Hello'), then insert into the DOM via methods like appendChild or insertBefore.