Web development Interview Question and their solutions

1. What is HTML and how does it work in web development?

Answer:
HTML (HyperText Markup Language) is the standard markup language used to create and structure content on the web. It tells the browser how to display content like text, images, links, and other elements on a web page.

HTML is made up of tags which define different elements. For example, <p> is used to create a paragraph, and <h1> is used for a heading.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Basic HTML Page</title>
</head>
<body>
    <h1>Hello World!</h1>
    <p>This is a simple HTML example.</p>
</body>
</html>

In this example, the <!DOCTYPE html> tag defines the document as an HTML5 document. The content is placed between <body></body>, and the heading <h1> and paragraph <p> elements display the content.


2. How do you create a basic structure of an HTML document?

Answer:
A basic HTML document has a specific structure that every web page follows. It consists of:

  1. <!DOCTYPE html>: Declares the document type as HTML5.
  2. <html>: The root element of the page.
  3. <head>: Contains meta-information about the page like title and linked resources (CSS, JS).
  4. <body>: Contains the content that is visible on the web page (text, images, links, etc.).
  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>My First Web Page</title>
</head>
<body>
    <h1>Welcome to My Web Page</h1>
    <p>This is where my content goes.</p>
</body>
</html>

In this example, the head contains the title, and the body contains the visible content.


3. What are semantic HTML tags? Give examples.

Answer:
Semantic HTML tags clearly describe their meaning to both the browser and the developer. They make the HTML more readable and meaningful.

Examples of semantic tags:

  • <header>: Defines the header of a page or section.
  • <article>: Represents an independent piece of content.
  • <section>: Defines sections in a document.
  • <footer>: Defines the footer of a document or section.
  • Example:
<article>
    <header>
        <h2>Introduction to Web Development</h2>
    </header>
    <p>Web development involves building websites and applications.</p>
    <footer>Written by John Doe</footer>
</article>

In this example, the header contains the heading, the article holds the main content, and the footer displays information about the author.


4. How do you link an external CSS file in an HTML document?

Answer:
To link an external CSS file, use the <link> tag inside the <head> section of the HTML document. The href attribute specifies the location of the CSS file.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>My Styled Page</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Welcome to My Styled Page</h1>
    <p>This page has external CSS applied.</p>
</body>
</html>

Here, the <link rel="stylesheet" href="styles.css"> tells the browser to load the CSS from styles.css.


5. How do you insert an image in HTML?

Answer:
You can insert an image in HTML using the <img> tag. The src attribute defines the image source (URL or file path), and the alt attribute provides alternative text if the image cannot be displayed.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Image Example</title>
</head>
<body>
    <h1>My Favorite Animal</h1>
    <img src="cat.jpg" alt="A cute cat">
</body>
</html>

In this example, <img src="cat.jpg" alt="A cute cat"> displays an image of a cat, and “A cute cat” will appear if the image cannot load.


6. How can you create a hyperlink in HTML?

Answer:
You can create a hyperlink using the <a> (anchor) tag. The href attribute specifies the URL that the link points to.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Hyperlink Example</title>
</head>
<body>
    <p>Visit <a href="https://www.example.com">Example Website</a>.</p>
</body>
</html>

In this example, <a href="https://www.example.com">Example Website</a> creates a link to https://www.example.com with the clickable text “Example Website”.


7. What is the purpose of the <meta> tag?

Answer:
The <meta> tag provides metadata about the HTML document, such as character encoding, viewport settings, and keywords for search engines. It is used inside the <head> element.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="description" content="A web development tutorial site">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Meta Tag Example</title>
</head>
<body>
    <p>Meta tags are in the head section of the document.</p>
</body>
</html>

In this example, the meta tags define:

  • charset: Character encoding (UTF-8).
  • description: Description of the page.
  • viewport: Viewport settings for mobile responsiveness.

8. How do you create an ordered and unordered list in HTML?

Answer:
In HTML, an ordered list is created using the <ol> tag, and an unordered list is created using the <ul> tag. Each list item is represented by the <li> tag.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>List Example</title>
</head>
<body>
    <h1>Ordered List</h1>
    <ol>
        <li>Item One</li>
        <li>Item Two</li>
        <li>Item Three</li>
    </ol>

    <h1>Unordered List</h1>
    <ul>
        <li>Item A</li>
        <li>Item B</li>
        <li>Item C</li>
    </ul>
</body>
</html>

In this example:

  • Ordered List (<ol>): Items are numbered (1, 2, 3).
  • Unordered List (<ul>): Items are marked with bullets.

9. What is the difference between <div> and <span>?

Answer:

  • <div> is a block-level element that takes up the entire width of its parent container. It’s used to group elements together.
  • <span> is an inline element, which only takes up as much space as its content, and it’s used to style a specific part of the text or content inside a block.
  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>div vs span Example</title>
</head>
<body>
    <div>
        This is a block-level element.
        <span>This is an inline element inside a block.</span>
    </div>
</body>
</html>

Here, the <div> occupies the whole line, while the <span> only occupies the space around the text “This is an inline element.”


10. How do you embed a video in an HTML page?

Answer:
You can embed a video in HTML using the <video> tag. The src attribute defines the video file’s location, and attributes like controls allow users to control video playback.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Video Embedding Example</title>
</head>
<body>
    <h1>Embedded Video</h1>
    <video width="400" controls>
        <source src="movie.mp4" type="video/mp4">
        Your browser does not support the video tag.
    </video>
</body>
</html>

In this example, the <video> tag embeds a video, with a width of 400 pixels and playback controls.


11. What are inline, block, and inline-block elements in HTML?

Answer:

  • Block-level elements: Take up the full width available, creating a new line after the element. Examples: <div>, <p>, <h1> to <h6>.
  • Inline elements: Only take up as much width as necessary, staying within the line. Examples: <span>, <a>, <img>.
  • Inline-block elements: Behave like inline elements but allow setting width and height, unlike regular inline elements. Example: <img>, when styled with display: inline-block.
  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Block, Inline, Inline-Block Example</title>
    <style>
        .inline-block {
            display: inline-block;
            width: 150px;
            height: 50px;
            background-color: lightblue;
        }
    </style>
