FDT FE-102 Sprint Summary

Modified on Fri, 24 May at 2:54 PM

Usage Directions:


This is FE-102 Sprint Summary. Revising the entire content is estimated to require one-two hours of effort, assuming you have prior exposure to JavaScript. We recommend approaching this task in parts for a more effective revision process.


All the best!




TABLE OF CONTENTS






Topic 1: Javascript in HTML


Window Object in Javascript


What is it? 

The Window object is a global object in JavaScript that represents the browser window or frame in which the script is running.

Where is it used?

The Window object is available in web browsers and is used in client-side JavaScript to interact with the browser's window and its contents.

How is it used?

  1. Accessing Global Scope: The Window object serves as the global scope in JavaScript, allowing access to global variables and functions.

  2. Interacting with Document: The Window object provides access to the Document Object Model (DOM) of the current web page, enabling manipulation of its elements, attributes, and content.

  3. Handling Timers: The Window object offers methods, such as setTimeout() and setInterval(), to schedule the execution of JavaScript code at specified intervals or after a certain delay.

  4. Communicating Between Windows: The Window object can communicate with other windows or frames, whether they are within the same domain or different domains, using methods like postMessage() and window.open().

Code snippet example (accessing global scope):

<!DOCTYPE html>
<html>
<head>
  <title>Window Object Example</title>
</head>
<body>
  <script>
    // Accessing global variables
    var globalVariable = 'Hello from global scope!';
    console.log(window.globalVariable); // Output: 'Hello from global scope!'

    // Defining global function
    function globalFunction() {
      console.log('This is a global function.');
    }

    // Calling global function
    window.globalFunction(); // Output: 'This is a global function.'
  </script>
</body>
</html>

Takeaways / Best Practices:

  • Be cautious when using global variables and functions since they can lead to naming conflicts and code maintainability issues.

  • Avoid excessive manipulation of the browser window to provide a better user experience and prevent intrusive behavior.

<script> tag 

  • What is it? 

The <script> tag is an HTML element used to embed or reference external JavaScript code within an HTML document.

  • Where is it used? 

The <script> tag is used in HTML documents, typically placed in the <head> or <body> section, to include or reference JavaScript code.

  • How is it used?

    • Start by opening a pair of <script> tags.

    • Inside the <script> tags, you can write JavaScript code directly or reference an external JavaScript file using the src attribute.

    • If using the src attribute to reference an external JavaScript file, specify the file's path using the src attribute value. For example: <script src="path/to/script.js"></script>.

    • Close the <script> tag by adding a closing </script> tag.

Example code snippet:

<html>
  <head>
    <script>
      // JavaScript code written directly inside <script> tags
      function greet() {
        console.log("Hello, World!");
      }
      greet();
    </script>
    <script src="path/to/external/script.js"></script>
  </head>
  <body>
    <!-- Rest of the HTML content -->
  </body>
</html>
  • Takeaways / Best practices:

    • It's generally recommended to place the <script> tag just before the closing </body> tag to ensure the HTML content is loaded before executing JavaScript code. This can improve page load times.

    • When referencing an external JavaScript file, provide the correct path to the file to ensure it is properly loaded.

    • Use the defer or async attributes to control when the JavaScript code is executed. The defer attribute ensures the script is executed after the HTML content is parsed, while the async attribute allows the script to be executed asynchronously without blocking HTML parsing.



Topic 2: Document Object Model


Document Object Model


  • What is it? 

The Document Object Model (DOM) is a programming interface that represents an HTML or XML document as a structured tree-like object, allowing JavaScript to interact with and manipulate the document's elements, attributes, and text.

  • Where is it used?

