Building strong foundational knowledge in frontend development topics

 These topics are essential for building strong foundational knowledge, and each comes with a simple solution or code snippet to illustrate the concept.

1. What is the difference between HTML, CSS, and JavaScript?

  • Answer:
    • HTML (Hypertext Markup Language) is used for structuring web content (headings, paragraphs, images, links, etc.).
    • CSS (Cascading Style Sheets) is used for styling the layout, design, and appearance of the web content.
    • JavaScript is used for adding interactivity and dynamic behavior to the website (e.g., form validation, animations, events).
    html
    <!-- HTML --> <div class="box"></div>
    css
    /* CSS */ .box { width: 100px; height: 100px; background-color: blue; }
    javascript
    // JavaScript document.querySelector('.box').addEventListener('click', function() { alert('Box clicked!'); });

2. What are semantic HTML elements and why are they important?

  • Answer:
    • Semantic HTML elements clearly describe their meaning in a human-readable way and help search engines and developers understand the content structure better.
    • Examples include <header>, <footer>, <article>, <section>, and <main>.
    • They improve SEO, accessibility, and code readability.
    html
    <header> <h1>Welcome to my website</h1> </header> <main> <p>This is the main content.</p> </main> <footer> <p>© 2025 All rights reserved.</p> </footer>

3. What is the box model in CSS?

  • Answer: The CSS box model defines how the size of elements is calculated. It consists of:
    • Content: The actual content (text, image, etc.)
    • Padding: Space between content and border
    • Border: Surrounds padding (if specified)
    • Margin: Space outside the border, separating elements
    • Understanding the box model is essential for controlling layout.
    css
    .element { width: 300px; padding: 20px; border: 5px solid black; margin: 10px; }

4. What is the difference between class and id in CSS?

  • Answer:
    • The id is unique and should only be used for a single element on the page (e.g., id="header").
    • The class can be used multiple times to apply styles to multiple elements (e.g., class="box").
    • id has higher specificity than class in CSS.
    html
    <div id="uniqueElement">This is an ID element</div> <div class="commonElement">This is a class element</div>

5. What is the difference between inline and block elements in HTML?

  • Answer:
    • Inline elements do not start on a new line and take up only as much width as necessary (e.g., <span>, <a>).
    • Block elements start on a new line and take up the full width available (e.g., <div>, <p>).
    html
    <div>This is a block element.</div> <span>This is an inline element.</span>

6. What is the CSS display property and its common values?

  • Answer:
    • The display property specifies how elements are displayed on the page.
    • Common values:
      • block: Element takes up full width.
      • inline: Element takes up only necessary width.
      • inline-block: Combines block and inline behaviors.
      • none: Hides the element.
    css
    .blockElement { display: block; } .inlineElement { display: inline; } .hiddenElement { display: none; }

7. What is the position property in CSS and its types?

  • Answer: The position property defines how an element is positioned on the page.
    • static: Default value, no special positioning.
    • relative: Positioned relative to its normal position.
    • absolute: Positioned relative to the nearest positioned ancestor.
    • fixed: Positioned relative to the viewport.
    • sticky: Switches between relative and fixed, based on scroll position.
    css
    .relative { position: relative; top: 20px; } .absolute { position: absolute; top: 50px; }

8. What are JavaScript Data Types?

  • Answer: JavaScript has primitive and non-primitive data types:
    • Primitive types: String, Number, Boolean, Null, Undefined, Symbol, BigInt.
    • Non-primitive types: Object, Array, Function.
    javascript
    let name = "Alice"; // String let age = 25; // Number let isActive = true; // Boolean let person = { name: "John", age: 30 }; // Object

9. What is the difference between let, const, and var in JavaScript?

  • Answer:
    • **let**: Block-scoped and can be reassigned.
    • **const**: Block-scoped, but cannot be reassigned.
    • **var**: Function-scoped, can be redeclared in the same scope.
    javascript
    let a = 10; a = 20; // Allowed with let const b = 30; // b = 40; // Error: Assignment to constant variable var c = 50; var c = 60; // Allowed with var