</head>
<body>
    <div>This is a block element.</div>
    <span>This is an inline element.</span>
    <div class="inline-block">This is an inline-block element.</div>
</body>
</html>

In this example:

  • Block elements take up the full width.
  • Inline elements stay within the text flow.
  • Inline-block elements act like inline but can have defined dimensions.

12. What is the use of the <form> tag in HTML?

Answer:
The <form> tag is used to collect user input and send it to a server. Inside a form, elements like text inputs, radio buttons, checkboxes, and buttons can be used to collect data.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <form action="submit.php" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email"><br>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

In this example, the form collects the user’s name and email and submits it to a server-side script (like submit.php).


13. How do you create a checkbox in an HTML form?

Answer:
To create a checkbox in an HTML form, use the <input type="checkbox"> tag.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Checkbox Example</title>
</head>
<body>
    <form>
        <input type="checkbox" id="subscribe" name="subscribe" value="newsletter">
        <label for="subscribe">Subscribe to Newsletter</label><br>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Here, the checkbox allows users to opt-in to a newsletter subscription.


14. How can you create a dropdown list in HTML?

Answer:
You can create a dropdown list using the <select> element, with each option being defined inside <option> tags.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Dropdown Example</title>
</head>
<body>
    <form>
        <label for="cars">Choose a car:</label>
        <select id="cars" name="cars">
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="mercedes">Mercedes</option>
            <option value="audi">Audi</option>
        </select>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Here, the user can select from the options in the dropdown list.


15. How do you include JavaScript in an HTML document?

Answer:
You can include JavaScript in an HTML document in three ways:

  1. Inline JavaScript.
  2. Internal JavaScript (within <script> tags).
  3. External JavaScript (linked through a separate file).
  • Example of Internal JavaScript:
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Example</title>
    <script>
        function showAlert() {
            alert("Hello, World!");
        }
    </script>
</head>
<body>
    <button onclick="showAlert()">Click me</button>
</body>
</html>

Here, clicking the button triggers an alert using JavaScript.


16. What is the difference between <section>, <article>, and <aside> tags?

Answer:

  • <section>: Used for grouping related content.
  • <article>: Represents a self-contained piece of content, like a blog post.
  • <aside>: Used for content related to the main content but placed to the side, like a sidebar.
  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Section, Article, Aside Example</title>
</head>
<body>
    <section>
        <article>
            <h1>Main Article</h1>
            <p>This is the main article content.</p>
        </article>
        <aside>
            <p>This is related but secondary content.</p>
        </aside>
    </section>
</body>
</html>

Here, the article contains the primary content, and the aside holds secondary content.


17. How do you create a table in HTML?

Answer:
You create a table using the <table> tag, with rows (<tr>) and cells (<td> for data cells, <th> for headers).

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Table Example</title>
</head>
<body>
    <table border="1">
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Age</th>
        </tr>
        <tr>
            <td>John</td>
            <td>Doe</td>
            <td>25</td>
        </tr>
        <tr>
            <td>Jane</td>
            <td>Doe</td>
            <td>23</td>
        </tr>
    </table>
</body>
</html>

Here, the table has three columns (firstname, lastname, age) and two rows of data.


18. What is the purpose of the <header> and <footer> tags?

Answer:

  • <header>: Defines the header section of a document or section, usually containing headings, navigation links, or introductory content.
  • <footer>: Defines the footer of a document or section, typically containing copyright information, links, or contact details.
  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Header and Footer Example</title>
</head>
<body>
    <header>
        <h1>Website Title</h1>
        <nav>
            <a href="#home">Home</a> | <a href="#about">About</a>
        </nav>
    </header>

    <p>This is the main content of the page.</p>

    <footer>
        <p>&copy; 2024 Website Name</p>
    </footer>
</body>
</html>

Here, the header contains the site title and navigation, while the footer has copyright information.


19. How can you create a button in HTML?

Answer:
You can create a button using the <button> tag or <input type="button">.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Button Example</title>
</head>
<body>
    <button type="button" onclick="alert('Button clicked!')">Click Me</button>
</body>
</html>

Here, the button triggers a JavaScript alert when clicked.

See also  create a magazine layout using Semantic HTML and CSS Flexbox

20. How do you make an image a clickable link in HTML?

Answer:
You can wrap an image inside an anchor (<a>) tag to make it clickable.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Image Link Example</title>
</head>
<body>
    <a href="https://www.example.com">
        <img src="image.jpg" alt="Clickable Image">
    </a>
</body>
</html>

In this example, clicking the image will take the user to https://www.example.com.


21. What is CSS and why is it used in web development?

Answer:
CSS (Cascading Style Sheets) is a style sheet language used to control the appearance and layout of web pages. It separates the content (HTML) from the visual styling (colors, fonts, layout) and enables you to apply consistent styling across multiple pages.

  • Example
<!DOCTYPE html>
<html>
<head>
    <title>CSS Example</title>
    <style>
        body {
            background-color: lightblue;
        }
        h1 {
            color: navy;
            font-size: 2em;
        }
    </style>
</head>
<body>
    <h1>Styled Heading</h1>
    <p>This paragraph has default styling.</p>
</body>
</html>

Here, the CSS styles the body background and the color/size of the heading.


21. What is CSS and why is it used in web development?

Answer: CSS (Cascading Style Sheets) is used to style and layout web pages. It controls colors, fonts, spacing, and positioning of elements, separating the content from its presentation.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        body { background-color: lightgrey; }
        h1 { color: blue; }
    </style>
</head>
<body>
    <h1>Styled Heading</h1>
    <p>This is a styled paragraph.</p>
</body>
</html>

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

Answer: id is used for a unique element, while class can be used for multiple elements. id should be unique within a page, whereas class is not.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        #unique { color: red; }
        .common { color: green; }
    </style>