The DOM is primarily used in web development when working with HTML documents in the browser. It is accessible through the JavaScript language.

  • How is it used?

    • Accessing elements: Use DOM methods to access and manipulate elements in an HTML document. Common methods include getElementById()getElementsByClassName()getElementsByTagName(), etc.

    • Modifying elements: Change the content, attributes, or styles of elements using DOM properties and methods. For example, use the innerHTML property to modify the HTML content of an element, or the setAttribute() method to set or modify an attribute.

    • Creating new elements: Use DOM methods like createElement() to create new elements, and then append them to the document using methods such as appendChild() or insertBefore().

    • Responding to events: Register event listeners on elements to handle user interactions. Use methods like addEventListener() to bind JavaScript functions to events such as click, hover, submit, etc.

    • Traversing the DOM: Navigate through the DOM tree using properties like parentNodechildNodesnextSibling, etc., to access and manipulate different elements based on their relationships within the document structure.

            Example code snippet:

 

<html>
  <body>
    <h1 id="heading">Hello, DOM!</h1>
    <p class="content">This is a paragraph.</p>
    <button id="myButton">Click Me</button>

    <script>
      // Accessing elements
      const heading = document.getElementById("heading");
      const paragraph = document.getElementsByClassName("content")[0];
      const button = document.querySelector("#myButton");

      // Modifying elements
      heading.innerHTML = "Hello, Updated DOM!";
      paragraph.style.color = "blue";
      button.setAttribute("disabled", true);

      // Creating new elements
      const newElement = document.createElement("p");
      newElement.textContent = "This is a new paragraph.";
      document.body.appendChild(newElement);

      // Responding to events
      button.addEventListener("click", function() {
        alert("Button clicked!");
      });

      // Traversing the DOM
      const parentElement = paragraph.parentNode;
      const siblingElement = heading.nextSibling;
    </script>
  </body>
</html>

       Takeaways / Best practices:

  • Use the appropriate DOM methods for element selection to ensure accurate and efficient access to elements.

  • Avoid inline event handlers (e.g., onclick="function()") use something as JavaScript addEventListener() instead.


Nodes in DOM


  • What is it? 

In the Document Object Model (DOM), a node represents an individual element, attribute, or piece of text within an HTML or XML document.

  • Where is it used?

Nodes are used within the DOM structure to represent the various elements, attributes, and text content of an HTML or XML document. They are primarily accessed and manipulated through JavaScript.

  • How is it used?

    • Node Types: Nodes can have different types, such as element nodes, attribute nodes, or text nodes, which determine their role and behavior within the DOM tree.

    • Accessing Nodes: Use DOM methods like getElementById()getElementsByClassName()getElementsByTagName(), or querySelector() to access nodes based on their ID, class, tag name, or other selectors.

    • Manipulating Nodes: Modify the content, attributes, or structure of nodes using DOM properties and methods. For example, use innerHTML to change the HTML content of an element, setAttribute() to set or modify attributes, or appendChild() to append a child node.

    • Traversing Nodes: Traverse through the DOM tree by accessing properties like parentNodechildNodesnextSibling, etc., to navigate to related nodes and perform operations on them.

    • Creating Nodes: Use methods like createElement() to create new element nodes, createAttribute() to create attribute nodes, or createTextNode() to create text nodes, and then insert them into the document structure using methods like appendChild() or insertBefore().

    • Removing Nodes: Remove nodes from the DOM using methods like removeChild() or remove().

        Example code snippet:

 

<html>
  <body>
    <div id="container">
      <h1 class="title">Hello, DOM!</h1>
      <p>This is a paragraph.</p>
    </div>

    <script>
      // Accessing nodes
      const container = document.getElementById("container");
      const title = container.getElementsByClassName("title")[0];
      const paragraph = container.getElementsByTagName("p")[0];

      // Manipulating nodes
      title.innerHTML = "Updated Title";
      paragraph.setAttribute("class", "highlight");
      const newElement = document.createElement("p");
      newElement.textContent = "This is a new paragraph.";
      container.appendChild(newElement);

      // Traversing nodes
      const parentElement = paragraph.parentNode;
      const siblingElement = title.nextSibling;

      // Removing nodes
      container.removeChild(paragraph);
      title.remove();
    </script>
  </body>
