JavaScript Interview Questions for 1–2 Years Experience - Interview Questions and Answers

JavaScript supports Primitive (String, Number, Boolean, Null, Undefined, Symbol, BigInt) and Non-Primitive (Object, Array, Function) data types.

== checks for value equality with type coercion. === checks for both value and type equality.

undefined means a variable has been declared but not assigned a value. null is an assignment value that represents no value.

A closure is a function that has access to its own scope, the scope of the outer function, and the global scope.

  • var is function-scoped and can be redeclared.
  • let is block-scoped and can be reassigned.
  • const is block-scoped and cannot be reassigned.

Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope before code execution.

Synchronous code runs sequentially. Asynchronous code runs independently using callbacks, promises, or async/await.

Event delegation is a technique to handle events at a higher level in the DOM rather than on individual elements.

Arrow functions provide a shorter syntax for writing functions and do not bind their own this.

this refers to the object from which a function is called. Its value depends on the context in which it is used.

A promise is an object representing the eventual completion or failure of an asynchronous operation.

Using try...catch blocks or by handling promise rejections with .catch().

  • map() creates a new array with the results of calling a function on every element.
  • filter() creates a new array with elements that pass a test.
  • forEach() executes a function for each element but does not return a new array.

  • call() invokes a function with arguments passed individually.
  • apply() invokes a function with arguments passed as an array.
  • bind() returns a new function with a specific this value.

  • setTimeout() runs a function once after a delay.
  • setInterval() runs a function repeatedly with a fixed time delay between each call.

The DOM (Document Object Model) is a programming interface for web documents, representing the page as a tree of objects.

Template literals are string literals allowing embedded expressions using backticks `` and ${} syntax.

  • A shallow copy copies only the first level of the object.
  • A deep copy copies all levels recursively.

Using Array.isArray(object).

Function parameters that have default values if no value or undefined is passed.

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

Recursion is a technique where a function calls itself until a base condition is met.

A function passed into another function as an argument to be executed later.

The spread operator ... allows an iterable to be expanded in places where arguments or elements are expected.

The rest operator ... collects multiple elements into a single array.

  • freeze() prevents adding/removing/updating properties.
  • seal() prevents adding/removing but allows updating existing properties.

The event loop handles asynchronous callbacks in JavaScript by placing them in a queue and executing them one by one.

Returns the type of a given variable or expression.

Using Object.assign({}, obj) or the spread operator {...obj}.

JSON is a format for storing and transporting data. Use JSON.parse() to parse and JSON.stringify() to convert to string.

Values that evaluate to false: false, 0, -0, 0n, "", null, undefined, and NaN.

  • getElementById() selects by ID.
  • querySelector() selects the first element matching a CSS selector.

Objects can inherit properties from another object using __proto__ or Object.create().

  • Declarations are hoisted.
  • Expressions are not hoisted and can be anonymous.

A function that produces the same output for the same input and has no side effects.

Caching the result of expensive function calls to avoid redundant calculations.

A technique to limit the rate at which a function is executed. Useful in input events.

A function is allowed to run at most once in a specified time interval.

  • localStorage stores data with no expiration.
  • sessionStorage stores data until the session ends.

Modules help divide code into reusable pieces using import and export.

  • Mutable: Can be changed (e.g., objects, arrays).
  • Immutable: Cannot be changed (e.g., strings, numbers).

  • innerHTML parses HTML inside the element.
  • textContent sets or gets only the text content.

Functions like setTimeout() and setInterval() used to delay or repeat execution.

Immediately Invoked Function Expressions are functions that run immediately after they're defined.

The new keyword is used to create an instance of an object or a constructor function.

A special function used to create and initialize an object created with the new keyword.

  • Function: A standalone block of code.
  • Method: A function that is a property of an object.

A primitive data type used to create unique identifiers.

Use event.preventDefault() in the event handler.

Use event.stopPropagation() or event.stopImmediatePropagation().

  • Bubbling: The event starts from the target element and bubbles up to the root.
  • Capturing: The event starts from the root and goes down to the target.
    Use addEventListener(type, listener, useCapture) to specify capturing phase.

A technique to handle events efficiently by assigning a single event listener to a parent element that handles events from its children.

It contains information about the browser, such as name, version, platform, and userAgent.

It allows you to interact with the browser session history (e.g., history.back(), history.forward()).

  • localStorage: Stores data with no expiration.
  • sessionStorage: Stores data for the duration of the page session.
  • cookies: Stores data with expiration, sent with every HTTP request.

 

It safely accesses nested properties without throwing an error if an intermediate value is null or undefined.

Returns the right-hand operand when the left is null or undefined.

async functions return a promise, and await pauses execution until the promise resolves or rejects.

  • Microtasks: Promise callbacks, MutationObservers (executed first).
  • Macrotasks: setTimeout, setInterval, I/O tasks.

When memory that is no longer needed is not released. Often caused by unused references.

WeakMap and WeakSet hold references that do not prevent garbage collection.

The engine automatically frees up memory by removing objects that are no longer reachable.

eval() executes a string of JavaScript code, but it's unsafe and leads to security issues and performance degradation.

A polyfill is code that provides missing functionality on older browsers.

Functions declared with function* that can pause execution with yield and resume later.

Advanced form of template literals using a function to process template strings.

Transforming a function with multiple arguments into a sequence of functions each taking a single argument.

 

Combining multiple functions together where the output of one becomes the input to the next.

 

It creates a new object using an existing object as the prototype.

Both copy properties, but Object.assign() doesn't copy inherited properties, and both can perform shallow copies.

Extracting values from arrays or properties from objects into distinct variables.

Tools like Handlebars, EJS, or Mustache that help generate HTML dynamically using templates

Object.is() is similar to === but handles NaN and -0/+0 more precisely.

  • Imperative: How to do something (step-by-step).
  • Declarative: What you want to do (more abstract, like React).

Methods defined on the class, not on the instance. Used with utility functions.

 

Methods defined on the instance of a class (using this).

A function that returns a new object every time it is called, without using new.

Objects that are instantiated only once and shared across the application.

 

Extends the scope chain for a statement block. Deprecated due to ambiguity and poor performance.

Using URLSearchParams:

const params = new URLSearchParams(window.location.search);
params.get('id');

When multiple functions are called on the same object in a single line, returning this allows chaining.

Reusable object properties or methods that can be combined into other objects or classes.

 

Used to define custom behavior for fundamental operations like property lookup, assignment, enumeration, etc.

 

An interface for defining custom asynchronous iteration behavior with for await...of.

  • window in browsers
  • global in Node.js

They return arrays of the object's entries, keys, and values, respectively.

Connecting .then() handlers together to handle asynchronous operations sequentially.

 

Use structuredClone(obj) (modern), or JSON parse/stringify (with limitations), or libraries like Lodash's cloneDeep.

 

Example:

const [a, b] = [1, 2];

  • Class is a newer syntax to create objects.
  • Prototype is the underlying inheritance mechanism.

  • Synchronous uses for...of.
  • Asynchronous uses for await...of with async iterables.

 

  • Promise.all(): waits for all.
  • Promise.race(): resolves/rejects with the first.
  • Promise.allSettled(): waits for all to settle.
  • Promise.any(): resolves with first fulfilled.

  • Declaration: function foo() {} (hoisted)
  • Expression: const foo = function() {}; (not hoisted)

Used to expand elements:

function sum(a, b, c) {}  
sum(...[1, 2, 3]);

Using window.onerror, try/catch in async functions, or top-level Promise.catch() handlers.

 

Store results based on arguments in a cache object. Use libraries like Lodash's _.memoize().

Use .flat():

[1, [2, 3], [4, [5]]].flat(2);

An optimization where the last function call returns directly, reducing stack usage. Supported in strict mode (rarely implemented in JS engines).

 

A built-in symbol that defines the default iterator for an object used in for...of.

 

  • Use browser DevTools (Console, Sources tab)
  • Add breakpoints, use console.log(), use debugger statement
  • Use linting tools like ESLint to prevent bugs