10. What is a CSS Transition?

  • Answer: A CSS Transition allows you to change property values smoothly (over a specified duration) when a specific event occurs (e.g., hover).
    css
    .element { transition: background-color 0.5s ease; } .element:hover { background-color: red; }

11. What is a CSS Animation?

  • Answer: CSS Animations allow you to animate an element's properties over time. They consist of @keyframes that define the changes during the animation.
    css
    @keyframes slide { from { transform: translateX(0); } to { transform: translateX(100px); } } .element { animation: slide 2s infinite; }

12. What is a Web API in the context of JavaScript?

  • Answer: Web APIs are browser-provided interfaces that allow JavaScript to interact with the browser and perform actions like making HTTP requests (using fetch), manipulating the DOM, handling local storage, or interacting with the user's device (e.g., Geolocation API).
    • Example:
      javascript
      fetch('https://api.example.com') .then(response => response.json()) .then(data => console.log(data));

13. What is the difference between localStorage and sessionStorage?

  • Answer:
    • localStorage: Stores data with no expiration time. Data remains available even after the browser is closed.
    • sessionStorage: Stores data for the duration of the page session (until the browser is closed).
    javascript
    localStorage.setItem('name', 'John'); sessionStorage.setItem('sessionId', '123');

14. What are JavaScript Functions and why are they important?

  • Answer: Functions are blocks of reusable code that perform specific tasks. They can take inputs (parameters) and return outputs (values). Functions help avoid code repetition and improve modularity.
    javascript
    function greet(name) { return "Hello " + name; } console.log(greet('Alice')); // Output: Hello Alice

15. What is the this keyword in JavaScript?

  • Answer: The this keyword refers to the current context of execution. It can refer to different objects depending on how the function is invoked:

    • In a method, this refers to the object the method is called on.
    • In a regular function, this refers to the global object (in non-strict mode).
    • In arrow functions, this is lexically bound, meaning it refers to the surrounding context.
    javascript
    const person = { name: 'Alice', greet: function() { console.log(this.name); // 'this' refers to person object } }; person.greet(); // Output: Alice

16. What is an Event Listener in JavaScript?

  • Answer: An Event Listener is a function that waits for an event to occur on an element and runs when the event is triggered (e.g., click, mouseover, keydown).
    javascript
    document.getElementById('btn').addEventListener('click', function() { alert('Button clicked!'); });
***************************************************************

1. CSS Flexbox Basics

  • Topic: What is Flexbox and how to use it for responsive layouts?
  • Solution: Demonstrate the basic usage of Flexbox for aligning items within a container.
    css
    .container { display: flex; justify-content: center; /* Horizontal centering */ align-items: center; /* Vertical centering */ } .item { margin: 10px; }

2. CSS Grid Basics

  • Topic: How to create a simple grid layout with CSS Grid?
  • Solution: Show a basic grid layout with grid-template-columns and grid-template-rows.
    css
    .container { display: grid; grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */ grid-gap: 10px; } .item { background-color: lightblue; }

3. CSS Transitions

  • Topic: How to add smooth transitions in CSS (e.g., hover effect)?
  • Solution: Show how to apply a transition effect on hovering a button.
    css
    .button { background-color: #3498db; padding: 10px 20px; border: none; transition: background-color 0.3s ease; } .button:hover { background-color: #2980b9; }

4. JavaScript Arrow Functions

  • Topic: What are arrow functions in JavaScript and why should you use them?
  • Solution: Compare regular functions and arrow functions.
    javascript
    // Regular Function function add(a, b) { return a + b; } // Arrow Function const add = (a, b) => a + b; console.log(add(2, 3)); // Output: 5

5. Event Delegation in JavaScript

  • Topic: What is event delegation and why is it useful?
  • Solution: Show how to handle events on dynamically added elements.
    javascript
    document.querySelector('#parent').addEventListener('click', function(event) { if (event.target && event.target.matches('button.classname')) { console.log('Button clicked'); } });

6. JavaScript Debouncing

  • Topic: How to debounce input events to prevent multiple function calls?
  • Solution: Show a simple debounce function to optimize event listeners (e.g., for search input).
    javascript
    let debounceTimer; document.getElementById('searchInput').addEventListener('input', function() { clearTimeout(debounceTimer); debounceTimer = setTimeout(function() { console.log('Searching for:', document.getElementById('searchInput').value); }, 500); // Wait 500ms after last input });

7. CSS Variables (Custom Properties)

  • Topic: How to use CSS variables for theming and reusability?
  • Solution: Show how to define and use CSS variables for consistent styling.
    css
    :root { --primary-color: #3498db; --secondary-color: #2ecc71; } .header { background-color: var(--primary-color); } .button { background-color: var(--secondary-color); }

8. LocalStorage vs SessionStorage

  • Topic: What is the difference between localStorage and sessionStorage in JavaScript?
  • Solution: Show examples of both localStorage and sessionStorage with saving and retrieving data.
    javascript
    // Using localStorage localStorage.setItem('username', 'JohnDoe'); console.log(localStorage.getItem('username')); // Output: JohnDoe // Using sessionStorage sessionStorage.setItem('tempData', 'Temporary'); console.log(sessionStorage.getItem('tempData')); // Output: Temporary

9. CSS Box Model

  • Topic: How the CSS box model works and how to manage margins, padding, and borders?
  • Solution: Visualize the CSS box model and its components.
    css
    .box { width: 200px; height: 100px; padding: 20px; border: 5px solid #333; margin: 15px; background-color: lightgray; }

10. JavaScript Map vs. Object

  • Topic: What is the difference between a JavaScript Map and an Object?
  • Solution: Show a basic comparison of both.
    javascript
    // Using Object let obj = {}; obj['key1'] = 'value1'; console.log(obj['key1']); // Output: value1 // Using Map let map = new Map(); map.set('key1', 'value1'); console.log(map.get('key1')); // Output: value1

11. Responsive Web Design with Media Queries

  • Topic: How to make a website responsive using CSS media queries?
  • Solution: Demonstrate a simple layout change for mobile view.
    css
    /* Default style */ .container { display: flex; flex-direction: row; } /* Mobile view */ @media (max-width: 600px) { .container { flex-direction: column; } }

12. Handling Form Validation in JavaScript

  • Topic: How to perform basic form validation with JavaScript?
  • Solution: Show a basic form validation example.
    javascript
    document.getElementById('submitBtn').addEventListener('click', function(event) { const name = document.getElementById('name').value; if (!name) { alert('Name is required'); event.preventDefault(); } });

13. CSS Pseudo-classes: :hover, :focus, and :active

  • Topic: How to use CSS pseudo-classes for interactivity?
  • Solution: Demonstrate styling changes on :hover, :focus, and :active.
    css
    button:hover { background-color: blue; } input:focus { border-color: green; } button:active { transform: scale(0.95); }

14. Using Icons with Font Awesome

  • Topic: How to use Font Awesome icons in a project?
  • Solution: Demonstrate adding Font Awesome icons to HTML and styling them.
    html
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <button><i class="fas fa-thumbs-up"></i> Like</button>

15. JavaScript Template Literals

  • Topic: What are template literals in JavaScript and how to use them?
  • Solution: Show how to use template literals for string interpolation.
    javascript
    let name = "Alice"; let age = 25; let message = `Hello, my name is ${name} and I am ${age} years old.`; console.log(message);

16. CSS :nth-child Selector

  • Topic: How to style specific child elements with the :nth-child selector?
  • Solution: Show how to select even and odd elements using :nth-child.
    css
    .list-item:nth-child(odd) { background-color: #f0f0f0; } .list-item:nth-child(even) { background-color: #ffffff; }

17. JavaScript Closures

  • Topic: What is a closure in JavaScript and how does it work?
  • Solution: Show a basic closure example.
    javascript
    function outerFunction() { let count = 0; return function innerFunction() { count++; console.log(count); } } const counter = outerFunction(); counter(); // Output: 1 counter(); // Output: 2

18. Custom Scrollbars in CSS

  • Topic: How to create custom scrollbars with CSS?
  • Solution: Demonstrate customizing scrollbar styles.
    css
    ::-webkit-scrollbar { width: 10px; } ::-webkit-scrollbar-thumb { background-color: #3498db; border-radius: 5px; }

These topics are concise and important for improving core frontend development skills. 

*************************************

1. What is the difference between == and === in JavaScript?

  • Answer: == is the loose equality operator that compares values after type coercion, while === is the strict equality operator that compares both the value and type.
    javascript
    5 == '5'; // true (type coercion occurs) 5 === '5'; // false (no type coercion)

2. What is the DOM (Document Object Model)?

  • Answer: The DOM represents the page so that programs can manipulate the structure, style, and content of a document. It turns the HTML into a tree of nodes.
    • Example: Using JavaScript to change content:
      javascript
      document.getElementById('myElement').textContent = 'Hello, World!';

3. What is the difference between null and undefined in JavaScript?

  • Answer: undefined means a variable has been declared but has not been assigned a value. null is an assignment value, representing the intentional absence of any value.
    javascript
    let x; console.log(x); // undefined let y = null; console.log(y); // null

4. What is the purpose of the this keyword in JavaScript?

  • Answer: this refers to the current context or object that is executing the code. It can vary depending on how a function is called.
    • Example: In a method:
      javascript
      const person = { name: 'Alice', greet: function() { console.log(`Hello, ${this.name}`); } }; person.greet(); // Output: Hello, Alice

5. What are Promises in JavaScript?

  • Answer: A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, resolved (fulfilled), or rejected.
    • Example:
      javascript
      let promise = new Promise((resolve, reject) => { let success = true; if(success) { resolve("Success!"); } else { reject("Failure!"); } }); promise.then(response => console.log(response)).catch(error => console.log(error));

6. What is localStorage in JavaScript and how is it different from sessionStorage?

  • Answer: localStorage stores data with no expiration time, while sessionStorage only stores data for the duration of the page session (until the browser or tab is closed).
    javascript
    localStorage.setItem('username', 'John'); sessionStorage.setItem('sessionID', '12345');

7. What is the box-sizing property in CSS?

  • Answer: The box-sizing property defines how the width and height of an element are calculated. With box-sizing: border-box;, padding and border are included within the element's width and height.
    css
    .element { width: 200px; padding: 20px; border: 5px solid black; box-sizing: border-box; }

8. What are CSS pseudo-classes and how are they used?

  • Answer: Pseudo-classes are keywords that define the special state of an element (like :hover, :focus, :nth-child).
    • Example:
      css
      button:hover { background-color: blue; } input:focus { border-color: green; }

9. What is the difference between a class and an id in HTML?

  • Answer: id is a unique identifier for an element, meaning it should only appear once in a page. class can be used to apply styles to multiple elements.
    html
    <div id="unique">This is unique</div> <div class="common">This is common</div>

10. What is the event.preventDefault() method in JavaScript?

  • Answer: The event.preventDefault() method prevents the default action of an event (such as form submission or link redirection).
    • Example:
      javascript
      document.getElementById('myForm').addEventListener('submit', function(event) { event.preventDefault(); alert('Form submission prevented!'); });

11. What is the CSS position property and its types?

  • Answer: The position property defines how an element is positioned in a document. It can have values like static, relative, absolute, fixed, and sticky.
    • Example:
      css
      .relative { position: relative; top: 10px; left: 20px; } .absolute { position: absolute; top: 50px; left: 50px; }

12. What is the purpose of the z-index in CSS?

  • Answer: The z-index property controls the stacking order of elements. Elements with a higher z-index value appear above elements with a lower value.
    css
    .element1 { position: absolute; z-index: 10; } .element2 { position: absolute; z-index: 5; }

13. What is the difference between inline and block elements in HTML?

  • Answer: Inline elements take up only as much width as necessary (e.g., <span>), while block elements take up the full width of their parent container (e.g., <div>, <p>).
    html
    <div>This is a block element</div> <span>This is an inline element</span>

14. What is the this keyword in arrow functions in JavaScript?

  • Answer: In arrow functions, this is lexically bound to the context in which the function is defined, rather than dynamically bound (like in regular functions).
    javascript
    const obj = { name: 'Alice', greet: function() { setTimeout(() => { console.log(`Hello, ${this.name}`); // 'this' refers to obj }, 1000); } }; obj.greet();

15. What are CSS pseudo-elements and how are they used?

  • Answer: Pseudo-elements like ::before and ::after are used to insert content before or after an element's actual content.
    css
    .content::before { content: "Note: "; font-weight: bold; }

16. How to add custom fonts in CSS?

  • Answer: You can add custom fonts using the @font-face rule or by using a service like Google Fonts.
    • Example (Google Fonts):
      html
      <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet"> <style> body { font-family: 'Roboto', sans-serif; } </style>

17. What is the async and defer attribute in script tags?

  • Answer: async loads the script asynchronously while defer ensures the script is executed after the document is parsed.
    html
    <script src="script.js" async></script> <!-- Async --> <script src="script.js" defer></script> <!-- Defer -->

18. What is the difference between localStorage and cookies?

  • Answer: localStorage is a larger, persistent storage option that does not expire, whereas cookies are smaller and can be set with an expiration date.
    javascript
    localStorage.setItem('key', 'value'); document.cookie = "name=John; expires=Thu, 18 Dec 2025 12:00:00 UTC";

19. What is the difference between font-weight and font-family in CSS?

  • Answer: font-weight defines the thickness of the text (e.g., normal, bold), whereas font-family specifies the typeface of the text (e.g., Arial, Times New Roman).
    css
    .text { font-family: 'Arial', sans-serif; font-weight: bold; }

20. What is the fetch() API in JavaScript?

  • Answer: The fetch() API allows you to make network requests and handle responses asynchronously.
    javascript
    fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log('Error:', error));
*******************************************

1. What is the Shadow DOM in Web Components?

  • Answer: The Shadow DOM is a way to encapsulate the internal structure of a web component, isolating its styles and behavior from the rest of the document.
    • Example:
      javascript
      const shadowRoot = document.getElementById('myElement').attachShadow({mode: 'open'}); shadowRoot.innerHTML = `<style>p { color: red; }</style><p>Hello from Shadow DOM!</p>`;

2. What is a CSS Flexbox wrap property?

  • Answer: The flex-wrap property in Flexbox is used to control whether the flex items should wrap or not when there is not enough space in the container.
    • Example:
      css
      .container { display: flex; flex-wrap: wrap; }

3. What is the opacity property in CSS?

  • Answer: The opacity property controls the transparency of an element, where 1 is fully opaque and 0 is fully transparent.
    • Example:
      css

      .element { opacity: 0.5; /* 50% transparent */ }

4. What is the isNaN() function in JavaScript?

  • Answer: The isNaN() function determines whether a value is NaN (Not-a-Number). It returns true if the value is NaN, otherwise false.
    • Example:
      javascript
      console.log(isNaN('Hello')); // true console.log(isNaN(123)); // false

5. What is the Event Bubbling in JavaScript?

  • Answer: Event bubbling is the process where events propagate from the target element to the root element, triggering event listeners on parent elements.
    • Example:
      javascript
      document.getElementById("parent").addEventListener("click", function() { alert("Parent clicked"); }); document.getElementById("child").addEventListener("click", function() { alert("Child clicked"); });

6. What is the defer attribute in HTML scripts?

  • Answer: The defer attribute tells the browser to continue parsing the HTML document while the script is being downloaded. The script is executed only after the document is fully parsed.
    • Example:
      html
      <script src="script.js" defer></script>

7. What are Web APIs in JavaScript?

  • Answer: Web APIs are interfaces provided by browsers that allow JavaScript to interact with the browser's features like local storage, geolocation, or fetch API for HTTP requests.
    • Example: Fetching data using the Fetch API:
      javascript
      fetch('https://api.example.com') .then(response => response.json()) .then(data => console.log(data));

8. What are CSS Media Queries and how do they work?

  • Answer: CSS Media Queries allow you to apply different styles based on the viewport size, screen resolution, or device orientation. It helps make websites responsive.
    • Example:
      css
      @media (max-width: 600px) { .container { flex-direction: column; } }

9. What is the visibility property in CSS?

  • Answer: The visibility property in CSS determines whether an element is visible or hidden, but unlike display: none, it still takes up space in the layout.
    • Example:
      css
      .hidden { visibility: hidden; /* Element is hidden but still occupies space */ }

10. What is the window.onload event in JavaScript?

  • Answer: The window.onload event is triggered when the entire page (including images, scripts, etc.) has finished loading.
    • Example:
      javascript
      window.onload = function() { alert("Page is fully loaded!"); };

11. What is the DOMContentLoaded event in JavaScript?

  • Answer: The DOMContentLoaded event is triggered when the HTML document has been completely loaded and parsed, without waiting for stylesheets or images to load.
    • Example:
      javascript
      document.addEventListener('DOMContentLoaded', function() { alert('DOM is fully loaded!'); });

12. What is the bubbling and capturing phases in JavaScript events?

  • Answer: When an event is triggered, it goes through two phases: capturing (from root to target) and bubbling (from target to root).
    • Example:
      javascript
      element.addEventListener('click', function() { console.log("Event in bubbling phase"); }, true); // true for capturing phase

13. What is the difference between var, let, and const in JavaScript?

  • Answer: var is function-scoped and can be re-declared. let is block-scoped and cannot be re-declared in the same block. const is block-scoped and cannot be reassigned after declaration.
    • Example:
      javascript
      var x = 10; let y = 20; const z = 30;

14. What is the JSON.parse() and JSON.stringify() in JavaScript?

  • Answer: JSON.parse() converts a JSON string into a JavaScript object, while JSON.stringify() converts a JavaScript object into a JSON string.
    • Example:
      javascript
      const jsonString = '{"name": "Alice", "age": 25}'; const jsonObj = JSON.parse(jsonString); console.log(jsonObj.name); // Output: Alice const newJsonString = JSON.stringify(jsonObj); console.log(newJsonString); // Output: '{"name":"Alice","age":25}'

15. What are Web Workers in JavaScript?

  • Answer: Web Workers allow JavaScript to run scripts in the background on a separate thread, without blocking the main thread (UI thread).
    • Example:
      javascript
      const worker = new Worker('worker.js'); worker.postMessage('Hello Worker'); worker.onmessage = function(e) { console.log('Message from worker:', e.data); };

16. What is the purpose of event.stopPropagation()?

  • Answer: The event.stopPropagation() method stops the event from propagating (bubbling or capturing) to other elements.
    • Example:
      javascript
      document.getElementById('parent').addEventListener('click', function() { console.log("Parent clicked"); }); document.getElementById('child').addEventListener('click', function(event) { event.stopPropagation(); // Stops bubbling console.log("Child clicked"); });

17. What is the CSS clip-path property?

  • Answer: The clip-path property allows you to define a specific region of an element to display, hiding parts outside the defined shape.
    • Example:
      css
      .circle { width: 200px; height: 200px; background-color: #3498db; clip-path: circle(50% at 50% 50%); }

18. What are Template Literals in JavaScript?

  • Answer: Template literals allow embedding expressions inside strings using ${} and support multi-line strings.
    • Example:
      javascript
      let name = 'Alice'; let greeting = `Hello, ${name}! Welcome to the world of JavaScript.`; console.log(greeting);

19. What is the Array.prototype.map() method in JavaScript?

  • Answer: The map() method creates a new array by applying a function to each element in the original array.
    • Example:
      javascript
      const numbers = [1, 2, 3, 4]; const squares = numbers.map(num => num * num); console.log(squares); // Output: [1, 4, 9, 16]

20. What is CORS (Cross-Origin Resource Sharing)?

  • Answer: CORS is a security feature that allows or restricts web pages to make requests to domains other than the one from which the page was served.
    • Example: If you're making an API call to a different domain, the server must allow it through CORS headers.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

oAuth in angular