</head>
<body>
    <p id="unique">This is a unique element.</p>
    <p class="common">This is a common class element.</p>
</body>
</html>

23. How do you center text in CSS?

Answer: Use the text-align property to center text.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        .centered { text-align: center; }
    </style>
</head>
<body>
    <p class="centered">This text is centered.</p>
</body>
</html>

24. How do you create a responsive layout in CSS?

Answer: Use media queries to apply styles based on device width.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; }
        .container { width: 100%; }
        @media (max-width: 600px) {
            .container { background-color: lightblue; }
        }
    </style>
</head>
<body>
    <div class="container">This is a responsive container.</div>
</body>
</html>

25. What are pseudo-classes in CSS?

Answer: Pseudo-classes are used to define the special state of an element, such as :hover, :focus, and :active.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        a:hover { color: red; }
    </style>
</head>
<body>
    <a href="#">Hover over this link</a>
</body>
</html>

26. How do you use flexbox for layout in CSS?

Answer: Flexbox is used for creating flexible and responsive layouts. Use display: flex on the container.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        .container {
            display: flex;
            justify-content: space-around;
        }
        .item { width: 100px; height: 100px; background-color: lightcoral; }
    </style>
</head>
<body>
    <div class="container">
        <div class="item">Item 1</div>
        <div class="item">Item 2</div>
        <div class="item">Item 3</div>
    </div>
</body>
</html>

27. What is the box-shadow property in CSS?

Answer: box-shadow adds shadow effects around an element’s frame.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        .box { width: 100px; height: 100px; background-color: lightgrey; box-shadow: 3px 3px 5px grey; }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>

28. How do you apply a gradient background in CSS?

Answer: Use the background: linear-gradient or background: radial-gradient property.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        .gradient-bg { height: 100px; background: linear-gradient(to right, red, yellow); }
    </style>
</head>
<body>
    <div class="gradient-bg"></div>
</body>
</html>

29. What is the z-index property in CSS?

Answer: z-index controls the stacking order of elements. Higher values are in front.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        .front { position: absolute; z-index: 2; background-color: red; width: 100px; height: 100px; }
        .back { position: absolute; z-index: 1; background-color: blue; width: 100px; height: 100px; }
    </style>
</head>
<body>
    <div class="back"></div>
    <div class="front"></div>
</body>
</html>

30. How do you use CSS Grid for layout?

Answer: CSS Grid allows for creating complex layouts with rows and columns using display: grid.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        .grid-container {
            display: grid;
            grid-template-columns: auto auto auto;
            gap: 10px;
        }
        .grid-item { background-color: lightcoral; padding: 20px; text-align: center; }
    </style>
</head>
<body>
    <div class="grid-container">
        <div class="grid-item">1</div>
        <div class="grid-item">2</div>
        <div class="grid-item">3</div>
    </div>
</body>
</html>


31. What is JavaScript and why is it used in web development?

Answer: JavaScript is a programming language used to create interactive and dynamic content on web pages. It can manipulate HTML and CSS, handle events, and perform calculations.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Example</title>
</head>
<body>
    <button onclick="changeText()">Click me</button>
    <p id="text">Original text</p>

    <script>
        function changeText() {
            document.getElementById("text").innerHTML = "Text changed!";
        }
    </script>
</body>
</html>

32. What is a JavaScript variable and how do you declare one?

Answer: A JavaScript variable stores data. You can declare a variable using var, let, or const.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Variable Example</title>
</head>
<body>
    <script>
        let message = "Hello, World!";
        console.log(message);
    </script>
</body>
</html>

33. How do you create a function in JavaScript?

Answer: A function is created using the function keyword, followed by the function name and parameters.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Function Example</title>
</head>
<body>
    <script>
        function greet(name) {
            return "Hello, " + name;
        }
        console.log(greet("Alice"));
    </script>
</body>
</html>

34. What is an event in JavaScript and how do you handle it?

Answer: An event is an action that occurs in the browser, such as a click or keypress. You handle events using event listeners.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Event Example</title>
</head>
<body>
    <button id="myButton">Click me</button>

    <script>
        document.getElementById("myButton").addEventListener("click", function() {
            alert("Button clicked!");
        });
    </script>
</body>
</html>

35. What is a JavaScript object and how do you create one?

Answer: A JavaScript object is a collection of key-value pairs. It is created using curly braces {}.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Object Example</title>
</head>
<body>
    <script>
        let person = {
            name: "John",
            age: 30,
            greet: function() {
                return "Hello, " + this.name;
            }
        };
        console.log(person.greet());
    </script>
</

body>
</html>

36. What is an array in JavaScript and how do you create one?

Answer: An array is a list-like object used to store multiple values. It is created using square brackets [].

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Array Example</title>
</head>
<body>
    <script>
        let fruits = ["Apple", "Banana", "Cherry"];
        console.log(fruits[1]); // Outputs "Banana"
    </script>
</body>
</html>

37. How do you loop through an array in JavaScript?

Answer: You can loop through an array using a for loop or the forEach method.

  • Example with for loop:
<!DOCTYPE html>
<html>
<head>
    <title>Loop Example</title>
</head>
<body>
    <script>
        let fruits = ["Apple", "Banana", "Cherry"];
        for (let i = 0; i < fruits.length; i++) {
            console.log(fruits[i]);
        }
    </script>
</body>
</html>
  • Example with forEach:
<!DOCTYPE html>
<html>
<head>
    <title>Loop Example</title>
</head>
<body>
    <script>
        let fruits = ["Apple", "Banana", "Cherry"];
        fruits.forEach(function(fruit) {
            console.log(fruit);
        });
    </script>
</body>
</html>

38. How do you perform error handling in JavaScript?

Answer: Use try...catch blocks to handle errors gracefully.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Error Handling Example</title>
</head>
<body>
    <script>
        try {
            let result = 10 / 0;
            if (!isFinite(result)) throw "Division by zero";
        } catch (error) {
            console.log("Error: " + error);
        }
    </script>
</body>
</html>

39. What is AJAX and how is it used in JavaScript?