</html>


  • Takeaways / Best practices:
    • Understand the different node types in the DOM, such as element nodes, attribute nodes, and text nodes, to effectively work with and manipulate the document structure.

    • Familiarize yourself with the available DOM methods to access, modify, and traverse nodes efficiently.


innerHTML


  • What is it? 

innerHTML is a property in JavaScript that allows you to access or modify the HTML content inside an element, including its child elements, as a string.

  • Where is it used?

innerHTML is used when you need to manipulate the HTML content of an element dynamically. It is primarily used in web development with JavaScript to update or retrieve HTML content.

  • How is it used? 

<html>
  <body>
    <div id="myElement">
      <h1>Hello, DOM!</h1>
      <p>This is some content.</p>
    </div>

    <script>
      // Accessing HTML content
      const element = document.getElementById("myElement");
      const htmlContent = element.innerHTML;

      console.log(htmlContent);
      // Output: <h1>Hello, DOM!</h1><p>This is some content.</p>

      // Modifying HTML content
      element.innerHTML = "<h2>Updated Heading</h2><p>New content</p>";


     </script>
  </body>
</html>


  • Takeaways / Best practices:

    • Use innerHTML when you need to dynamically update or retrieve HTML content inside an element.

    • When possible, use more targeted DOM manipulation methods (e.g., creating elements, modifying attributes) instead of replacing entire HTML content to minimize performance impact.

textContent


  • What is it? 

textContent is a property in JavaScript that allows you to access or modify the text content of an element, excluding any HTML tags.

  • Where is it used? 

textContent is used when you need to access or modify the text content of an element, regardless of any HTML tags it may contain.

  • How is it used?

    • Difference from innerHTML: Unlike innerHTMLtextContent only accesses or modifies the text content of an element, ignoring any HTML tags present. It treats the content as plain text.

            Example code snippet:

 

<html>
  <body>
    <div id="myElement">
      <h1>Hello, DOM!</h1>
      <p>This is some content.</p>
    </div>

    <script>
      // Accessing text content
      const element = document.getElementById("myElement");
      const textContent = element.textContent;

      console.log(textContent);
      // Output: Hello, DOM! This is some content.

      // Modifying text content
      element.textContent = "Updated content";

      // Difference from innerHTML
      const htmlContent = "<strong>HTML content</strong>";
      element.innerHTML = htmlContent; // Sets HTML content
      console.log(element.textContent);
      // Output: HTML content
    </script>
  </body>
</html>


  • Takeaways / Best practices:

    • Use textContent when you specifically need to work with the plain text content of an element, excluding any HTML tags.

    • textContent is suitable for accessing and modifying text content, irrespective of any HTML structure or tags present in the element.

Topic 3: Selecting HTML Elements using Javascript


  • What is it?

Element selectors in HTML are patterns used to select and target specific elements within an HTML document for manipulation or styling.

  • Where is it used?

Element selectors are primarily used in JavaScript to access and manipulate elements within an HTML document. They are also used in CSS for styling purposes.

  • How is it used?

    • Syntax: Element selectors in JavaScript are similar to CSS selectors and use various methods to select elements based on their tag name, ID, class, attributes, or relationship to other elements.


  • Selecting by Tag Name: Use the getElementsByTagName() method to select elements based on their tag name. For example, getElementsByTagName('div') selects all <div> elements in the document.


  • Selecting by ID: Use the getElementById() method to select an element with a specific ID attribute. For example, getElementById('myElement') selects the element with id="myElement".


  • Selecting by Class: Use the getElementsByClassName() method to select elements based on their class name. For example, getElementsByClassName('myClass') selects all elements with class="myClass".


  • Selecting by CSS Selector: Use the querySelector() or querySelectorAll() methods to select elements using CSS selectors. For example, querySelector('#myElement') selects the element with id="myElement".


  • Combining Selectors: You can combine selectors to create more specific element selections. For example, querySelectorAll('div.myClass') selects all <div> elements with class="myClass".

                Example code snippet:

 

<html>
  <body>
    <div id="myElement">Element with ID</div>
    <p class="myClass">Element with Class</p>
    <div class="myClass">Another Element with Class</div>

    <script>
      // Selecting by tag name
      const divElements = document.getElementsByTagName('div');
      console.log(divElements);
      // Output: HTMLCollection [ <div id="myElement">, <div class="myClass"> ]

      // Selecting by ID
      const elementById = document.getElementById('myElement');
      console.log(elementById);
      // Output: <div id="myElement">

      // Selecting by class
      const elementsByClass = document.getElementsByClassName('myClass');
      console.log(elementsByClass);
      // Output: HTMLCollection [ <p class="myClass">, <div class="myClass"> ]

      // Selecting by CSS selector
      const elementBySelector = document.querySelector('#myElement');
      console.log(elementBySelector);
      // Output: <div id="myElement">

      // Combining selectors
      const elementsByCombinedSelector = document.querySelectorAll('div.myClass');
      console.log(elementsByCombinedSelector);
      // Output: NodeList [ <div class="myClass"> ]
    </script>
  </body>
</html>


  • Takeaways / Best practices:

    • Familiarize yourself with different element selection methods such as getElementsByTagName()getElementById()getElementsByClassName()querySelector(), and querySelectorAll()..

    • Use CSS selectors with querySelector() and querySelectorAll() for more flexible and complex element selections.


Topic 4: DOM Manipulation


Creating and Inserting DOM Elements


  • What is it?
    Creating DOM elements in JavaScript refers to the process of programmatically generating new elements and inserting them into the Document Object Model (DOM) of an HTML or XML document.

  • Where is it used?

Creating DOM elements is used when you need to dynamically generate and insert elements into the DOM based on user interactions, data retrieval, or other programmatic logic.

  • How is it used?

    • Create Element: Use the createElement() method to create a new element. Provide the tag name of the element you want to create as the argument.

    • Set Element Properties: Assign values to element properties, such as idclasssrctextContent, or other custom attributes, using the appropriate DOM properties or methods.

    • Append Element: Use methods like appendChild() or insertBefore() to add the newly created element as a child to an existing element within the DOM.

    • Apply Styling: Modify the style of the created element by accessing and updating its style property with CSS properties like backgroundColorcolorfontSize, etc.

    • Add Event Listeners: Register event listeners on the created element using methods like addEventListener() to respond to user interactions or trigger specific actions.

    • Insert Into DOM: Insert the created element into the desired location within the DOM by appending it to an existing element or inserting it before or after another element.

Example code snippet:

 

<html>
  <body>
    <div id="container">
      <h1 id="heading">Hello, DOM!</h1>
    </div>

    <script>
      // Create a new element
      const newElement = document.createElement("p");

      // Set element properties
      newElement.textContent = "This is a new paragraph.";
      newElement.setAttribute("class", "new-paragraph");

      // Append element to an existing element
      const container = document.getElementById("container");
      container.appendChild(newElement);

      // Apply styling
      newElement.style.color = "blue";
      newElement.style.fontSize = "20px";

      // Add event listeners
      newElement.addEventListener("click", function() {
        console.log("New paragraph clicked!");
      });

      // Insert into DOM
      const heading = document.getElementById("heading");
      container.insertBefore(newElement, heading.nextSibling);
    </script>
  </body>
</html>


  • Takeaways / Best practices:

    • Use createElement() to dynamically create new elements in JavaScript.

    • Identify the target location within the DOM where you want to insert the created element, and use methods like appendChild()insertBefore(), or insertAdjacentElement() to add it to the desired location.


Topic 5: Javascript in Browsers


Javascript Engine

What is it? 
A JavaScript Engine is a program that executes JavaScript code by translating it into machine code that a computer can understand.

