Front End interview questions


What is semantic HTML, and why is it important?

Semantic HTML refers to using HTML tags that convey meaning about the content, rather than just presenting it. This practice is important because it improves accessibility, search engine optimization, and code maintainability. Examples include using '<header>', '<footer>', '<article>', and '<section>' instead of generic '<div>' elements.

What is the difference between HTML and XHTML?

HTML (Hypertext Markup Language) and XHTML (Extensible Hypertext Markup Language) are both markup languages used to create web pages, but they differ in their syntax and rules.

Aspect HTML XHTML
Syntax HTML syntax is more forgiving and allows for more flexibility, such as optional closing tags and lowercase tag names XHTML syntax is stricter and requires well-formed XML syntax, including properly nested elements, lowercase tag names, and self-closing tags
Tag Names Tag names are case-insensitive and can be written in uppercase, lowercase, or a mix of both Tag names must be written in lowercase
Attribute Values Attribute values do not require quotes and can be written without quotes, single quotes, or double quotes Attribute values must be enclosed in quotes (single or double)
Empty Elements Empty elements can be written without a closing slash (e.g., <br>, <img>) Empty elements must be written with a closing slash (e.g., <br />, <img />)
Document Structure HTML documents do not require a specific document structure and can have optional elements such as the <html>, <head>, and <body> tags XHTML documents must follow a strict XML document structure, including a single root element and properly nested elements
Error Handling HTML parsers are more forgiving and can handle syntax errors more leniently XHTML parsers are stricter and may produce errors or fail to render if the document is not well-formed XML
Browser Support Widely supported by web browsers and used for most web pages Less commonly used due to its stricter syntax requirements and compatibility issues with older web browsers

How can you embed a video in an HTML document?

You can embed a video in an HTML document using the ‘<video>‘ element. You specify the source of the video using the ‘src’ attribute, and you can also include fallback content for browsers that do not support the ‘<video>‘ element by placing content between the opening and closing tags.

<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

What is the purpose of the ‘ DOCTYPE’ declaration in HTML?

The ‘doctype’ declaration specifies the document type and version of HTML used in a web page. It helps the browser to render the page correctly by defining the rules that the markup language must follow.

Explain the difference between ‘<div>‘ and ‘<span>‘ tags.

The <div> and <span> tags are both HTML elements used for grouping and styling content, but they have different default behaviors and are typically used in different contexts:

Aspect <div> <span>
Type Block-level element Inline-level element
Usage Used for grouping and dividing content into sections Used for applying styles or grouping inline elements
Default Display Renders as a block with line breaks before and after Renders inline without line breaks
Width Takes up the full width available in its parent container Takes up only the width required by its content
Layout Often used for layout purposes, creating sections of content Typically used for applying styles or grouping inline elements
Example <div>Content here</div> <span style="color: red;">Text</span>

What is the purpose of the ‘alt’ attribute in an ‘<img>‘ tag?

The ‘alt’ attribute provides alternative text for an image in case the image cannot be displayed. It is also used by screen readers to describe the content of the image to visually impaired users and by search engines for indexing purposes.

What is the difference between an inline element and a block-level element?

Some key difference between inline elements and block-level elements:

Aspect Inline Elements Block-Level Elements
Display Type Renders inline Renders as block
Line Break Does not start on a new line and does not force line breaks before or after Starts on a new line and forces line breaks before and after
Width and Height Ignores width and height properties Respect width and height properties
Margin and Padding Only horizontal margins and paddings are respected Respects both horizontal and vertical margins and paddings
Usage Typically used for styling small elements within a line of text, like emphasizing text or adding links Used for larger structural elements, such as sections of content, paragraphs, headings, etc.

What are some common HTML attributes, and what are they used for?

HTML attributes provide additional information about elements. Common attributes include:

  • 'class': Assigns a class name for styling and scripting.
  • 'id': Gives a unique identifier to an element.
  • 'href': Specifies the URL for a hyperlink.
  • 'src': Defines the source file for media elements like images and videos.

How do you create a hyperlink in HTML?

To create a hyperlink, use the '<a>' tag with the 'href' attribute specifying the URL. Example: '<a href="https://www.example.com">Click here</a>'.

What is the 'DOCTYPE' declaration, and why is it important?

The 'DOCTYPE' declaration tells the browser which version of HTML is being used, allowing it to render the page correctly. For example, '<!DOCTYPE html>' indicates HTML5, ensuring compatibility with modern standards.

How do you add comments to HTML, and why might you use them?

Comments in HTML are added using '<!-- comment text -->'. They are used to leave notes for other developers or to describe sections of code for better maintainability without affecting the webpage's display.

What is the role of meta tags in HTML?

Meta tags provide metadata about the webpage, including information for search engines, character set specification, viewport settings, and more. For example, '<meta charset="UTF-8">' specifies the character encoding, while '<meta name="description" content="A brief description of the page">' provides information for search engines.

How do you embed an image in HTML?

To embed an image, use the '<img>' tag with the 'src' attribute specifying the image source and the 'alt' attribute providing alternative text for accessibility. Example: '<img src="image.jpg" alt="Description of the image">'.

What is the purpose of the `alt` attribute in the '<img>' tag?

The 'alt' attribute provides alternative text for images. It's crucial for accessibility, allowing screen readers to describe the image to visually impaired users, and it's also used when an image fails to load, providing context to users.

How do you create a table in HTML?

A table is created using the '<table>' tag, with rows defined by '<tr>', table headers by '<th>', and table data by '<td>'.

<table>
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
  </tr>
  <tr>
    <td>Data 1</td>
    <td>Data 2</td>
  </tr>
</table>

How do you create a form in HTML?

Forms are created using the '<form>' tag, with various input fields like text boxes, checkboxes, radio buttons, and submit buttons.

<form action="/submit" method="post">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <input type="submit" value="Submit">
</form>

What are some common input types in HTML, and why are they useful?

Common input types include:

  • text: For text input.
  • password: For hidden text input.
  • email: For email addresses, with built-in validation.
  • number: For numeric input, allowing additional controls like spin buttons.
  • date: For date selection, often with a calendar interface.
  • submit: For submitting the form.

These input types offer varying user interfaces and built-in validation, enhancing the form experience.

What is a responsive web design, and how does it relate to HTML?

Responsive web design ensures that webpages adapt to different screen sizes and devices. This often involves using semantic HTML, media queries, and a mobile-first approach to ensure content is accessible and usable on various devices.

What is the difference between an ordered list and an unordered list in HTML?

Some key difference between list and an unordered list in HTML are:

Aspect Ordered List (<ol>) Unordered List (<ul>)
Appearance Renders a list with items displayed in sequential order, typically with numbers or letters as markers Renders a list with items displayed in no particular order, typically with bullets or other symbols as markers
Default Marker Default markers are numerical (1, 2, 3, ...) or alphabetical (a, b, c, ...) Default markers are typically bullets (•), circles (◦), or squares (▪)
Usage Used when the order of items is important or meaningful, such as steps in a process or ranked items Used when the order of items is not significant or when presenting a collection of related items

How do you include external CSS and JavaScript files in HTML?

To include external CSS, use the '<link>' tag in the '<head>', specifying the file's location with the `href` attribute.

<link rel="stylesheet" href="styles.css">

For JavaScript, use the '<script>' tag, specifying the source with the 'src' attribute.

<script src="script.js"></script>

What is the difference between `<iframe>` and `<frame>` in HTML?

The <iframe> and <frame> elements are both used to embed content from one HTML document within another, but they have different purposes and behaviors:

Aspect <iframe> <frame>
Purpose Used to embed content from another document within the current document Used to divide the browser window into multiple frames or panes, each displaying a separate document
Document Structure Creates an inline frame within the current document, allowing for seamless embedding of external content Defines a frame within a frameset, splitting the browser window into separate regions
Content Handling Renders the content of the embedded document independently of the surrounding content Renders the content of the embedded document within a designated frame region
Browser Support Widely supported by modern web browsers Deprecated in HTML5 and not supported by most modern web browsers

What are some HTML5-specific features, and how do they improve web development?

HTML5 introduced several new features, including:

  • Semantic elements like '<header>', '<footer>', '<article>', and '<section>'.
  • Media elements like '<audio>' and '<video>', allowing native multimedia support without plugins.
  • The '<canvas>' element for drawing and animations.
  • Improved form controls with new input types like 'email', 'number', and 'date'.
  • The 'contenteditable' attribute, allowing inline editing of elements.

These features enhance accessibility, multimedia capabilities, and overall flexibility in web development.

What is accessibility in the context of HTML, and how can it be achieved?

Accessibility in HTML involves designing and structuring webpages to be usable by everyone, including people with disabilities. It can be achieved through:

  • Using semantic HTML to convey structure and meaning.
  • Providing alternative text for images with the 'alt' attribute.
  • Ensuring proper keyboard navigation and focus management.
  • Using ARIA (Accessible Rich Internet Applications) attributes to improve screen reader compatibility.
  • Implementing responsive design to ensure content is usable across devices.

What is CSS, and why is it used? 

CSS (Cascading Style Sheets) is a language used to style and layout web pages. It allows developers to separate content from presentation, providing a flexible and scalable approach to designing websites. It is used to control aspects like colors, fonts, spacing, layout, and responsiveness.

What are the different types of CSS selectors?

CSS has various selectors, including:

  • Element selector: Targets HTML tags (e.g., 'h1', 'p').
  • Class selector: Targets elements with a specific class (e.g., '.my-class').
  • ID selector: Targets an element with a unique ID (e.g., '#my-id').
  • Attribute selector: Targets elements with specific attributes (e.g., '[type="text"]').
  • Pseudo-classes: Targets elements in a specific state (e.g., ':hover', ':first-child').
  • Pseudo-elements: Targets specific parts of elements (e.g., '::before', '::after').

Explain the box model in CSS.   

The CSS box model describes the layout and sizing of elements. It consists of four parts:

  • Content: The text or other content within an element.
  • Padding: The space between the content and the border.
  • Border: The visible boundary around the element.
  • Margin: The space outside the border, separating elements.

What is the difference between 'display: inline', 'display: block', and 'display: inline-block'?  

The CSS display property controls how an HTML element is displayed on a web page. Here's a comparison between display: inline, display: block, and display: inline-block:

Property Value display: inline display: block display: inline-block
Type Renders as an inline-level element Renders as a block-level element Renders as an inline-level block container
Line Break Does not start on a new line Starts on a new line Does not start on a new line but respects block-level properties
Width/Height Does not respect width/height properties Respects width/height properties Respects width/height properties
Margin/Padding Does not respect margin/padding properties Respects margin/padding properties Respects margin/padding properties
Full Width Takes up only the space required by its content Takes up the full width available in its parent container Takes up only the space required by its content but allows setting block-level properties

What are the advantages of using CSS preprocessors?

CSS preprocessors, like SASS or LESS, offer several benefits:

  • Variables: Reuse values like colors and font sizes.
  • Nesting: Organize styles in a nested hierarchy.
  • Mixins: Create reusable blocks of code.
  • Inheritance: Extend existing styles.

What is a CSS reset, and why is it important?   

A CSS reset is a set of styles designed to override browser default styles. Different browsers may apply varying default styles to HTML elements, leading to inconsistencies. By using a CSS reset (like Normalize.css), you can create a consistent starting point across different browsers, making cross-browser styling easier.

How do you implement responsive design in CSS?

Responsive design adapts the layout to different screen sizes and devices. Techniques for responsive design include:

  • Media queries: Adjust styles based on screen size, orientation, etc. (e.g., '@media (max-width: 600px) { ... }').
  • Flexible grid systems: Use frameworks like Bootstrap or CSS Grid to create adaptable layouts.
  • Flexible images and media: Ensure images and media scale proportionally (e.g., 'img { max-width: 100%; height: auto; }').
  • Relative units: Use relative units like 'em', 'rem', or '%' instead of absolute units like 'px'.

What is Flexbox, and how is it different from traditional layout techniques?

Flexbox (Flexible Box Layout) is a layout model designed to simplify complex layouts. It allows you to align, justify, and order elements flexibly within a container. Flexbox provides a more straightforward way to create responsive layouts compared to traditional techniques like floats or inline-block. With Flexbox, you can control the direction, alignment, and distribution of space among items in a container.

Explain the differences between 'position: static', 'position: relative', 'position: absolute', 'position: fixed', and 'position: sticky'.

  • 'position: static': Default position; elements are positioned according to the normal flow.
  • 'position: relative': The element is positioned relative to its normal position, allowing for offset with 'top', 'right', 'bottom', or 'left'.
  • 'position: absolute': The element is positioned relative to its nearest positioned ancestor (not 'static'). It can be positioned anywhere within that context.
  • 'position: fixed': The element is positioned relative to the viewport, meaning it stays in the same place when scrolling.
  • 'position: sticky': A hybrid between relative and fixed. The element behaves like relative until it reaches a certain position, after which it sticks to that position while scrolling.

What is CSS Grid, and how does it differ from Flexbox?    

CSS Grid is a layout system designed to create complex grid-based layouts. It allows you to create multi-dimensional layouts with rows and columns. CSS Grid differs from Flexbox in that it provides a more robust way to create 2D layouts, whereas Flexbox is more suitable for 1D layouts (either row-based or column-based). Grid offers more explicit control over both rows and columns, while Flexbox focuses more on alignment and distribution within a single axis.

Explain specificity in CSS.    

Specificity determines which CSS rules apply when there are conflicting styles. It is calculated based on a specific scoring system:

  • Inline styles: The highest specificity (e.g., '<div style="color: red;">').
  • ID selectors: Have higher specificity than classes or elements (e.g., '#my-id').
  • Class and attribute selectors: Have medium specificity (e.g., '.my-class', '[type="text"]').
  • Element and pseudo-element selectors: Have the lowest specificity (e.g., 'p', '::before').

What is the cascade in CSS?

The cascade determines how styles are applied when multiple CSS rules affect the same element. It involves:

  • Inheritance: Styles can be inherited from parent elements.
  • Specificity: More specific rules override less specific ones.
  • Source order: If specificity is the same, the last rule in the CSS is applied.

The cascade allows for complex style interactions, making it possible to override or redefine styles at various levels.

Explain how 'z-index' works in CSS.

'z-index' controls the stacking order of positioned elements ('position: relative', 'absolute', 'fixed', 'sticky'). A higher 'z-index' value places the element above those with lower values. Elements with the same 'z-index' are stacked according to source order. To use 'z-index', the element must have a defined position property. Misunderstanding 'z-index' often leads to stacking issues, so understanding the stacking context and positioning is crucial.

What are CSS pseudo-classes and pseudo-elements?

Pseudo-classes and pseudo-elements allow you to apply styles to specific states or parts of elements:

  • Pseudo-classes: Apply styles based on an element's state (e.g., ':hover', ':active', ':nth-child(n)'). They are used to style elements based on user interaction or specific conditions.
  • Pseudo-elements: Style a specific part of an element (e.g., '::before', '::after', '::first-line'). These can be used to insert additional content or style certain sections of an element.

What are some common accessibility considerations in CSS?

Accessibility in CSS involves making sure that styles do not impede users with disabilities. Key considerations include:

  • Color contrast: Ensure sufficient contrast between text and background (following Web Content Accessibility Guidelines, or WCAG).
  • Focus indicators: Maintain visible focus indicators for keyboard users.
  • Avoiding text-only cues: Do not rely solely on color or styling to convey information.
  • Media responsiveness: Ensure responsive design works for assistive technologies.
  • Semantic HTML: Use appropriate HTML elements, allowing CSS to enhance, not replace, semantic structure.

What is the '@font-face' rule in CSS?

The '@font-face' rule allows you to include custom fonts in a CSS file, enabling the use of fonts not natively available in the browser. This rule specifies font file sources, fallback fonts, and other font properties. It’s crucial to ensure proper licensing when using custom fonts and to include font formats compatible with different browsers to ensure cross-browser support.

What is the difference between 'rem' and 'em' units in CSS?

Both rem and em are relative length units in CSS, but they have different reference points. 

Unit rem (Root em) em (Element em)
Reference Point Relative to the font size of the root element (usually the <html> element) Relative to the font size of the current element
Inheritance Inherits the font size of the root element, making it unaffected by nested font size changes Inherits the font size of its parent element, making it affected by nested font size changes
Predictability Provides more predictable and consistent results, especially in complex layouts May lead to cascading font size changes in nested elements, making it less predictable

What are some common methods to center elements in CSS?

Centering elements in CSS can be achieved in various ways, depending on the context:

Horizontal centering:

  • Use 'text-align: center' for inline elements.
  • Use 'margin: 0 auto' for block elements with a defined width.

Vertical centering:

  • Use 'flexbox' with 'align-items: center'.
  • Use 'grid' with 'align-items: center'.
  • Use relative and absolute positioning with translation ('transform: translate(-50%, -50%)').

Complete centering (both horizontal and vertical):

  • Use 'flexbox' with 'justify-content: center' and 'align-items: center'.
  • Use 'grid' with 'justify-content: center' and 'align-items: center'.

What is a media query in CSS?

A media query allows you to apply different CSS rules based on the characteristics of the user's device or browser environment. This includes screen size, resolution, orientation, etc. Media queries are fundamental to responsive design, allowing you to create layouts that adapt to different screen sizes. The most common media query uses conditions like 'min-width', 'max-width', and 'orientation' to apply specific styles.

What is the '@keyframes' rule in CSS?

The '@keyframes' rule is used to create animations in CSS. It allows you to define keyframes, representing the start, end, and intermediate stages of an animation. You can then use the 'animation' property to apply these keyframes to an element, specifying properties like duration, timing function, and delay. This enables you to create complex animations and transitions without relying on JavaScript.

What are the different data types in JavaScript?

JavaScript has primitive data types including 'undefined', 'null', 'boolean', 'number', 'string', 'bigint', and 'symbol'. It also has complex data types like 'object' and 'array'.

What is a closure in JavaScript?

A closure occurs when a function retains access to variables from its outer scope even after the outer function has finished executing. This is used for encapsulation and creating private variables.

function outerFunction() {
  const outerVariable = "Hello from outer function";

  function innerFunction() {
    console.log(outerVariable); // Accessing outer variable inside inner function
  }

  return innerFunction; // Returning the inner function
}

const closureExample = outerFunction();
closureExample(); // Output: Hello from outer function

How does the 'this' keyword work in JavaScript?

The 'this' keyword refers to the context in which a function is executed. In global scope, it refers to the global object (like 'window' in browsers). In object methods, it refers to the object itself. In arrow functions, 'this' is inherited from the parent scope.

Explain event bubbling and event capturing in JavaScript.

Event bubbling is when an event propagates from the innermost element to the outermost. Event capturing is the reverse, from the outermost to the innermost. Event listeners can be set to use either method.

What is a promise in JavaScript?

A promise represents an asynchronous operation that may complete successfully ('resolve') or fail ('reject'). It allows chaining of '.then()' for success and '.catch()' for errors, promoting cleaner asynchronous code.

What is the difference between synchronous and asynchronous code in JavaScript?

In JavaScript, synchronous and asynchronous code execution models differ in how they handle tasks and their order of execution:

Aspect Synchronous Code Asynchronous Code
Execution Flow Sequential execution, blocking subsequent tasks Non-sequential execution, tasks run concurrently
Blocking Blocks subsequent code execution until current task finishes Does not block subsequent code execution, allowing concurrency
Order Maintains strict order of execution Order of execution may vary depending on task completion
Handling Simple to understand and debug Requires understanding of callback, promise, or async/await mechanisms
Use Cases Suitable for tasks where order of execution is critical, and dependencies must be maintained Ideal for I/O-bound tasks, network requests, time-consuming operations
Example Reading files synchronously, performing mathematical calculations Making HTTP requests, reading files asynchronously, handling user input asynchronously

What is a callback function?

A callback function is a function passed as an argument to another function, typically to be executed later or upon a specific condition or event, allowing asynchronous operations and event-driven programming.

Describe the concept of hoisting in JavaScript.

Hoisting is when variable and function declarations are moved to the top of their scope during compilation. This allows functions and 'var' variables to be used before they are declared in code. 'let' and 'const' do not hoist in the same way.

Explain the difference between '==' and '===' in JavaScript.

Some key difference between the loose equality operator (==) and the strict equality operator (===) in JavaScript:

Operator Description Example Explanation
== Loose equality operator x == y Compares the values of two operands after performing type conversion if necessary. Returns true if the values are equal, ignoring their types.
=== Strict equality operator x === y Compares the values of two operands without type conversion. Returns true only if the values are equal and have the same data type.

What is an Immediately Invoked Function Expression (IIFE)?

An IIFE is a function that is defined and executed immediately. It is commonly used to create a local scope to avoid polluting the global namespace, like this: '(function() { /* code */ })();'.

How do you create a deep copy of an object in JavaScript?

A deep copy can be created using methods like 'JSON.parse(JSON.stringify(obj))', or using recursive functions. Libraries like lodash provide a deep copy method that handles complex cases like circular references.

const originalObject = {
  name: 'Baibhav',
  address: {
    city: 'Noida',
    state: 'IN'
  }
};

// Deep copy using JSON methods
const deepCopy = JSON.parse(JSON.stringify(originalObject));

deepCopy.address.city = 'Grater Noida'; // Modifying the deep copy
console.log(originalObject.address.city); // Output: Noida
console.log(deepCopy.address.city); // Output: Grater Noida

What is the 'async/await' syntax in JavaScript?

'async/await' is a syntax that allows writing asynchronous code in a synchronous style. Functions declared with 'async' return a promise, and 'await' can be used to wait for a promise to resolve or reject.

What is a module pattern in JavaScript?

The module pattern is a way to encapsulate code and provide public and private access to parts of a script. It often uses closures to create private variables and functions, exposing only the public API.

What is a prototype in JavaScript?

A prototype is an object from which other objects inherit properties and methods. All JavaScript objects have a prototype, allowing for shared methods and inheritance without duplication of code.

Describe the 'spread' and 'rest' operators in JavaScript.

The 'spread' operator ('...') allows expanding iterable elements like arrays or objects into individual elements, useful for array or object concatenation. The 'rest' operator, also '...', collects a variable number of arguments into an array, useful in functions for handling flexible arguments.

What is the difference between 'Array.forEach' and 'Array.map'?

Both Array.forEach() and Array.map() are methods in JavaScript used to iterate over arrays, but they have different purposes and behaviors:

Method Array.forEach() Array.map()
Purpose Executes a provided function once for each array element Calls a provided function on every element in the array and returns a new array containing the results
Return Value Does not return a value (returns undefined) Returns a new array containing the results of calling the provided function on each element
Modifies Original Does not modify the original array Does not modify the original array
Side Effects Performs a side effect on each element (e.g., logging, modifying original array) Does not perform side effects; purely functional approach
Use Case Use when you want to perform an action or operation on each array element without necessarily transforming them Use when you want to transform each array element and generate a new array with the transformed values

Explain the concept of a 'Promise.all' in JavaScript.

'Promise.all' takes an array of promises and returns a new promise that resolves when all input promises have resolved, or rejects when any one of them rejects. It's useful for waiting for multiple asynchronous tasks to complete.

What is the event loop in JavaScript?

The event loop is a mechanism that handles asynchronous code in JavaScript. It allows JavaScript to process events and execute code asynchronously while maintaining single-threaded execution, managing tasks, and microtasks in a non-blocking manner.

console.log('Start'); // This will always execute first

setTimeout(() => {
  console.log('Inside setTimeout'); // Will execute after the stack is cleared
}, 0);

console.log('End'); // This will execute before setTimeout due to the event loop

Explain the concept of "strict mode" in JavaScript.

"Strict mode" is a way to enforce stricter parsing and error handling in JavaScript. It catches common mistakes and unsafe actions, such as assigning to undeclared variables or using reserved words as variable names. You enable it with '"use strict";' at the top of a script or function.

What is React, and why would you use it?

React is a JavaScript library developed by Facebook for building user interfaces, particularly single-page applications. It is designed to make building complex UIs with reusable components easier. Its virtual DOM implementation provides high performance, and React's component-based architecture promotes code reusability and easier maintenance.

What is JSX, and how does it differ from HTML?

JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML but is used to describe the UI components in React. Unlike HTML, JSX can embed JavaScript expressions within curly braces '{}'. JSX is compiled into regular JavaScript using tools like Babel.

Explain the component lifecycle in React.    

React has several lifecycle methods that allow you to manage component creation, updates, and destruction. Common lifecycle phases are:

  • Mounting: When a component is initialized and inserted into the DOM ('componentDidMount').
  • Updating: When a component is re-rendered due to changes in props or state ('componentDidUpdate').
  • Unmounting: When a component is removed from the DOM ('componentWillUnmount').

What is the difference between a functional component and a class component?

Functional components and class components are two types of components used in React for building user interfaces, but they differ in their syntax and usage:

Aspect Functional Components Class Components
Syntax Defined as JavaScript functions Defined as ES6 classes
State Cannot hold state or use lifecycle methods Can hold state and use lifecycle methods
Lifecycle Methods Cannot use lifecycle methods Can use lifecycle methods such as componentDidMount, render, etc.
State Management Use React Hooks for state management (useState, useEffect, etc.) Use this.state and this.setState for state management
Code Structure Simpler and more concise syntax More verbose syntax, especially for defining state and lifecycle methods
Performance Typically have better performance due to fewer optimizations needed May have slightly worse performance due to optimizations needed for class components
Hooks Support Fully support React Hooks Do not support React Hooks

What are React Hooks, and why were they introduced?

React Hooks are functions that allow you to use state and lifecycle features in functional components. Introduced in React 1. 6.8, they enable developers to write cleaner code without needing class components. Popular hooks include 'useState', 'useEffect', 'useContext', and 'useRef'.

How does the virtual DOM work in React?

The virtual DOM is an abstraction layer that represents the actual DOM in memory. React compares the virtual DOM with a snapshot of the actual DOM (a process called "reconciliation") to determine which parts of the real DOM need updating. This results in fewer direct DOM manipulations, improving performance.

What is the use of 'useEffect' in React, and how does it differ from lifecycle methods in class components?

'useEffect' is a hook that performs side effects in functional components. It combines the functionality of lifecycle methods like 'componentDidMount', 'componentDidUpdate', and 'componentWillUnmount'. It takes a function to run and an optional dependency array to control when the effect should run.

What is the context API in React, and when would you use it?

The context API allows components to share global data without passing props through every component in the tree. It helps avoid "prop drilling" in deeply nested component structures. You'd use it for themes, user authentication, or other global data.

Explain state management in React. What options are available for managing complex states?

State management in React involves tracking and updating the component's data. React's built-in 'useState' hook is suitable for local component state. For complex state management across multiple components, tools like Redux, MobX, or Context API are used. Redux, a popular option, centralizes state management with actions and reducers.

What is PropTypes, and how does it improve React component development?

PropTypes is a way to define expected types for component props in React. It helps catch type-related bugs during development by providing warnings if a component receives incorrect prop types. It improves component documentation and enforces type safety.

How do you handle events in React?

React handles events with a syntax similar to HTML but uses camelCase for event names (e.g., 'onClick' instead of 'onclick'). Event handlers are typically defined as functions and passed to components as props.

What is the purpose of 'key' in React lists, and why is it important?

In React, the 'key' prop is used to identify elements in a list. It helps React determine which items have changed, allowing it to efficiently re-render the UI. Without unique keys, React cannot properly reconcile list items, leading to unexpected behavior.

What is Higher-Order Component (HOC), and when would you use it?

A Higher-Order Component (HOC) is a pattern in React where a function takes a component and returns a new component with additional functionality. It's used to reuse component logic and abstract common behaviors. While hooks have become more common, HOCs are still used in some cases.

Explain the concept of controlled and uncontrolled components in React.

Controlled components have their state controlled by React, usually through props and state updates. In contrast, uncontrolled components maintain their own internal state, often using refs to interact with the DOM. Controlled components are preferred for form handling because they offer more predictable behavior.

How would you optimize a React application for performance?

To optimize React applications for performance, consider the following:

  • Use React.memo: Memoize functional components to prevent unnecessary re-renders.
  • Use 'React.useCallback' and 'React.useMemo': Cache functions and computations to reduce re-renders.
  • Code-splitting: Use dynamic imports to split the code into smaller chunks, reducing initial load time.
  • Virtualization: Use libraries like 'react-window' or 'react-virtualized' for efficient rendering of large lists.
  • Optimize images: Compress images and use responsive formats.
  • Minimize direct DOM manipulations: Use React's virtual DOM for updates.

What is Angular and why would you use it?

Angular is a TypeScript-based open-source framework primarily maintained by Google. It's used for building web applications, particularly single-page applications (SPAs), because it offers features like data binding, dependency injection, and modular development that enhance productivity and maintainability.

What are the key features of Angular?

Angular offers features like two-way data binding, MVC architecture, dependency injection, directives, services, routing, and robust community support.

Explain the difference between AngularJS and Angular.

AngularJS and Angular are both web application development frameworks.

Aspect AngularJS Angular
Framework AngularJS is a JavaScript-based framework Angular is a TypeScript-based framework
Architecture Follows the MVC (Model-View-Controller) architecture Follows the component-based architecture
Language Written in JavaScript Written in TypeScript
Data Binding Uses two-way data binding (automatically synchronizes data between model and view) Uses one-way data binding by default (improves performance and simplifies debugging)
Performance Performance may degrade with large applications due to two-way data binding and digest cycle Performance is improved with ahead-of-time (AOT) compilation, improved rendering engine, and optimized change detection
Dependency Injection Supports dependency injection Supports dependency injection
Mobile Development Limited support for mobile development Full support for mobile development (with Angular Mobile Toolkit)
Tooling Limited tooling and ecosystem compared to Angular Robust tooling and ecosystem (Angular CLI, Angular Material, etc.)
Learning Curve Steeper learning curve due to complex concepts Moderate learning curve, especially for developers familiar with modern web development
Backward Compatibility Not fully backward compatible with Angular Not fully backward compatible with AngularJS

What is TypeScript, and why does Angular use it?

TypeScript is a superset of JavaScript that adds optional static typing and other features to the language. Angular uses TypeScript because it offers advantages like enhanced code maintainability, better IDE support, and improved error checking during development.

What are components in Angular?

Components are the building blocks of Angular applications. They consist of a TypeScript class with an associated HTML template and optional CSS styles. Components encapsulate the behavior and presentation of a part of the UI.

Explain Angular data binding.

Angular data binding is a mechanism for synchronizing the data between the model and the view components of an application. It includes one-way and two-way data binding. One-way binding updates the view when the model changes, while two-way binding updates both the view and the model when either changes.

What are directives in Angular?

Directives are markers on a DOM element that tell Angular to do something with that element. They can be structural, altering the layout of the DOM, or attribute-based, modifying the behavior or appearance of the element.

What is dependency injection in Angular?

Dependency injection is a design pattern in which components receive their dependencies from an external source rather than creating them directly. Angular's dependency injection system provides a way to inject dependencies into components, making them more modular, testable, and reusable.

How does routing work in Angular?

Angular's routing module allows you to build SPAs with multiple views and navigate between them by changing the URL in the browser's address bar. It maps URLs to components, enabling the loading of different components based on the URL.

What is Angular CLI, and how do you use it?

Angular CLI (Command Line Interface) is a powerful tool for initializing, developing, and maintaining Angular applications. It provides commands for generating components, services, modules, and other artifacts, as well as for building and serving the application.

Explain Angular services and their importance.

Angular services are singleton objects that are instantiated only once during the lifetime of an application. They provide a way to share data and functionality across components. Services are commonly used for tasks like fetching data from a server, logging, or managing application state.

How do you handle HTTP requests in Angular?

Angular provides the HttpClient module for making HTTP requests to a server. You can use methods like get(), post(), put(), and delete() to perform various types of HTTP operations. Additionally, you can use interceptors to intercept and modify HTTP requests and responses.

What is Angular's modular architecture?

Angular applications are composed of modules, which are collections of components, directives, pipes, and services that are related to each other. Modules help organize the application into cohesive units and promote code reusability and maintainability.

What is Angular's testing infrastructure, and how do you write unit tests for Angular components? 

Angular provides a testing infrastructure based on Jasmine and Karma for writing unit tests for components, services, and other Angular artifacts. You can use TestBed to configure and compile Angular components for testing, and write test cases to verify their behavior and interactions.

How do you optimize the performance of Angular applications? 

Performance optimization in Angular involves various techniques such as lazy loading modules, preloading modules, optimizing change detection, using trackBy with ngFor, minimizing the size of bundles through tree shaking and code splitting, and optimizing the rendering performance of components.

What is Vue.js and why is it used?

Vue.js is a progressive JavaScript framework used for building user interfaces and single-page applications. It is designed to be incrementally adaptable, easy to learn, and focuses on the view layer of an application. Vue's flexibility allows developers to create complex applications or integrate with other frameworks as needed.

Explain the Vue instance and its lifecycle hooks.

A Vue instance is the core of any Vue application. It binds data and templates, enabling reactivity and rendering. Lifecycle hooks are functions that get called at different stages of the instance's lifecycle. Common hooks include 'created', 'mounted', 'updated', and 'destroyed', allowing developers to insert custom behavior at these points.

How does Vue.js handle reactivity?

Vue uses a reactivity system based on getters and setters. When a property is accessed or changed, Vue detects these changes and automatically updates the relevant parts of the DOM. This reactivity is achieved through Vue's "Observer" pattern and dependency tracking.

What are Vue components, and why are they important?

Vue components are reusable building blocks in a Vue application. They encapsulate a specific part of the UI and its related logic. Components are important because they promote reusability, maintainability, and modularity, allowing developers to create complex applications more efficiently.

Describe the Vue CLI and its features.

The Vue CLI (Command Line Interface) is a tool for scaffolding and managing Vue.js projects. It provides features like project templates, plugins, build tools, and a development server. The CLI simplifies project setup, encourages best practices, and streamlines the development process.

How does Vue.js support two-way data binding?

Vue.js supports two-way data binding using the 'v-model' directive. It creates a synchronized link between a data property and an input element, allowing changes in either to be reflected in the other. This is particularly useful for form inputs and other interactive components.

What is Vue Router, and how does it work?

Vue Router is a routing library for Vue.js that enables navigation and routing within a Vue application. It allows developers to define routes, map them to components, and handle navigation. Vue Router supports nested routes, named views, and navigation guards, providing a robust solution for single-page applications.

Explain Vuex and its use cases.

Vuex is a state management library for Vue.js. It provides a centralized store for managing the state across components, facilitating predictable state transitions and enabling advanced features like time-travel debugging. Vuex is useful for complex applications with shared state and complex interactions between components.

What are Vue directives, and can you create custom directives?

Vue directives are special tokens in the template that apply reactive behavior to the DOM. Examples include 'v-if', 'v-for', and 'v-bind'. You can create custom directives to add custom behavior to DOM elements. This allows developers to extend Vue's capabilities in specific ways.

How do you handle asynchronous operations in Vue.js?

Asynchronous operations in Vue.js are typically handled using JavaScript promises and async/await syntax. Vue also supports integrating with other libraries for managing async operations, like Axios for HTTP requests. Vue components often use lifecycle hooks or Vuex actions to handle async tasks and update the state accordingly.

What is server-side rendering (SSR) in Vue.js, and why would you use it?

Server-side rendering (SSR) in Vue.js refers to rendering the Vue components on the server before sending them to the client. This can improve performance, SEO, and initial load times, especially for content-heavy applications. SSR is often used in combination with frameworks like Nuxt.js to simplify implementation.

How do you test Vue.js components?

Testing Vue.js components can be done using tools like Vue Test Utils, Jest, and Cypress. Vue Test Utils allows developers to mount and interact with components in a controlled environment, while Jest is used for unit tests and Cypress for end-to-end tests. Testing strategies include unit tests, integration tests, and end-to-end tests to ensure application reliability.

What is Vue's "slot" system, and how does it work?

Vue's slot system allows components to accept and render content passed to them from their parent components. It supports basic slots, named slots, and scoped slots, enabling flexible component composition. Slots are useful for creating highly customizable components while maintaining structure and encapsulation.

What are Vue mixins, and when should you use them?

Vue mixins allow you to reuse code across components by merging common functionality into multiple components. They can contain data properties, computed properties, methods, lifecycle hooks, etc. Mixins are useful for sharing behavior among components, but should be used judiciously to avoid code complexity and conflicts.

Describe how you would optimize a Vue.js application for performance.

Optimizing a Vue.js application involves various strategies, such as:

  • Using 'v-if' instead of 'v-show' for conditionally rendering large components.
  • Employing lazy loading and code splitting for large codebases to reduce initial load times.
  • Leveraging computed properties and watchers to minimize unnecessary re-renders.
  • Using 'key' attributes in 'v-for' loops to maintain list stability.
  • Utilizing Vuex for state management to reduce prop drilling and improve state management efficiency.
  • Implementing server-side rendering (SSR) or static site generation (SSG) to improve initial load times and SEO.

What are Vue transitions, and how do you use them to create animations?

Vue transitions are a way to apply CSS transitions and animations when elements enter or leave the DOM. Vue provides the `transition` and `transition-group` components to manage these effects. You can define CSS transitions using classes like `v-enter`, `v-enter-active`, `v-leave`, and `v-leave-active`, or use JavaScript hooks for more complex animations.

What is Nuxt.js, and how does it relate to Vue.js?

Nuxt.js is a framework built on top of Vue.js designed for server-side rendering (SSR), static site generation (SSG), and creating universal Vue applications. It abstracts away much of the complexity of setting up server-side rendering, provides routing and state management out of the box, and supports SEO optimization and code splitting. Nuxt.js is useful for creating high-performance Vue applications with minimal setup.

How do you implement authentication in a Vue.js application?

Implementing authentication in Vue.js typically involves integrating with an authentication provider (like Firebase, Auth0, or a custom backend) and managing authentication state in Vuex. You can use Vue Router navigation guards to protect routes, ensuring that only authenticated users can access certain parts of the application. Additionally, you may implement token-based authentication, storing tokens in localStorage or cookies for persistence.

Explain how Vue.js handles props and event communication between components.

Props are a way to pass data from a parent component to a child component in Vue.js. They allow for component composition and data encapsulation. Event communication, on the other hand, is used for child-to-parent communication. Child components can emit custom events using `this.$emit('eventName', data)`, which the parent can listen to using the `@eventName="handler"` syntax. This pattern promotes a clear and structured communication flow between components.

What is Vue 3, and what are its major improvements over Vue 2?

Vue 3 is the latest major version of Vue.js, with significant improvements over Vue 2. Some key enhancements include:

  • Composition API: A new way to organize component logic, providing better reusability and flexibility compared to the Options API.
  • Improved Performance: Vue 3 uses a more efficient rendering engine and optimized reactivity system.
  • Tree-shakable Architecture: This allows for smaller bundle sizes by including only the features used in the project.
  • Concurrent Rendering: Vue 3 supports concurrent rendering, improving responsiveness.
  • Custom Directives with Simplified Syntax: Vue 3 offers a more straightforward way to create custom directives.

What are the advantages of using jQuery?

  • Cross-browser compatibility: jQuery abstracts away browser-specific inconsistencies.
  • Conciseness: It requires fewer lines of code to achieve complex tasks.
  • Community support: A large community means extensive plugins and resources.
  • Built-in animations: jQuery has several animation utilities for dynamic interactions.
  • Easy integration with Ajax: jQuery provides a simplified API for Ajax requests.

How does jQuery differ from JavaScript?

jQuery is a library built on JavaScript. While JavaScript is a general-purpose programming language, jQuery provides a simplified, abstracted interface for common tasks like DOM manipulation, event handling, and Ajax interactions. It also addresses cross-browser compatibility issues, allowing developers to write consistent code across different browsers.

What is the significance of the '$' symbol in jQuery?

The '$' symbol is an alias for the 'jQuery' object, allowing concise access to jQuery functionalities. It is commonly used to represent a jQuery object or initiate jQuery operations.

How do you include jQuery in a web project?

There are several ways to include jQuery:

  • CDN (Content Delivery Network): Include a link to a hosted jQuery library (e.g., Google, Microsoft, or jQuery's own CDN).
  • Local file: Download jQuery and reference it in your HTML file.
  • Module bundlers: Use tools like Webpack or Rollup to bundle jQuery with other scripts.
<!-- Including jQuery via CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

What is the Document Ready event in jQuery, and why is it important?

The Document Ready event ensures that the DOM is fully loaded before executing jQuery code. It's crucial because manipulating the DOM before it's ready can lead to errors.

$(document).ready(function() {
  // Code to run when the DOM is ready
});

How do you select elements in jQuery?

jQuery uses CSS selectors to select elements. Common selection methods include:

  • By ID: '$('#elementId')'
  • By class: '$('.className')'
  • By tag name: '$('tagName')'
  • By attribute: '$('[attribute="value"]')'
  • Combined selectors: '$('#id .className')'

How do you handle events in jQuery?

jQuery provides a simple way to handle events using the '.on()' method. For example, to handle a click event:

$('#myButton').on('click', function() {
  alert('Button clicked!');
});

What is event delegation in jQuery?

Event delegation allows you to attach an event handler to a parent element, then handle events from its child elements. This is useful for dynamically added elements, as it reduces the need for reattaching event handlers.

// Delegating a click event to a parent
$('#parentElement').on('click', '.childElement', function() {
  console.log('Child element clicked!');
});

What are some common jQuery methods for manipulating the DOM?

Here are some common DOM manipulation methods in jQuery:

  • Add elements: '.append()', '.prepend()', '.after()', '.before()'
  • Remove elements: '.remove()', '.empty()'
  • Modify content: '.html()', '.text()'
  • Modify attributes: '.attr()', '.removeAttr()', '.addClass()', '.removeClass()'
  • Modify styles: '.css()'

How do you perform animations in jQuery?

jQuery provides several built-in methods for animations, including:

  • Show/hide: '.show()', '.hide()', '.toggle()'
  • Slide animations: '.slideDown()', '.slideUp()', '.slideToggle()'
  • Fade animations: '.fadeIn()', '.fadeOut()', '.fadeToggle()'
  • Custom animations: '.animate(properties, [duration], [easing], [callback])'
// Example of a slide-down animation
$('#myElement').slideDown(500); // 500 ms duration

What is the purpose of the '.each()' method in jQuery?

The '.each()' method iterates over a jQuery collection, allowing you to execute a function on each matched element. This is useful for batch operations or applying similar logic to multiple elements.

$('ul li').each(function(index) {
  $(this).text('Item ' + (index + 1));
});

What is chaining in jQuery, and why is it useful?

Chaining allows you to call multiple jQuery methods on the same object in sequence. This is useful for writing concise code and reducing redundant variable assignments.

$('#myElement')
  .addClass('highlight')
  .text('Hello, jQuery!')
  .fadeIn(500);

How do you make an Ajax request with jQuery?

jQuery provides several methods for making Ajax requests, such as '.ajax()', '.get()', and '.post()'. Here's an example of an Ajax GET request:

$.ajax({
  url: 'https://api.example.com/data',
  method: 'GET',
  success: function(response) {
    console.log('Data retrieved:', response);
  },
  error: function(xhr, status, error) {
    console.error('Error:', status, error);
  }
});

What is JSONP, and how does jQuery support it?

JSONP (JSON with Padding) is a technique for making cross-domain Ajax requests using '<script>' tags. jQuery supports JSONP by setting the 'dataType' property to '"jsonp"' in an Ajax request.

$.ajax({
  url: 'https://api.example.com/data',
  dataType: 'jsonp',
  success: function(response) {
    console.log('Data received:', response);
  }
});

What is the purpose of the '.data()' method in jQuery?

The '.data()' method allows you to attach custom data to DOM elements. This data can be retrieved later or used in event handlers and other operations.

$('#myElement').data('info', { key: 'value' });

// Retrieving data
var data = $('#myElement').data('info');
console.log(data.key); // Output: "value"

What is the difference between '.prop()' and '.attr()' in jQuery?

In jQuery, both .prop() and .attr() are methods used to access and manipulate attributes of HTML elements.

Method Purpose Behavior Examples
.prop() Used to get or set properties of DOM elements Manipulates boolean properties or properties representing the state of an element $('input[type="checkbox"]').prop('checked', true);<br>let disabled = $('button').prop('disabled');
.attr() Used to get or set attributes of HTML elements Manipulates any attribute defined in the HTML markup $('img').attr('src', 'new_image.jpg');<br>let href = $('a').attr('href');
// Using .attr()
$('#myImage').attr('src', 'newImage.png');

// Using .prop()
$('#myCheckbox').prop('checked', true);

What is the purpose of the '.extend()' method in jQuery?

The '.extend()' method is used to merge two or more objects into one, often for configuration or data handling. It can also be used to create deep copies of objects.

// Merging objects
var defaultConfig = { color: 'blue', size: 'medium' };
var userConfig = { size: 'large' };

var finalConfig = $.extend({}, defaultConfig, userConfig);
console.log(finalConfig); // { color: 'blue', size: 'large' }

What is the difference between '.bind()', '.on()', and '.delegate()' in jQuery?

In jQuery, .bind(), .on(), and .delegate() are all methods used for event handling.

Method Usage Description
.bind() $(selector).bind(event, handler) Binds a handler function to one or more selected elements for a specified event.
.on() $(selector).on(event, handler) Attaches an event handler function for one or more events to the selected elements. This method is preferred for attaching event handlers as of jQuery 1.7.
.delegate() $(ancestor).delegate(selector, event, handler) Deprecated since jQuery 1.7. Binds an event handler to one or more selected ancestor elements and delegates the event handling to the selected descendant elements.

How do you avoid jQuery conflicts with other libraries that use the '$' symbol?

jQuery provides a method called '$.noConflict()' to avoid conflicts with other libraries that use the '$' symbol. After calling '$.noConflict()', you must use 'jQuery' instead of '$'.

jQuery.noConflict();

// Use jQuery with a different alias, such as 'jQuery'
jQuery(document).ready(function($) {
  // Now you can use $ safely within this function without conflicts
  $('#myElement').addClass('highlight');
});