Answer: AJAX (Asynchronous JavaScript and XML) is used to make asynchronous HTTP requests to update parts of a web page without reloading.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>AJAX Example</title>
</head>
<body>
    <button id="loadData">Load Data</button>
    <div id="data"></div>

    <script>
        document.getElementById("loadData").addEventListener("click", function() {
            let xhr = new XMLHttpRequest();
            xhr.open("GET", "data.json", true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    document.getElementById("data").innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        });
    </script>
</body>
</html>

40. What is localStorage and sessionStorage in JavaScript?

Answer: Both localStorage and sessionStorage are web storage options. localStorage stores data with no expiration, while sessionStorage stores data for the duration of the page session.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Storage Example</title>
</head>
<body>
    <script>
        // Using localStorage
        localStorage.setItem("name", "Alice");
        console.log(localStorage.getItem("name"));

        // Using sessionStorage
        sessionStorage.setItem("sessionName", "Bob");
        console.log(sessionStorage.getItem("sessionName"));
    </script>
</body>
</html>


41. How do you add comments in CSS?

Answer: Comments in CSS are added with /* comment */.

  • Example:
/* This is a comment */
body {
    background-color: lightblue;
}

42. How do you add comments in JavaScript?

Answer: Comments in JavaScript can be single-line (// comment) or multi-line (/* comment */).

  • Example:
// This is a single-line comment
let x = 10;

/* This is a
multi-line comment */
let y = 20;

43. What is a callback function in JavaScript?

Answer: A callback function is a function passed into another function as an argument to be executed later.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Callback Example</title>
</head>
<body>
    <script>
        function fetchData(callback) {
            setTimeout(() => {
                let data = "Data fetched";
                callback(data);
            }, 1000);
        }

        fetchData(function(data) {
            console.log(data);
        });
    </script>
</body>
</html>

44. What is a closure in JavaScript?

Answer: A closure is a function that retains access to its lexical scope even when the function is executed outside that scope.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Closure Example</title>
</head>
<body>
    <script>
        function createCounter() {
            let count = 0;
            return function() {
                count++;
                return count;
            };
        }

        let counter = createCounter();
        console.log(counter()); // 1
        console.log(counter()); // 2
    </script>
</body>
</html>

45. How do you define and use a class in JavaScript?

Answer: Classes are syntactic sugar over JavaScript’s prototype-based inheritance, introduced in ES6.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Class Example</title>
</head>
<body>
    <script>
        class Person {
            constructor(name, age) {
                this.name = name;
                this.age = age;
            }
            greet() {
                return `Hello, my name is ${this.name}.`;
            }
        }

        let person = new Person("Alice", 30);
        console.log(person.greet());
    </script>
</body>
</html>

46. How do you make an API call using JavaScript Fetch API?

Answer: The Fetch API provides a modern way to make network requests.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Fetch API Example</title>
</head>
<body>
    <script>
        fetch('https://api.example.com/data')
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error('Error:', error));
    </script>
</body>
</html>

47. How do you handle asynchronous code in JavaScript?

Answer: Use async and await to handle asynchronous code in a more readable way.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Async/Await Example</title>
</head>
<body>
    <script>
        async function fetchData() {
            try {
                let response = await fetch('https://api.example.com/data');
                let data = await response.json();
                console.log(data);
            } catch (error) {
                console.error('Error:', error);
            }
        }

        fetchData();
    </script>
</body>
</html>

48. What is the this keyword in JavaScript?

Answer: The this keyword refers to the object that is currently executing the code. Its value depends on the context.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>this Keyword Example</title>
</head>
<body>
    <script>
        let person = {
            name: "Alice",
            greet() {
                return `Hello, my name is ${this.name}.`;
            }
        };
        console.log(person.greet());
    </script>
</body>
</html>

49. How do you manipulate the DOM using JavaScript?

Answer: Use methods like getElementById, querySelector, and properties like innerHTML to manipulate the DOM.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>DOM Manipulation Example</title>
</head>
<body>
    <p id="demo">Hello</p>
    <button onclick="changeText()">Change Text</button>

    <script>
        function changeText() {
            document.getElementById("demo").innerHTML = "Text changed!";
        }
    </script>
</body>
</html>

50. How do you create an HTML form and handle form submission with JavaScript?

Answer: Create a form using <form>, and handle submission with JavaScript by listening to the form’s submit event.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Form Submission Example</title>
</head>
<body>
    <form id="myForm">
        <input type="text" id="name" name="name" placeholder="Enter your name">
        <button type="submit">Submit</button>
    </form>

    <script>


        document.getElementById("myForm").addEventListener("submit", function(event) {
            event.preventDefault(); // Prevents default form submission
            let name = document.getElementById("name").value;
            console.log("Form submitted with name:", name);
        });
    </script>
</body>
</html>


51. What is the difference between inline, inline-block, and block display properties in CSS?

See also  How to Build a Responsive Portfolio Website Using HTML, CSS, and JavaScript

Answer:

  • block: Takes up the full width available and starts on a new line.
  • inline: Takes up only as much width as necessary and does not start on a new line.
  • inline-block: Combines properties of both inline and block, allowing setting width and height.
  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        .block { display: block; width: 100%; background-color: lightcoral; }
        .inline { display: inline; width: 50px; background-color: lightblue; }
        .inline-block { display: inline-block; width: 50px; height: 50px; background-color: lightgreen; }
    </style>
</head>
<body>
    <div class="block">Block</div>
    <div class="inline">Inline</div>
    <div class="inline">Inline</div>
    <div class="inline-block">Inline-block</div>
    <div class="inline-block">Inline-block</div>
</body>
</html>

52. What are CSS variables and how are they used?

Answer: CSS variables, also known as custom properties, allow you to store values and reuse them throughout your stylesheet.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        :root {
            --main-bg-color: lightcoral;
            --main-text-color: white;
        }
        body {
            background-color: var(--main-bg-color);
            color: var(--main-text-color);
        }
    </style>
</head>
<body>
    <p>This is a paragraph with custom properties.</p>
</body>
</html>

53. What is the CSS calc() function used for?

Answer: The calc() function allows you to perform calculations to determine CSS property values.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        .box {
            width: calc(100% - 20px);
            height: 100px;
            background-color: lightblue;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>

54. How do you create a CSS transition effect?

Answer: Use the transition property to animate changes to CSS properties.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: lightcoral;
            transition: background-color 0.5s ease;
        }
        .box:hover {
            background-color: lightgreen;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>

55. What are media queries in CSS?

Answer: Media queries are used to apply different styles based on the device’s characteristics, such as screen width.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; }
        @media (max-width: 600px) {
            body { background-color: lightblue; }
        }
    </style>
</head>
<body>
    <p>This is a responsive page.</p>
</body>
</html>

56. How do you add JavaScript to an HTML document?

Answer: JavaScript can be added using the <script> tag, either in the <head> or <body> section of the HTML.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Script Example</title>
</head>
<body>
    <script>
        console.log("JavaScript is added!");
    </script>
</body>
</html>

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

Answer: The DOM is a programming interface for web documents. It represents the structure of a document as a tree of objects.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>DOM Example</title>
</head>
<body>
    <p id="demo">Hello</p>
    <script>
        let element = document.getElementById("demo");
        element.innerHTML = "Text updated by JavaScript!";
    </script>
</body>
</html>

58. What are getElementById, getElementsByClassName, and querySelector used for in JavaScript?

Answer:

  • getElementById selects a single element by its ID.
  • getElementsByClassName selects multiple elements by their class.
  • querySelector selects a single element using CSS selectors.
  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Selectors Example</title>
</head>
<body>
    <p id="id1">Paragraph with ID</p>
    <p class="class1">Paragraph with Class</p>
    <p class="class1">Another Paragraph with Class</p>

    <script>
        let idElement = document.getElementById("id1");
        let classElements = document.getElementsByClassName("class1");
        let queryElement = document.querySelector(".class1");

        console.log(idElement.textContent);
        console.log(classElements.length);
        console.log(queryElement.textContent);
    </script>
</body>
</html>

59. What is the innerHTML property in JavaScript?

Answer: innerHTML is used to get or set the HTML content inside an element.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>innerHTML Example</title>
</head>
<body>
    <div id="content">Original Content</div>
    <script>
        document.getElementById("content").innerHTML = "Updated Content!";
    </script>
</body>
</html>

60. How do you create a JavaScript object with methods?

Answer: Create an object with methods by defining functions as properties of the object.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Object with Methods Example</title>
</head>
<body>
    <script>
        let calculator = {
            add(a, b) {
                return a + b;
            },
            subtract(a, b) {
                return a - b;
            }
        };

        console.log(calculator.add(5, 3));  // Outputs 8
        console.log(calculator.subtract(5, 3));  // Outputs 2
    </script>
</body>
</html>

61. What is event delegation in JavaScript?

Answer: Event delegation involves adding a single event listener to a parent element that manages events for its child elements.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Event Delegation Example</title>
</head>
<body>
    <ul id="list">
        <li>Item 1</li>
        <li>Item 2</li>
    </ul>

    <script>
        document.getElementById("list").addEventListener("click", function(event) {
            if (event.target.tagName === "LI") {
                alert("List item clicked: " + event.target.textContent);
            }
        });
    </script>
</body>
</html>

62. What is JSON and how is it used in JavaScript?

Answer: JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is used to send data between a server and a client.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>JSON Example</title>
</head>
<body>
    <script>
        let jsonData = '{"name": "Alice", "age": 30}';
        let obj = JSON.parse(jsonData);
        console.log(obj.name);  // Outputs "Alice"

        let newData = JSON.stringify({name: "Bob", age: 25});
        console.log(newData);  // Outputs '{"name":"Bob","age":25}'
    </script>
</body>
</html>

63. How do you handle form validation in JavaScript?

Answer: Use JavaScript to check form inputs before submission and display validation messages.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Form Validation Example</title>
</head>
<body>
    <form id="myForm">
        <input type="text" id="username" placeholder="Enter username" required>
        <button type="submit">Submit</button>
    </form>
    <p id="message"></p>

    <script>
        document.getElementById("myForm").addEventListener("submit", function(event) {
            let username =

 document.getElementById("username").value;
            let message = document.getElementById("message");
            if (username === "") {
                event.preventDefault(); // Prevents default form submission
                message.textContent = "Username is required!";
                message.style.color = "red";
            }
        });
    </script>
</body>
</html>

64. How do you include external JavaScript and CSS files in an HTML document?

Answer: Use the <link> tag for CSS and the <script> tag for JavaScript.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <script src="script.js"></script>
</body>
</html>

65. What is the purpose of the defer attribute in the <script> tag?

Answer: The defer attribute ensures that the script is executed after the HTML document has been completely parsed.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Defer Example</title>
</head>
<body>
    <script src="script.js" defer></script>
</body>
</html>

66. What is the difference between const and let in JavaScript?

Answer:

  • const declares a constant variable that cannot be reassigned.
  • let declares a variable that can be reassigned.
  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Const vs Let Example</title>
</head>
<body>
    <script>
        const pi = 3.14;
        let radius = 5;

        // pi = 3.15; // This will throw an error
        radius = 10; // This is allowed
        console.log(pi, radius);
    </script>
</body>
</html>

67. What is the fetch API and how does it differ from XMLHttpRequest?

Answer: The fetch API provides a modern way to make HTTP requests and is more flexible and readable than XMLHttpRequest.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Fetch API Example</title>
</head>
<body>
    <script>
        fetch('https://api.example.com/data')
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error('Error:', error));
    </script>
</body>
</html>

68. How do you implement a basic JavaScript timer?

Answer: Use setTimeout for a single delay or setInterval for repeated intervals.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Timer Example</title>
</head>
<body>
    <script>
        // Single delay
        setTimeout(function() {
            alert("This message appears after 2 seconds.");
        }, 2000);

        // Repeated interval
        let counter = 0;
        let intervalId = setInterval(function() {
            console.log("Interval message");
            counter++;
            if (counter === 5) {
                clearInterval(intervalId);
            }
        }, 1000);
    </script>
</body>
</html>

69. How do you create a simple modal dialog in JavaScript?

Answer: Use HTML, CSS, and JavaScript to create a modal dialog.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Modal Example</title>
    <style>
        .modal {
            display: none;
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
        }
        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
        }
        .close {
            float: right;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <button id="openModal">Open Modal</button>
    <div id="myModal" class="modal">
        <div class="modal-content">
            <span class="close" id="closeModal">&times;</span>
            <p>This is a modal dialog.</p>
        </div>
    </div>

    <script>
        let modal = document.getElementById("myModal");
        let openModal = document.getElementById("openModal");
        let closeModal = document.getElementById("closeModal");

        openModal.onclick = function() {
            modal.style.display = "flex";
        };

        closeModal.onclick = function() {
            modal.style.display = "none";
        };

        window.onclick = function(event) {
            if (event.target === modal) {
                modal.style.display = "none";
            }
        };
    </script>
</body>
</html>

70. What is the Promise object in JavaScript?

Answer: The Promise object represents the eventual completion or failure of an asynchronous operation and its resulting value.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Promise Example</title>
</head>
<body>
    <script>
        let promise = new Promise(function(resolve, reject) {
            let success = true; // or false
            if (success) {
                resolve("Operation was successful!");
            } else {
                reject("Operation failed.");
            }
        });

        promise.then(function(result) {
            console.log(result);
        }).catch(function(error) {
            console.error(error);
        });
    </script>
</body>
</html>

71. What are async and await in JavaScript?

Answer: async and await simplify working with promises by making asynchronous code look synchronous.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Async/Await Example</title>
</head>
<body>
    <script>
        async function fetchData() {
            try {
                let response = await fetch('https://api.example.com/data');
                let data = await response.json();
                console.log(data);
            } catch (error) {
                console.error('Error:', error);
            }
        }

        fetchData();
    </script>
</body>
</html>

72. How do you create a simple dropdown menu with HTML, CSS, and JavaScript?

Answer: Use HTML for the menu structure, CSS for styling, and JavaScript for interactive behavior.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Dropdown Menu Example</title>
    <style>
        .dropdown {
            position: relative;
            display: inline-block;
        }
        .dropdown-content {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 160px;
            box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
            z-index: 1;
        }
        .dropdown-content a {
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
        }
        .dropdown-content a:hover { background-color: #f1f1f1; }
        .dropdown:hover .dropdown-content { display: block; }
    </style>
</head>
<body>
    <div class="dropdown">
        <button class="dropbtn">Dropdown</button>
        <div class="dropdown-content">
            <a href="#">Link 1</a>
            <a href="#">Link 2</a>
            <a href="#">Link 3</a>
        </div>
    </div>
</body>
</html>

73. What is the purpose of localStorage and sessionStorage in JavaScript?

Answer: Both localStorage and sessionStorage allow you to store data on the client side. localStorage persists data across sessions, while sessionStorage only persists data for the duration of the page session.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Storage Example</title>
</head>
<body>
    <script>
        // Local Storage
        localStorage.setItem('name', 'Alice');
        console.log(localStorage.getItem('name'));  // Outputs "Alice"

        // Session Storage
        sessionStorage.setItem('sessionName', 'Bob');
        console.log(sessionStorage.getItem('sessionName'));  // Outputs "Bob"
    </script>
</body>
</html>

74. What is AJAX and how is it used?

Answer: AJAX (Asynchronous JavaScript and XML) is a technique for making asynchronous requests to the server without reloading the page.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>AJAX Example</title>
</head>
<body>
    <button id="loadData">Load Data</button>
    <div id="result"></div>

    <script>
        document.getElementById('loadData').addEventListener('click', function() {
            let xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://api.example.com/data', true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    document.getElementById('result').innerText = xhr.responseText;
                }
            };
            xhr.send();
        });
    </script>