Where is it used? 
JavaScript engines are used in web browsers to run JavaScript code and interpret it on the client-side. They are also used in server-side environments like Node.js to execute JavaScript code on the server.

Javascript is single threaded


  • What is it? 

JavaScript is single-threaded, meaning it executes code sequentially in a single thread of execution, processing one task at a time.

  • Where is it used?

JavaScript's single-threaded nature applies to all environments where JavaScript is executed, including web browsers, server-side environments (e.g., Node.js), and other platforms supporting JavaScript execution.

  • How is it used?

    • Sequential Execution: JavaScript executes code line by line, one statement at a time, in a single thread of execution.

    • Event Loop: JavaScript utilizes an event loop mechanism to handle asynchronous operations and non-blocking I/O, allowing concurrent execution of tasks without creating additional threads.

    • Callbacks and Promises: Asynchronous operations in JavaScript are typically handled through callbacks or Promises, where the code provides a callback function or a Promise object that gets executed when the asynchronous task completes.


  • Takeaways / Best practices:

    • JavaScript's single-threaded nature means that only one task can be executed at a time, so long-running or blocking operations can affect the responsiveness of your code.

    • Utilize asynchronous patterns like callbacks, Promises, or async/await to handle time-consuming or non-blocking tasks effectively.

Javascript Runtime


What it is: 


JavaScript Runtime refers to the environment where JavaScript code is executed. It includes the JavaScript engine, the call stack, and the event loop.

Where it is used: 


- It is used in web browsers to run JavaScript code on client-side.
- It is also used in server-side environments such as Node.js.

How it is used:

1. The JavaScript code is written and saved in a file with the .js extension.
2. The file is loaded by a web browser or a server-side environment.
3. The JavaScript engine, like V8 in Google Chrome, interprets and executes the code line by line.
4. The code is executed on the call stack, which keeps track of the program execution context (variables, functions, etc.).
5. Asynchronous operations, such as API calls or event handlers, are handled by the event loop. The event loop continuously checks for pending operations and executes their associated callbacks when available.
6. The code continues to run until it reaches the end or encounters an error.

Example code snippet:

javascript
// Example of JavaScript runtime
console.log("Start");

setTimeout(function() {
  console.log("Timeout callback");
}, 2000);

console.log("End");


In this snippet, "Start" and "End" will be printed immediately, while "Timeout callback" will be printed after a delay of 2 seconds due to the asynchronous nature of `setTimeout`.

Takeaways / Best Practices:


- Understand the event-driven nature of JavaScript runtime to handle asynchronous operations effectively.
- Optimize code performance by minimizing synchronous blocking operations.
- Be aware of the call stack and manage function execution to prevent stack overflow errors.


Topic 6: Browser APIs - setTimeout, console.log()

setTimeout


  • What is it?

setTimeout is a built-in JavaScript function used to schedule the execution of a callback function after a specified delay, measured in milliseconds.

  • Where is it used?

setTimeout is commonly used in JavaScript, both in browser and server-side environments, to create time delays, schedule asynchronous operations, or introduce timers for specific actions.

  • How is it used?

    • Specify a Callback Function: Provide a callback function that you want to execute after a certain delay.

    • Set Delay: Specify the delay duration in milliseconds as the second argument to setTimeout.

    • Optional Parameters: Additional parameters can be provided after the delay to be passed as arguments to the callback function.

    • Execution: After the specified delay, the callback function is added to the callback queue and will be executed once the call stack is empty and the event loop picks it up.

            Example code snippet:

 

function greet() {
  console.log("Hello, World!");
}

setTimeout(greet, 2000);
console.log("This message appears first.");

// Output: This message appears first. (after ~2 seconds) Hello, World!


  • Takeaways / Best practices:

    • Use setTimeout when you need to introduce a time delay or schedule the execution of a function after a specified period.

    • Provide a callback function as the first argument to setTimeout that will be executed after the specified delay.

    • Specify the delay duration in milliseconds as the second argument to setTimeout.

    • Avoid using setTimeout for precise timing or critical operations, as the actual execution time may vary depending on system load and other factors.

console.log()


What is it? 
console.log() is a JavaScript method used to print or log messages to the console, which can be helpful for troubleshooting, debugging, or displaying information during program execution.

Where is it used?
console.log() is mainly used in JavaScript for web development, specifically in the browser console.

How is it used?
1. To log a basic message: Simply use console.log() followed by the message enclosed in quotation marks.
2. To log values of variables or expressions: Pass the variable or expression as an argument to console.log().
3. To log multiple messages or values: Separate them with commas inside console.log().

Takeaways / best practices
1. Use console.log() to check the value of variables or expressions during program execution.
2. Comment out or remove unnecessary console.log() statements before deploying the code to production, as they may affect performance.
3. To prevent errors in browsers that do not have a console, use a fallback option such as wrapping console.log() within an if statement.


localStorage 


  • What is it?

localStorage is a web browser API in JavaScript that allows web applications to store key-value pairs locally on the user's device, persisting even after the browser is closed.

  • Where is it used?

localStorage is primarily used in web browsers as a client-side storage solution for web applications. It provides a simple and persistent storage mechanism without the need for server interaction.

  • How is it used?

    • Storing Data: Use the localStorage.setItem(key, value) method to store a key-value pair in the local storage. The key and value can be any valid JavaScript data types (e.g., strings, numbers, objects, arrays).

    • Retrieving Data: Use the localStorage.getItem(key) method to retrieve the value associated with a specific key from the local storage.

    • Updating Data: To update the value of an existing key, use the localStorage.setItem(key, value) method again with the same key.

    • Removing Data: Use the localStorage.removeItem(key) method to remove a key-value pair from the local storage based on the specified key.

    • Clearing Data: To clear all data stored in the local storage, use the localStorage.clear() method.

    Example code snippet:

 // Storing data in localStorage
localStorage.setItem("name", "Alice");
localStorage.setItem("age", "25");

// Retrieving data from localStorage
const name = localStorage.getItem("name");
const age = localStorage.getItem("age");

console.log(name); // Output: "Alice"
console.log(age); // Output: "25"


  • Takeaways / Best practices:

    • localStorage provides a simple and persistent storage mechanism for web applications.

    • Use localStorage.setItem(key, value) to store key-value pairs in the local storage.

    • Retrieve stored values using localStorage.getItem(key) by providing the associated key..


Topic 7: Promises in Javascript


Promises


  • What is it?

Promises are a built-in JavaScript feature that represents the eventual completion (or failure) of an asynchronous operation, providing a more structured and manageable way to work with asynchronous code.

  • Where is it used?

Promises are used in JavaScript applications across various environments, including web browsers and server-side environments like Node.js, wherever asynchronous operations are involved.

  • How is it used?

    • Creating a Promise: Use the Promise constructor to create a new Promise object, which takes a callback function with two arguments: resolve and reject.

    • Asynchronous Operation: Inside the Promise callback function, perform the asynchronous operation (e.g., making an HTTP request, reading a file) and call resolve with the result if it succeeds or reject with an error if it fails.

    • Handling Promise Results: Use the then() method on the Promise object to specify the callback function that will be executed when the Promise is resolved, receiving the resolved value as an argument.

    • Handling Errors: Chain the catch() method after then() to specify the callback function that will be executed when the Promise is rejected, receiving the error as an argument.

    • Chaining Promises: Use the then() method to chain multiple Promises together, allowing sequential or parallel execution of asynchronous operations.

    • Handling Multiple Promises: Utilize Promise.all() to wait for multiple Promises to complete and receive an array of resolved values when all Promises are fulfilled, or reject immediately if any Promise is rejected.

    • Error Handling in Chained Promises: Use catch() or finally() at the end of a Promise chain to handle any errors that occur throughout the chain or perform cleanup tasks regardless of the Promise outcome.

        Example code snippet:

 

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = "Data from asynchronous operation.";
      resolve(data);
    }, 2000);
  });
}

fetchData()
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.error(error);
});


  • Takeaways / Best practices:

    • Promises provide a more structured and manageable way to work with asynchronous code in JavaScript.

    • Use the Promise constructor to create a new Promise object, specifying a callback function with resolve and reject arguments.

    • Perform the asynchronous operation inside the Promise callback function and call resolve with the result when it succeeds, or reject with an error when it fails.

    • Use the then() method to specify the callback function that will be executed when the Promise is resolved, receiving the resolved value as an argument.

    • Chain the catch() method to handle errors that occur during Promise execution, providing a callback function that receives the error as an argument.

    • Chain Promises together using then() to achieve sequential or parallel execution of asynchronous operations.

    • Use Promise.all() to wait for multiple Promises to complete and receive an array of resolved values when all Promises are fulfilled, or reject immediately if any Promise is rejected.

    • Employ error handling techniques such as catch() or finally() to handle errors or perform cleanup tasks in Promise chains.

    • Utilize async/await syntax, built on top of Promises, to write more readable and synchronous-like code when dealing with asynchronous operations.


Topic 8: Fetch API in Javascript


Fetch API


  • What is it? 

The Fetch API is a way to communicate with web servers using JavaScript. It allows you to send requests to get data from a server or send data to a server.

  • Where is it used?

The Fetch API is used in web browsers and other JavaScript environments to fetch data from web servers, such as getting information from an API or submitting a form to a server.

  • How is it used?

    • Sending a Request: You use the fetch() function and provide the URL of the server you want to communicate with.

    • Handling the Response: After sending the request, you use the then() method to handle the response from the server. You can access the response data and process it in different ways.

    • Parsing the Response: The response from the server can be in different formats like JSON or plain text. You can use methods like json() or text() to extract the data from the response.

    • Error Handling: You can use the catch() method to handle errors that may occur during the fetch operation, like when the server is not reachable or the request fails.

Example code snippet:

 

fetch('<https://api.example.com/data>')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
});


  • Takeaways / Best practices:

    • The Fetch API is used to communicate with web servers using JavaScript.

    • You can use fetch() to send requests and receive responses from a server.

    • Use the then() method to handle the response and access the data returned by the server.

    • Use methods like json() or text() to extract data from the response.

    • Handle errors using the catch() method to handle any issues that occur during the fetch operation.


Topic 9: Async/Await in Javascript


Async/Await


  • What is it?

Async/await is a feature in JavaScript that makes working with asynchronous code easier.

  • Where is it used?

Async/await is used in JavaScript applications, whenever you need to work with asynchronous operations like making API calls or reading files.

  • How is it used?

    • Function Declaration: You declare an async function by adding the async keyword before the function definition. This tells JavaScript that this function contains asynchronous code.

    • Await Keyword: Inside the async function, you use the await keyword before calling a function or expression that returns a Promise. This keyword allows the function to wait for the Promise to resolve or reject before moving on.

    • Promise Handling: You can assign the result of the awaited Promise to a variable or use it directly in your code. You can also use try/catch blocks to handle any errors that may occur during the Promise execution.

Example code snippet:

 

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = "Data from asynchronous operation.";
      resolve(data);
    }, 2000);
  });
}

async function getData() {
  try {
    const result = await fetchData();
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

getData();
  • Takeaways / Best practices:

    • Async/await makes working with asynchronous code in JavaScript easier and more readable.

    • Use the async keyword to declare an async function that contains asynchronous code.

    • Use the await keyword before calling functions or expressions that return Promises, allowing the function to wait for their completion.

    • Handle errors using try/catch blocks to catch and handle any errors that may occur during the execution of Promises.






Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article