Fresher interview questions
JavaScript is a lightweight, interpreted programming language most commonly used to make web pages interactive. It runs natively inside every major browser, handling things like form validation, animations and dynamic content updates. Thanks to Node.js, JavaScript also runs outside the browser, powering servers, command-line tools and even desktop applications, which is a big part of why it has become one of the most widely used languages in the world.
var is function-scoped and can be redeclared and reassigned, but it ignores block boundaries like if statements, which often leads to confusing bugs. let is block-scoped and can be reassigned but not redeclared in the same scope. const is also block-scoped but cannot be reassigned after its initial value is set. Modern JavaScript style favors const by default and let only when a value genuinely needs to change.
undefined means a variable has been declared but has not yet been given a value, and it is also what a function returns by default when no return statement is written. null is an intentional value that a developer assigns to represent "no value" or "empty" on purpose. In practice, undefined usually signals something was forgotten, while null signals a deliberate absence of a value.
JavaScript has seven primitive types: string, number, boolean, undefined, null, symbol and bigint. Primitives are immutable and compared by their actual value rather than by reference, which is different from objects, arrays and functions, all of which are reference types compared by identity rather than content.
Type coercion is JavaScript automatically converting a value from one type to another when an operation expects a different type, such as turning the number 5 into the string "5" when it is combined with text using the plus operator. This can produce surprising results, like "5" plus 1 becoming "51" instead of 6, which is one reason many teams prefer the strict equality operator over automatic coercion when comparing values.
The == operator compares two values after converting them to a common type if they differ, which can lead to surprising results like 0 == "0" being true. The === operator, known as strict equality, compares both value and type without any conversion, so 0 === "0" is false. Most style guides recommend always using === to avoid coercion-related bugs.
A falsy value is one that behaves as false when evaluated in a boolean context, such as an if statement. JavaScript treats false, 0, an empty string, null, undefined and NaN as falsy. Every other value, including non-empty strings, objects and arrays, even an empty array or object, is considered truthy.
The most common ways are a function declaration, written as the function keyword followed by a name, parameters and a body, and a function expression, where a function is assigned to a variable. Function declarations are hoisted and can be called before they appear in the file, while function expressions are not available until the line where they are defined actually runs.
An arrow function is a shorter syntax for writing a function, introduced to make callbacks and short functions easier to write. Beyond the shorter syntax, its key behavioral difference is that it does not have its own this value; instead it inherits this from the surrounding code, which makes it especially useful inside callbacks where the traditional behavior of this would otherwise cause bugs.
A function declaration starts with the function keyword and a name at the statement level, and it is hoisted, meaning it can be called earlier in the code than where it is written. A function expression assigns a function to a variable, and it only becomes callable once that line of code actually executes, since only the variable declaration itself is hoisted, not the function assigned to it.
An array is an ordered list of values, which can be of any type and even mixed types, accessed by a numeric index starting at zero. The most common way to create one is with square brackets, such as const numbers equals an opening and closing bracket containing 1, 2, 3, though the Array constructor is also available for less common cases like pre-sizing an array.
An object is a collection of key-value pairs, where each key is a string or symbol and each value can be any type, including another object or a function. Objects are the primary way JavaScript models real-world entities, and they are typically created with curly-brace literal syntax, such as a user object holding name and age properties.
Common options include a standard for loop with an index, a for-of loop that iterates directly over each value, and the forEach array method, which calls a given function once for every item. for-of and forEach are generally preferred for readability when the index itself is not needed, while a standard for loop is still useful when finer control is needed, such as skipping items or looping backwards.
map creates a brand new array by calling a given function on every item of the original array and collecting the results, without changing the original array at all. It is the standard tool for transforming every element in a list, such as converting an array of prices into an array of prices with tax already added.
filter creates a new array containing only the items from the original array for which a given function returns true, leaving the original array untouched. It is the standard way to select a subset of items based on a condition, such as pulling out only the completed tasks from a longer list of tasks.
reduce processes every item in an array and combines them into a single accumulated value, using a function that receives the running total and the current item on each pass. It is commonly used to sum numbers, flatten nested arrays, or build up an object from a list, and it is one of the more flexible but also more commonly misunderstood array methods.
A template literal is a string written with backticks instead of quotes, allowing variables and expressions to be embedded directly inside the string using a dollar sign and curly braces, and allowing the string to span multiple lines without special characters. It largely replaced manually concatenating strings with the plus operator because it is easier to read and less error-prone.
The DOM, or Document Object Model, is the tree of objects a browser builds to represent every element on a web page after loading the HTML. JavaScript reads and modifies this tree to change what the user sees without reloading the page, which is the mechanism behind everything from updating text to adding brand new elements dynamically.
The most flexible method is querySelector, which accepts any CSS-style selector and returns the first matching element, with querySelectorAll returning every match as a list. Older methods like getElementById and getElementsByClassName still work and can be slightly faster for simple lookups, but querySelector has become the common default because its selector syntax is so familiar from CSS.
An event listener is a function registered to run automatically whenever a specific event, such as a click or a key press, happens on a particular element. It is attached using the addEventListener method, which takes the event name and the function to run, and it lets a page react to user actions without constantly checking for them.
event.preventDefault stops the browser's built-in default behavior for a given event, such as a form actually submitting and reloading the page, or a link navigating away. It is commonly called at the start of a submit handler when the form should be processed with JavaScript instead of the browser's normal page-reload behavior.
JSON, short for JavaScript Object Notation, is a text-based data format used to exchange data between a client and a server. It looks similar to a JavaScript object literal but is actually just a string, with stricter rules, such as requiring double quotes around every key. A JavaScript object, by contrast, is a live in-memory structure that can hold functions and other objects, which JSON cannot represent directly.
JSON.parse takes a JSON-formatted string and converts it into a real JavaScript object or array that code can work with directly. The reverse operation, turning a JavaScript object into a JSON string for sending over a network or saving to storage, is done with JSON.stringify.
typeof returns a string describing the type of a given value, such as "string", "number", "boolean", "undefined", "object" or "function". It is commonly used to check what kind of value a variable holds before operating on it, though it has a well-known quirk where typeof applied to null incorrectly returns "object", a long-standing bug preserved for backward compatibility.
NaN stands for "not a number" and represents the result of an invalid or undefined mathematical operation, such as dividing zero by zero or parsing text that is not numeric. Because NaN is famously not equal to itself, checking a value against NaN directly never works; instead, Number.isNaN or the global isNaN function should be used to reliably detect it.
push adds one or more new items to the end of an array and returns the array's new length, while pop removes the very last item from the array and returns that removed item. Both methods change, or mutate, the original array in place rather than creating a new one.
The spread operator, written as three dots, expands the elements of an array or the properties of an object into another array, object or function call. It is commonly used to copy an array or object without mutating the original, merge multiple arrays together, or pass a list of values as individual arguments to a function.
Destructuring is a syntax that lets you unpack values from an array or properties from an object into separate variables in a single, concise statement, rather than accessing each one individually with an index or property name. It is widely used when working with function parameters and with data returned from an API, since it makes the intended shape of the data immediately visible.
A callback function is a function passed as an argument to another function, intended to be called at a later point, often once some operation like a timer, a network request or an array iteration completes. Callbacks are the original way JavaScript handled asynchronous work before promises and async/await became common, and they still appear throughout the language, including inside array methods like map and forEach.
try wraps code that might fail, catch runs if an error occurs inside the try block, letting the program handle it gracefully instead of crashing, and finally runs afterward regardless of whether an error happened, making it the natural place for cleanup work such as closing a connection or hiding a loading indicator.
Scope determines where a variable is accessible within the code. JavaScript has global scope, visible everywhere, function scope, visible only inside the function where it is declared, and, since let and const were introduced, block scope, visible only inside the nearest pair of curly braces such as an if statement or loop.
A variable in global scope is declared outside any function and can be accessed from anywhere in the program, including inside every function. A variable in local scope is declared inside a function or block and can only be accessed within that function or block, which helps prevent different parts of a program from accidentally interfering with each other's data.
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their containing scope before the code actually runs. Function declarations are fully hoisted and callable immediately, var declarations are hoisted but initialized as undefined until their line runs, and let and const are hoisted but remain inaccessible until their declaration line, a state known as the temporal dead zone.
The ternary operator is a compact, one-line alternative to a simple if-else statement, written as a condition followed by a question mark, a value to use if the condition is true, a colon, and a value to use if it is false. It is best reserved for short, simple decisions, since chaining several together quickly becomes difficult to read.
forEach runs a given function once for every item in an array purely for its side effects, such as logging each value, and it always returns undefined. map also runs a function on every item but collects the return values into a brand new array. Use forEach when you just need to do something with each item, and map when a transformed array needs to be returned.
includes checks whether an array contains a specific value and returns true or false accordingly, without needing to write a manual loop or a separate indexOf check. It also correctly detects NaN as present in an array, unlike the older indexOf method, which cannot find NaN because of how NaN compares to itself.
String interpolation is the ability to embed variables or expressions directly inside a string, rather than manually joining separate pieces of text with the plus operator. In JavaScript this is done with template literals, using backticks and placing the expression inside a dollar sign followed by curly braces.
An anonymous function is a function defined without a name, typically written inline as an argument to another function, such as inside an event listener or an array method like map. Anonymous functions keep short, one-off pieces of logic close to where they are used, though a named function can still be preferable when the logic is reused or when a clearer stack trace is useful for debugging.
window is the global object provided by the browser, representing the browser tab or window itself. It holds global functions and values like setTimeout, alert and location, and in a browser environment, any variable declared globally with var effectively becomes a property of window, though this does not apply to variables declared with let or const.
localStorage is a simple key-value store built into the browser that lets a web page save small amounts of text data on the user's device, persisting even after the browser is closed and reopened. It is commonly used for things like remembering a user's theme preference or saving a draft of a form, though it is not suitable for large amounts of data or sensitive information like passwords.
An array is an ordered collection of values indexed by number, best suited to lists where position and order matter. An object is a collection of key-value pairs indexed by name, best suited to describing a single entity with named properties, such as a user with a name and an age. The right choice usually comes down to whether the data is thought of in terms of positions or in terms of named fields.
A new property can be added simply by assigning a value to it using dot notation, such as user.city set to "London", or using square bracket notation, such as user["city"] set to "London", which also allows the property name to come from a variable. Both approaches add the property immediately if it does not already exist, or overwrite it if it does.
Array.isArray reliably checks whether a given value is genuinely an array, returning true or false. It exists because typeof applied to an array unhelpfully returns "object", the same result it gives for a plain object, so Array.isArray is the correct and dependable way to distinguish an array from other object-like values.
A default parameter lets a function specify a fallback value to use for a parameter when the caller does not provide one, written directly in the function signature with an equals sign. This avoids the older pattern of manually checking whether an argument was undefined and assigning a fallback value inside the function body.
Strict mode, enabled with the string "use strict" at the top of a file or function, changes JavaScript to catch common mistakes as actual errors rather than silently allowing them, such as assigning to an undeclared variable or duplicating a parameter name. It also disables some confusing legacy behaviors, and code written as an ES module or inside a class runs in strict mode automatically.