</body>
</html>

75. How do you create a responsive web page?

Answer: Use responsive design techniques such as media queries and flexible layouts to ensure your website adapts to various screen sizes.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Responsive Design Example</title>
    <style>
        body { font-family: Arial, sans-serif; }
        .container { width: 100%; padding: 20px; }
        .box { width: 100%; padding: 20px; background-color: lightblue; }

        @media (min-width: 600px) {
            .box { width: 50%; float: left; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="box">Box 1</div>
        <div class="box">Box 2</div>
    </div>
</body>
</html>

76. What is the this keyword in JavaScript?

Answer: The this keyword refers to the context in which a function is executed. Its value depends on how the function is called.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>This Keyword Example</title>
</head>
<body>
    <script>
        function showThis() {
            console.log(this);
        }

        let obj = {
            name: "Alice",
            show: function() {
                console.log(this.name);
            }
        };

        showThis();  // Logs the global object
        obj.show();  // Logs "Alice"
    </script>
</body>
</html>

77. How do you handle errors in JavaScript?

Answer: Use try, catch, and finally blocks to handle errors in JavaScript.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Error Handling Example</title>
</head>
<body>
    <script>
        try {
            let result = riskyFunction(); // Assume this function might throw an error
        } catch (error) {
            console.error("An error occurred:", error.message);
        } finally {
            console.log("This will always execute.");
        }
    </script>
</body>
</html>

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

Answer: == checks for equality with type coercion, while === checks for equality without type coercion.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Equality Example</title>
</head>
<body>
    <script>
        console.log(5 == '5');   // true
        console.log(5 === '5');  // false
    </script>
</body>
</html>

79. How do you manipulate the DOM in JavaScript?

See also  create a magazine layout using Semantic HTML and CSS Flexbox

Answer: Use methods like getElementById, querySelector, appendChild, and removeChild to interact with the DOM.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>DOM Manipulation Example</title>
</head>
<body>
    <div id="container"></div>
    <script>
        let container = document.getElementById('container');
        let newElement = document.createElement('p');
        newElement.textContent = 'New paragraph added!';
        container.appendChild(newElement);

        setTimeout(() => {
            container.removeChild(newElement);
        }, 2000);
    </script>
</body>
</html>

80. What are CSS pseudo-classes and pseudo-elements?

Answer: Pseudo-classes style elements based on their state (e.g., :hover), while pseudo-elements style parts of elements (e.g., ::before).

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Pseudo-Classes and Elements Example</title>
    <style>
        a:hover { color: red; }
        p::first-line { font-weight: bold; }
    </style>
</head>
<body>
    <a href="#">Hover over me</a>
    <p>This is a paragraph with a bold first line.</p>
</body>
</html>

81. How do you create a JavaScript class?

Answer: Use the class keyword to create a class with a constructor and methods.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Class Example</title>
</head>
<body>
    <script>
        class Person {
            constructor(name, age) {
                this.name = name;
                this.age = age;
            }

            greet() {
                console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
            }
        }

        let person = new Person('Alice', 30);
        person.greet();
    </script>
</body>
</html>

82. What is a closure in JavaScript?

Answer: A closure is a function that retains access to variables from its lexical scope even after the function has finished executing.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Closure Example</title>
</head>
<body>
    <script>
        function createCounter() {
            let count = 0;
            return function() {
                count++;
                console.log(count);
            };
        }

        let counter = createCounter();
        counter();  // Outputs 1
        counter();  // Outputs 2
    </script>
</body>
</html>

83. What is event bubbling in JavaScript?

Answer: Event bubbling is the process where an event starts from the target element and bubbles up to the root element.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Event Bubbling Example</title>
</head>
<body>
    <div id="parent">
        <button id="child">Click me</button>
    </div>

    <script>
        document.getElementById('parent').addEventListener('click', function() {
            console.log('Parent clicked');
        });

        document.getElementById('child').addEventListener('click', function(event) {
            console.log('Child clicked');
            event.stopPropagation(); // Prevents event from bubbling up
        });
    </script>
</body>
</html>

84. How do you use setTimeout and setInterval in JavaScript?

Answer: setTimeout executes a function after a delay, while setInterval executes a function repeatedly at specified intervals.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>setTimeout and setInterval Example</title>
</head>
<body>
    <script>
        setTimeout(() => {
            console.log("Executed after 2 seconds");
        }, 2000);

        let counter = 0;
        let intervalId = setInterval(() => {
            console.log("Repeated message");
            counter++;
            if (counter === 5) {
                clearInterval(intervalId);
            }
        }, 1000);
    </script>
</body>
</html>

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

In JavaScript, null and undefined are both used to represent “empty” or “non-existent” values, but they are different in several ways:

1. Type

  • null: It is an object. When you check its type with typeof null, it will return "object".
  • undefined: It is a primitive type. When you check its type with typeof undefined, it will return "undefined".

2. Meaning

  • null: It represents an intentional absence of any object value. It is explicitly assigned by the programmer to indicate “no value.”
  • undefined: It means a variable has been declared, but no value has been assigned to it. JavaScript automatically assigns undefined to any variable that has not been initialized.

3. Usage

  • null: You use null when you want to intentionally clear a variable or set it to an empty or “non-existent” state.
    javascript let user = null; // user has no value, explicitly set
  • undefined: JavaScript uses undefined when a variable is declared but not initialized or when a function does not return a value.
    javascript let user; // user is declared but not initialized console.log(user); // undefined

4. Comparison

  • null == undefined: This is true because both represent “empty” values in a loose equality check.
    javascript console.log(null == undefined); // true
  • null === undefined: This is false because strict equality checks both value and type.
    javascript console.log(null === undefined); // false

5. When to Use

  • Use null when you want to explicitly indicate that a variable should have “no value.”
  • Use undefined when a variable is uninitialized or if you rely on JavaScript’s default behavior.

Here are the remaining questions, continuing from where we left off.


86. How do you implement form validation using JavaScript?

Answer: Form validation checks user input for errors before submitting the form. It can be implemented using the submit event and checking input values.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Form Validation Example</title>
</head>
<body>
    <form id="myForm">
        <input type="text" id="username" placeholder="Username">
        <input type="password" id="password" placeholder="Password">
        <button type="submit">Submit</button>
    </form>

    <p id="message"></p>

    <script>
        document.getElementById('myForm').addEventListener('submit', function(event) {
            let username = document.getElementById('username').value;
            let password = document.getElementById('password').value;
            let message = document.getElementById('message');

            if (username === "" || password === "") {
                event.preventDefault();  // Prevent form submission
                message.textContent = "Username and password are required!";
                message.style.color = "red";
            }
        });
    </script>
</body>
</html>

87. What is the Object.assign() method in JavaScript?

Answer: Object.assign() is used to copy the properties of one or more objects into a target object.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Object.assign Example</title>
</head>
<body>
    <script>
        let obj1 = { a: 1, b: 2 };
        let obj2 = { b: 3, c: 4 };
        let result = Object.assign({}, obj1, obj2);

        console.log(result);  // { a: 1, b: 3, c: 4 }
    </script>
</body>
</html>

88. How do you create an image slider using JavaScript?

Answer: You can create a simple image slider by using JavaScript to change the src attribute of an image element.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Image Slider Example</title>
</head>
<body>
    <img id="slider" src="image1.jpg" alt="Slider" width="300">
    <button onclick="nextImage()">Next</button>

    <script>
        let images = ["image1.jpg", "image2.jpg", "image3.jpg"];
        let currentIndex = 0;

        function nextImage() {
            currentIndex = (currentIndex + 1) % images.length;
            document.getElementById("slider").src = images[currentIndex];
        }
    </script>
</body>
</html>

89. How do you create a sticky header in CSS?

Answer: A sticky header stays at the top of the page even when the user scrolls. You can achieve this with the position: sticky; CSS property.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Sticky Header Example</title>
    <style>
        header {
            position: sticky;
            top: 0;
            background-color: #333;
            color: white;
            padding: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
    <header>Sticky Header</header>
    <div style="height: 1500px;">Scroll down to see the sticky header in action!</div>
</body>
</html>

90. How do you clone an object in JavaScript?

Answer: You can clone an object using Object.assign() or the spread operator (...).

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Object Cloning Example</title>
</head>
<body>
    <script>
        let original = { a: 1, b: 2 };

        // Using Object.assign()
        let clone1 = Object.assign({}, original);

        // Using the spread operator
        let clone2 = { ...original };

        console.log(clone1);  // { a: 1, b: 2 }
        console.log(clone2);  // { a: 1, b: 2 }
    </script>
</body>
</html>

91. How do you debounce a function in JavaScript?

Answer: Debouncing delays the execution of a function until a certain period has passed since it was last called. This is useful for optimizing repetitive events like window resizing.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Debounce Example</title>
</head>
<body>
    <input type="text" id="searchInput" placeholder="Type to search">

    <script>
        function debounce(func, delay) {
            let timeout;
            return function() {
                const context = this;
                const args = arguments;
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(context, args), delay);
            };
        }

        const search = debounce(function() {
            console.log("Searching...");
        }, 300);

        document.getElementById('searchInput').addEventListener('input', search);
    </script>
</body>
</html>

92. What is a JavaScript Map object and how is it different from an object literal?

Answer: A Map object allows you to store key-value pairs where keys can be any type (including objects and functions), unlike object literals where keys must be strings or symbols.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Map Example</title>
</head>
<body>
    <script>
        let map = new Map();
        map.set('name', 'Alice');
        map.set({key: 'key1'}, 'value1');

        console.log(map.get('name'));  // "Alice"
        console.log(map.size);  // 2
    </script>
</body>
</html>

93. What is a JavaScript Set object?

Answer: A Set object allows you to store unique values, meaning no duplicates are allowed.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Set Example</title>
</head>
<body>
    <script>
        let set = new Set();
        set.add(1);
        set.add(2);
        set.add(2);  // Duplicate, won't be added

        console.log(set.size);  // 2
        console.log(set.has(1));  // true
    </script>
</body>
</html>

94. How do you use template literals in JavaScript?

Answer: Template literals allow you to embed expressions and multi-line strings in JavaScript using backticks (`).

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Template Literals Example</title>
</head>
<body>
    <script>
        let name = 'Alice';
        let greeting = `Hello, ${name}! Welcome to the site.`;
        console.log(greeting);  // "Hello, Alice! Welcome to the site."
    </script>
</body>
</html>

95. How do you create an accordion in HTML, CSS, and JavaScript?

Answer: An accordion can be created by toggling the visibility of content sections when a header is clicked.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Accordion Example</title>
    <style>
        .accordion-content {
            display: none;
            padding: 10px;
            background-color: lightgray;
        }
        .active {
            display: block;
        }
    </style>
</head>
<body>
    <button class="accordion-header">Section 1</button>
    <div class="accordion-content">Content for section 1</div>

    <button class="accordion-header">Section 2</button>
    <div class="accordion-content">Content for section 2</div>

    <script>
        let headers = document.getElementsByClassName('accordion-header');

        for (let header of headers) {
            header.addEventListener('click', function() {
                let content = this.nextElementSibling;
                content.classList.toggle('active');
            });
        }
    </script>
</body>
</html>

96. How do you use innerHTML and textContent in JavaScript?

Answer: innerHTML allows you to set or get HTML content inside an element, while textContent only manipulates the text inside the element.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>innerHTML vs textContent Example</title>
</head>
<body>
    <div id="content"></div>

    <script>
        document.getElementById('content').innerHTML = "<strong>This is bold text.</strong>";
        console.log(document.getElementById('content').textContent);  // "This is bold text."
    </script>
</body>
</html>

97. What is event delegation in JavaScript?

Answer: Event delegation is a technique where you attach a single event listener to a parent element to manage events for its child

elements.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Event Delegation Example</title>
</head>
<body>
    <ul id="parent">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>

    <script>
        document.getElementById('parent').addEventListener('click', function(event) {
            if (event.target.tagName === 'LI') {
                console.log('Item clicked: ' + event.target.textContent);
            }
        });
    </script>
</body>
</html>

98. What are CSS Grid and Flexbox?

Answer: Both are layout models in CSS.

  • Flexbox: Aligns items along a single axis (horizontal or vertical).
  • Grid: Allows you to create complex two-dimensional layouts with rows and columns.
  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Grid and Flexbox Example</title>
    <style>
        .flex-container {
            display: flex;
            justify-content: space-around;
        }

        .grid-container {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
        }

        .item {
            padding: 20px;
            background-color: lightblue;
        }
    </style>
</head>
<body>
    <div class="flex-container">
        <div class="item">Flex Item 1</div>
        <div class="item">Flex Item 2</div>
        <div class="item">Flex Item 3</div>
    </div>

    <div class="grid-container">
        <div class="item">Grid Item 1</div>
        <div class="item">Grid Item 2</div>
        <div class="item">Grid Item 3</div>
    </div>
</body>
</html>

99. How do you toggle a class in JavaScript?

Answer: You can toggle a class using the classList.toggle() method, which adds or removes a class based on its presence.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Toggle Class Example</title>
</head>
<body>
    <button id="toggleButton">Toggle Highlight</button>
    <p id="text">This is a sample text.</p>

    <script>
        document.getElementById('toggleButton').addEventListener('click', function() {
            document.getElementById('text').classList.toggle('highlight');
        });
    </script>
</body>
</html>

100. How do you disable a button in JavaScript?

Answer: You can disable a button by setting its disabled property to true.

  • Example:
<!DOCTYPE html>
<html>
<head>
    <title>Disable Button Example</title>
</head>
<body>
    <button id="myButton" onclick="disableButton()">Click me</button>

    <script>
        function disableButton() {
            document.getElementById('myButton').disabled = true;
        }
    </script>
</body>
</html>

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *