Skip to content

Instantly share code, notes, and snippets.

@celmaun
Created January 24, 2026 01:03
Show Gist options
  • Select an option

  • Save celmaun/053a43f30c75c42f3bbecfcad050a322 to your computer and use it in GitHub Desktop.

Select an option

Save celmaun/053a43f30c75c42f3bbecfcad050a322 to your computer and use it in GitHub Desktop.
frontend-interview-questions.md

Frontend Interview Questions

HTML

Based on the principles of modern web standards, which of the following best describes "Semantic HTML" and its primary importance?

A. It acts as a server-side directive that compiles HTML into binary code for faster execution. B. It refers to using specific HTML markup that reflects the type and meaning of the content (e.g., <article><footer>), which is crucial for accessibility and SEO context. C. It is a deprecated method of styling that uses attributes like font-color directly within tags to ensure older browsers can read the text. D. It is a strict validation rule that prevents the page from rendering if tags are not closed properly.

Correct Answer: B. Semantic HTML uses tags that reflect the content's type.   

What is the specific function of the <!DOCTYPE> declaration at the beginning of an HTML document?

A. It imports the CSS library to ensure the page is styled correctly. B. It acts as a security token to prevent Cross-Site Scripting (XSS) attacks. C. It informs the browser which version of HTML is being used (e.g., <!DOCTYPE html> for HTML5), ensuring the page renders in "standards mode." D. It creates a root container for the DOM, similar to the <html> tag.

Correct Answer: C

What is the significance of the <title> tag, and where must it be placed within the document structure?

A. It is placed in the <body> and creates the largest heading on the page (H1) for users to read. B. It is placed in the <head> section; it defines the text shown in the browser tab and serves as the clickable headline in search engine results. C. It is a metadata attribute inside the <html> tag that names the document for file saving purposes. D. It is placed in the <footer> to assert copyright ownership of the page title.

Correct Answer: B

Which statement accurately describes the functional rules and differences between id and class attributes?

A. class implies uniqueness and can only be used once per page; id is for multiple items. B. id and class are functionally identical and can be used interchangeably without restriction. C. id is only used for database records, while class is for HTML styling. D. id is a unique identifier used once per page; class can be applied to multiple elements. IDs also have higher CSS specificity.

Correct Answer: D

Which attribute is mandatory for the <img> tag to ensure accessibility for screen readers?

A. title B. caption C. alt D. desc

Correct Answer: C

Which sequence of tags represents the correct hierarchy for a standard HTML table?

A. <table><tr> (row), <th> (header), <td> (data) B. <table><row><cell> C. <grid><line><box> D. <sheet><r><c>

Correct Answer: A

CSS

What does the acronym CSS stand for, and what is its primary architectural role in web development?   

A. Cascading Scripting System: Used to define the server-side logic and database interactions for a web application. A. Computer Style Sheets: Used to compress images and optimize media assets for faster loading. A. Creative Style System: A JavaScript library used for creating vector animations and interactive graphics. A.  Cascading Style Sheets: A language designed to describe the presentation of a document, effectively separating visual design from semantic content.

Correct Answer: B

What is the primary purpose of implementing a CSS Reset (or using tools like Normalize.css)?   

A. Consistency: To minimize cross-browser inconsistencies by resetting inconsistent default user-agent styles (like margins, headings, and list styles) to a baseline standard. B. Security: To remove malicious code injected into the CSS by third-party ads. C. Performance: To delete unused CSS classes from the file to reduce file size. D. Validation: To automatically fix syntax errors in the CSS code.

Correct Answer: A

Which of the following is an example of a pseudo-class used to style an element when a user's mouse is over it?

A. ::before B. :active C. ::first-line D. :hover

Correct Answer: D

Which CSS property combination is the modern standard for centering a child element both horizontally and vertically within a parent container?   

A. display: flex; justify-content: center; align-items: center; B. text-align: center; vertical-align: middle; C. position: absolute; top: 50%; left: 50%; D. float: center; clear: both;

Correct Answer: A

What is the fundamental structural difference between CSS Grid and Flexbox?   

A. Performance: Grid is strictly for desktop browsers, while Flexbox is for mobile. B. Syntax: Flexbox uses XML syntax, while Grid uses JSON. C. Axis Dimensionality: Flexbox is a one-dimensional layout system (dealing with rows or columns), while Grid is a two-dimensional system (dealing with rows and columns simultaneously). D. Deprecation: Flexbox is the legacy version of Grid and should no longer be used.

Correct Answer: C

When an element is set to position: absolute, what is it positioned relative to?   

A. The Viewport: It is always positioned relative to the browser window. B. The Nearest Positioned Ancestor: It is positioned relative to the closest ancestor element that has a position value other than static. C. The Parent: It is always positioned relative to its direct parent element in the HTML. D. The Document Body: It is always positioned relative to the <body> tag.

Correct Answer: C

What is the functional difference between visibility: hidden and display: none?   

A. Layout Footprint: visibility: hidden hides the element but it still occupies space in the layout; display: none removes the element from the document flow entirely, occupying no space. B. Interactivity: display: none allows the user to still click the element, while visibility: hidden does not. C. Animation: display: none can be animated, while visibility: hidden cannot. D. Syntax: visibility: hidden is valid CSS3, while display: none is deprecated.

Correct Answer: A

JavaScript

Which of the following descriptions most accurately categorizes the JavaScript language?

A. A low-level, statically compiled language designed primarily for multi-threaded server-side computations. B. A high-level,interpreted (and JIT-compiled), dynamic programming language that supports object-oriented, functional, and event-driven paradigms. C. A strictly procedural language that runs exclusively in client-side browser environments and cannot handle file system operations. D. A markup language integrated into HTML5 for defining dynamic content structures and styling.

Correct Answer: B

Which of the following options represents a comprehensive and accurate list of JavaScript’s Primitive data types?

A. String, Number, Boolean, Null, Undefined, Symbol, BigInt. B. String, Number, Boolean, Object, Symbol, Null. C. Array, Function, Object, String, Number. D. Boolean, Null, Undefined, Map, Set, WeakMap.

Correct Answer: A

What is the functional difference between the Loose Equality Operator (==) and the Strict Equality Operator (===)?

A. === performs type coercion to ensure both values arecomparable, whereas == does not. B.  == checks only the value and ignores the type, performing implicit type coercion if necessary; === compares both value and type, returning false if types differ. C.  === is a deprecated operator in ES6 and should be replaced by Object.is(). D.  == is faster in execution because it skips the type check step.

Correct Answer: B. ==  attempts to convert operands to the same type (usually number) before comparing. === requires both type and value to match exactly.

Regarding the scoping and initialization behaviors of var,  let, and const, which statement is technically accurate?

A. var declarations are block-scoped and are not hoisted to the top of their context. B. const variables are immutable, meaning that if a const variable holds an object, the properties of that object cannot be modified. C. let and const declarations are hoisted but remain in the Temporal Dead Zone (TDZ) until execution reaches their definition, preventing access before initialization. D.  let variables can be redeclared within the same scope without throwing a syntax error.

Correct Answer: C. This accurately describes the TDZ mechanism. The engine reserves memory for the variable upon entering the scope, but strictly forbids access until the declaration line.

Which statement best captures the semantic and technical distinction between null and undefined?

A. undefined is an object, whereas null is a primitive. B. typeof null returns “null” and typeof undefined returns “undefined”. C. They are interchangeable in JSON data structures. D. undefined indicates a variable has been declared but not yet assigned a value; null is an assignment value representing the intentional absence of any object value.

Correct Answer: D. This aligns with standard usage: undefined is “system-set” emptiness; null is “user-set” emptiness.

Which of the following arrays contains only falsy values in JavaScript?

A. [false, 0, "", null, undefined, NaN]  B. [false, 0, "0", null, undefined]  C. [false, -1, "", null, undefined]  D. [false, 0,, {}, NaN]

Correct Answer: A. These are the 6 core falsy values (plus newly added BigInt 0n). Any other value is truthy.

How do typeof and instanceof differ in their mechanism and return values?

A.  typeof is used for classes; instanceof is used for primitives. B.  typeof returns a string description of the primitive type; instanceof returns a boolean checking if an object’s prototype chain contains the constructor’s prototype property. C.  typeof reliably identifies Arrays as “array”. D. instanceof works across different window contexts (iframes) seamlessly.

Correct Answer: B. typeof gives strings like 'string' or 'number'instanceof verifies inheritance: dog instanceof Animal.

In a standard function (non-arrow), what determines the value of this?

A. The scope in which the function was defined. B. It is always the global object. C. It is always the object containing the function. D. The call-site (how the function is invoked).

Correct Answer: D. If called as obj.func()this is obj. If called as func()this is global/undefined. If called via call/applythis is explicitly set.

Besides concise syntax, what is the critical functional difference between Arrow Functions and regular functions?

A. Arrow functions are hoisted, whereas regular functions are not. B. Arrow functions do not have their own this binding; they inherit this from the enclosing lexical scope. C. Arrow functions can be used as constructors with the new keyword. D. Arrow functions have access to the arguments object.

Correct Answer: B. This makes arrow functions ideal for callbacks (e.g., inside setTimeout or class methods) where you want this to remain the class instance.

Why is typeof variable insufficient for checking if a value is an Array, and what is the correct alternative?

A. typeof returns “array”, which is not supported in IE. B. typeof returns “undefined” for empty arrays. C. typeof returns “object” for arrays; Array.isArray(variable) should be used instead. D. Arrays are technically strings in the V8 engine.

Correct Answer: C. Since arrays are objects, typeof is technically correct but useless for distinction. Array.isArray() checks the internal [[Class]] slot.

What is the primary function of Destructuring assignment in ES6?

A. To delete properties from an object. B. To unpack values from arrays or properties from objects into distinct variables using a concise syntax. C. To create immutable data structures. D. To automaticallly sort arrays.

Correct Answer: B. Example: const { name, age } = user; extracts specific fields.

Why is Object.assign({}, obj) considered a “shallow copy”?

A. It copies only the first 5 properties of the object. B. It creates a new object and copies the top-level properties, but nested objects are still copied by reference, meaning changes to nested data affect the original. C. It converts the object to a string before copying. D. It works only on Arrays, not Objects.

Correct Answer: B. If obj contains another object {a: {b: 1}}, the shallow copy will point to the same {b: 1} in memory.

Which method represents a valid strategy for performing a Deep Copy of a JSON-safe object?

A. const copy = {...original }  B. const copy = JSON.parse(JSON.stringify(original))  C. const copy = Object.assign({}, original)  D. const copy = original.clone()

Correct Answer: B. This serialization/deserialization trick works for plain data but fails on Functions, Dates, and undefined. Modern usage prefers structuredClone().

Which snippet correctly uses the Spread Operator (...) to merge two arrays into a new one?

A. const combined = [arr1, arr2];  B. const combined = [...arr1,...arr2];  C. const combined = arr1 + arr2;  D. const combined = Object.assign(arr1, arr2);

Correct Answer: B. This creates a new array and “spreads” the contents of both source arrays into it.

How does Asynchronous code execution differ from Synchronous execution in JavaScript?

A. Synchronous code runs in parallel threads; Asynchronous code runs on a single thread. B. Synchronous code blocks execution until the current task completes; Asynchronous code initiates a task and allows the program to continue executing subsequent lines immediately. C. Asynchronous code is only possible using Web Workers. D. Synchronous code is faster because it does not use the Callback Queue.

Correct Answer: B. This is the “Non-blocking” I/O model.

What are the three mutually exclusive states of a JavaScript Promise?

A. StartRunningFinished. B. PendingFulfilledRejected. C. UnsentOpenedLoading. D. TrueFalseNull.

Correct Answer: B. A Promise starts Pending. It transitions once to either Fulfilled (success) or Rejected (error). This immutability of state is key.

What does the await keyword actually do inside an async function?

A. It blocks the entire browser thread. B. It pauses the execution of the surrounding async function until the Promise resolves, without blocking the main thread. C. It converts a Promise into a callback. D. It forces a function to run on a background thread.

Correct Answer: B. The function yields execution, allowing the Event Loop to process other tasks, and resumes when the Promise settles.

What syntax is used to define ES6 Modules?

A. module.exports and require  B. import and export  C. include and define  D. using and namespace

Correct Answer: B.

What is a Callback function in JavaScript?

A. A function that calls itself recursively. B. A function that runs only when an error occurs. C. A method used to bind this to an object. D. A function passed as an argument to another function, which is then invoked inside the outer function to complete some kind of routine or action.

Correct Answer: D. While conceptually simple, overuse leads to “Callback Hell” (deep nesting), which Promises were designed to solve.

Which definition accurately describes a Higher-Order Function?

A. A function that executes faster than standard functions due to priority scheduling. B. A function that either takes one or more functions as arguments or returns a function as its result. C. A function that is defined inside a class. D. A function that utilizes the await keyword.

Correct Answer: B. Examples include map (takes a function), filter (takes a function), and closure factories (return a function).

Which statement accurately distinguishes map()filter(), and reduce()?

A. map modifies the array in place; filter returns a new array. B. map returns a new array of the same length with transformed items; filter returns a subset array; reduce accumulates the array into a single value. C. reduce is used only for numeric addition. D. filter returns the first item matching a condition.

Correct Answer: B. map is for transformation (1:1). filter is for selection (N:M where M<=N). reduce is for aggregation (N:1).

How does JavaScript manage memory allocation and deallocation?

A. Developers must manually allocate memory using pointers. B. Memory is only cleared when the browser tab is refreshed. C. It uses automatic Garbage Collection (GC), primarily via the Mark-and-Sweep algorithm, to reclaim memory from objects that are no longer reachable from the root. D. It uses a reference-counting algorithm exclusively, which cannot handle circular references.

Correct Answer: C. The GC starts from “roots” (global object, stack variables) and marks all reachable objects. Unmarked objects are swept. This handles circular references (where A references B and B references A, but neither is reachable from root) correctly.

The fetch() API returns a Promise that resolves to what?

A. The parsed JSON data. B.Response object representing the HTTP response, which must be further processed (e.g., .json()). C. The HTTP status code as an integer. D. A readable stream that cannot be cancelled.

Correct Answer: B. fetch resolves as soon as headers are received. You must asynchronously read the body.

What is the DOM?

A. The browser’s JavaScript engine. B. A tree-like representation of the HTML document that allows JavaScript to access and manipulate page content, structure, and style. C. A set of CSS rules applied to the page. D. A server-side database.

Correct Answer: B. It connects the web page (HTML) to scripts or programming languages.

Which method allows you to select the first element that matches a specific CSS selector?

A. document.getElementById()  B. document.querySelectorAll()  C. document.querySelector()  D. document.getElementsByTagName()

Correct Answer: C.

If you select the same DOM element using two different selectors, what will element1 === element2 return?

A.  false, because they are different variables. B.  true, because they refer to the exact same node object in memory. C. It depends on the browser. D.  true, but only if they have the same ID.

Correct Answer: B. The DOM API returns a reference to the singleton node object.

What is the principle of Event Delegation?

A. Using setTimeout to delay events. B. Creating custom events. C. Attaching a single event listener to a parent element to manage events for its children using the event bubbling mechanism. D. preventing default actions.

Correct Answer: B. This optimizes memory (1 listener vs N listeners) and handles dynamic content.

How do you prevent the default behavior (like a form submission reload) in an event handler?

A. event.stopPropagation()  B. event.preventDefault()  C. return null  D. event.stopImmediatePropagation()

Correct Answer: B. stopPropagation stops bubbling; preventDefault stops the browser action.

Which storage mechanism is persistent, limited to ~5MB, and sent only on client-side requests (not to server)?

A. Cookies B. SessionStorage C. LocalStorage D. Cache API

Correct Answer: C. LocalStorage persists until cleared. Cookies are sent to the server (bandwidth overhead). SessionStorage dies with the tab.

What is the primary role of a Service Worker?

A. To manipulate the DOM on a background thread. B. A script running in the background, acting as a network proxy to enable offline capabilities, caching, and push notifications. C. To compile TypeScript to JavaScript. D. To manage database connections.

Correct Answer: B. Service workers cannot access the DOM directly; they handle network traffic.

Git (Version Control System)

Which of the following descriptions most accurately describes Git?

A. A centralized version control system that locks files to prevent conflicts and stores data as a series of file diffs. B. A distributed version control system (DVCS) where every client clone is a full backup of the repository, storing data as a stream of snapshots in a content-addressable filesystem. C. A cloud-based storage service designed primarily for hosting open-source code, dependent on an active internet connection for version history. D. A linear compilation tool that automatically merges code changes from multiple developers into a single binary.

Correct Answer: B. Git is fundamentally distributed (every user has the full history) and uses a “snapshot” model rather than a “delta” (diff) model for storage. It addresses content by the SHA-1 hash of its data, making it a content-addressable filesystem.

You have an existing directory of code on your local machine that is not yet version controlled. You want to start tracking it with Git. Which command should you run inside the directory?

A. git start B. git clone. C. git init D. git config --init

Correct Answer: C. git init creates the .git subdirectory and initializes the repository structure. git clone is for copying remote repositories, not initializing local ones.   

A file in a Git repository can exist in one of several states. Which sequence correctly represents the lifecycle of a new file being added to the project?

A. Untracked -> Staged -> Committed B. Modified -> Committed -> Pushed C. Staged -> Modified -> Tracked D. New -> Cached -> Saved

Correct Answer: A. A new file starts as Untracked. Running git add moves it to Staged. Running git commit moves it to Committed (Unmodified in the working tree).

What is the specific architectural purpose of the “Staging Area” (or Index) in Git?

A. It is a temporary cache that stores files only when the network connection to the remote is lost. B. It is a mechanism to group specific changes from the working directory into the next commit snapshot, allowing developers to split work into logical, atomic commits. C. It is the area where merge conflicts are automatically resolved by the Git engine. D. It is a backup folder where deleted files are stored for 30 days.

Correct Answer: B. The Staging Area allows developers to curate exactly what goes into a commit. You can modify 10 files but only git add 3 of them, ensuring the commit history remains clean and atomic.

What is the fundamental difference between git merge and git rebase when integrating a feature branch into the main branch?

A. git merge preserves the exact history of events (creating a merge commit), whereas git rebase rewrites history to create a linear progression of commits. B. git merge is used for local branches, while git rebase is used for remote branches. C. git rebase is safer for public branches because it does not change commit hashes. D. git merge automatically resolves conflicts, while git rebase does not.

Correct Answer: A. Merging creates a “diamond” shape in the history (preserving the context of the branch). Rebasing “lifts” the commits and replays them on top of the target, creating a straight line but changing the commit hashes (rewriting history).

A developer creates a file script.sh, adds it to the staging area using git add script.sh, and then modifies the file again in the working directory without running git add  a second time. What content will be saved to the repository if the developer immediately runs git commit -m "Add script"?

A. The version of script.sh currently in the working directory (including the latest edits). B. The version of script.sh at the moment git add was executed (excluding the latest edits). C. Git will pause and ask the user which version to commit. D. The commit will fail because the file is in a “partially staged” state.

Correct Answer: B. The Staging Area (Index) captures a snapshot of the file at the precise moment git add is run. Subsequent changes in the working directory are “Modified but not staged” and are ignored by git commit unless specific flags (like -a) are used. This tests the candidate’s understanding of the separation between Working Directory and Index.   

What is the primary function of git push?

A. To save changes to the local staging area. B. To download the latest version of the code from GitHub. C. To upload local repository content (commits) to a remote repository. D. To merge two local branches together.

Correct Answer: C. Push transfers the commit objects and updates the refs on the remote server.

Technically, what is a "Branch" in Git?

A. A separate directory on the disk containing a full copy of the project files. B. A lightweight, movable pointer to a specific commit hash. C. A permanent link to the remote server. D. A snapshot of the code at a specific point in time that cannot be changed.

Correct Answer: B. A branch is just a reference (a text file containing a 40-character SHA-1 hash). This is why creating branches in Git is near-instant, regardless of project size.

Why is git revert preferred over git reset for branches that have already been pushed to a shared remote?

A. git revert runs faster. B. git reset cannot work on remote branches. C. git revert creates a new commit that creates an inverse of the changes, preserving history, whereas git reset rewrites history, causing conflicts for other team members. D. git revert automatically fixes syntax errors.

Correct Answer: C. “Never rewrite public history.” git revert is a “forward-moving” undo operation safe for collaboration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment