JavaScript Fundamentals

JavaScript is the programming language of the Web. It is used to make web pages interactive and dynamic.


Introduction to JavaScript

JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more.

JavaScript is the most popular scripting language on the Internet, and works in all major browsers, such as Internet Explorer, Mozilla Firefox, and Opera. It can be added to an HTML document in two ways: internally using the <script> tag, or externally by linking to a .js file.

<!-- Internal JavaScript -->
                        <script>
                          console.log("Hello, World!");
                          </script>

                        <!-- External JavaScript -->
                        <script src="myscripts.js"></script>

What is JavaScript?

  • JavaScript was designed to add interactivity to HTML pages
  • JavaScript is a scripting language
  • A scripting language is a lightweight programming language
  • JavaScript is usually embedded directly into HTML pages

Java and JavaScript are two completely different languages in both concept and design.


JavaScript is a client-side language, meaning it runs on the visitor's web browser. It is an interpreted language, meaning the code is read line by line and executed immediately.

JavaScript Variables (var, let, const)

JavaScript variables are containers for storing data values. In JavaScript, we use var, let, and const to declare variables.


  • var: Function-scoped. It's the old way of declaring variables. It can be redeclared and reinitialized.
    Example: var x = 10;
  • let: Let is Block-scoped. It can be reassigned.
  • It cannot be redeclared in the same scope.
  • let was introduced in ES6 (ECMAScript 2015).
  • let is used for variables that may change their value.
    Example: let y = 20;
  • const: Const is Block-scoped. It cannot be reassigned.
  • const is used for variables that should not change their value.
  • const was also introduced in ES6 (ECMAScript 2015).
    Example: const z = 30;
var name = "Developergtm"; // Function-scoped
let age = 5; // Block-scoped, can be changed
const PI = 3.14; // Block-scoped, cannot be changed

age = 6; // This is valid
// PI = 3.1415; // This will cause an error

Data Types

Data types are the different types of data that can be used. Data types are used to check the type of a variable.
Primitive data types are the most basic data types in JavaScript. They are not objects and have no methods.
JavaScript has six primitive data types:

  • String: Text, e.g., "Hello"

    Strings are used to represent text data. They can be enclosed in single quotes, double quotes, or backticks.

    Example:

    const greeting = "Hello, World!";
  • Number: Numeric values, e.g., 100

    Numbers in JavaScript can be integers or floating-point numbers. JavaScript uses the IEEE 754 standard for representing numbers.

    Example:

    const age = 25;
  • Boolean: True or false

    Booleans are used to represent a value that can be either true or false.

    They are often used in conditional statements to control the flow of a program.

    Example:

    const isJavaScriptFun = true;
  • Undefined: A variable that has been declared but not assigned a value

    Undefined is a type itself (undefined) and is the default value of uninitialized variables.

    Example:

    let x;
    console.log(x); // undefined
  • Null: A special value that represents "no value"

    Null is a type itself and it is used to indicate that a variable should not point to any object.

    Example:

    const emptyValue = null;
  • Symbol: A unique and immutable primitive value

    Symbols are basically used as unique identifiers for object properties.

    Example:

    const symbol = Symbol("id");
  • BigInt: It is used to store integer values that are too big to be represented by a normal JavaScript.

    BigInt is usually used for large integers, such as those used in cryptography or scientific calculations.

    Example:

    const bigNumber = BigInt(1234567890123456789012345678901234567890);

Non-Primitive Data Type

  • Object: A collection of key-value pairs

    The object data type can contain built-in objects, user-defined objects, and more.

    Objects are used to represent complex data structures.

    Example:

    const person = {
      name: "Goutam",
      age: 20,
      isFounder: true
    };

Functions

A function in JavaScript is a set of statements that performs a task or calculates a value and can be reused throughout the program. It eliminates the necessity to repeatedly write the same code. It assists programmers in writing modular codes. Functions enable the programmer to split a program into several small and manageable parts.

Like any other advanced programming language, JavaScript also supports all the features needed to write modular code with the help of functions. You have already seen a couple of functions like alert() and write() in the previous chapters. We repeatedly used these functions, but they were implemented in core JavaScript just a single time.

Pro Tip: Arrow Functions

ES6 introduced arrow functions, which provide a shorter syntax for writing functions. They are great for simple, one-line functions.

Example:

// Regular Function
function greet(name) {
  return "Hello, " + name;
}

// Arrow Function
const add = (a, b) => a + b;

console.log(greet("World")); // "Hello, World"
console.log(add(5, 3)); // 8

Types of Functions

  • Function Declaration:A function declaration is how you declare a function by name. It is hoisted, i.e., JavaScript knows about it even before code is executed. Because of hoisting, you can call it prior to or subsequent to it being defined in code. It has always a name and that name itself is called to invoke the function. Declarations are useful for functions you want available everywhere.

    Example:

    function multiply(a, b) {
      return a * b;
    }
  • Function Expression: A function expression is when a function is declared and put into a variable. It is not hoisted, so it does not actually work until the line of code is executed. It can be anonymous (named nothing) or occasionally named. The variable is a holder that the function is within. Expressions are good for flexibility, callbacks, and new styles of coding.

    Example:

    const divide = function(a, b) {
      return a / b;
    };
  • Arrow Function: Arrow functions represent a concise syntax for writing function expressions in JavaScript. Unlike traditional functions, they do not possess their own “this,” “arguments,” or “super”—they simply inherit these from their surrounding context. It’s important to note that arrow functions are not hoisted, meaning you must define one before attempting to invoke it. Typically, developers employ arrow functions for short operations, such as callbacks or when writing contemporary JavaScript code, as they often result in cleaner and more readable scripts. However, they are not universally applicable; for example, using them as object methods can lead to unintended behavior due to their lexical “this” binding.

    Example:

    const add = (a, b) => a + b;

Operators

In JavaScript, an operator is a symbol that performs an operation on one or more operands, such as variables or values, and returns a result. Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands, and + is called the operator.
There are different types of operators in JavaScript, such as arithmetic operators, comparison operators, logical operators, assignment operators, etc.

Types of Operators

  • Arithmetic Operators: They are used to perform mathematical operations like addition, subtraction, multiplication, and division.

    Example:

    const sum = 5 + 3; // 8
    const product = 5 * 3; // 15
  • Comparison Operators: It is used to compare the values of two operands like greater than, less than, equal to, etc.

    Example:

    const isEqual = (5 === 5); // true
    const isGreater = (5 > 3); // true
  • Logical Operators: Logical operators are used to combine boolean values and return a boolean result.

    Example:

    const andCondition = (true && false); // false
    const orCondition = (true || false); // true
  • Assignment Operators: Assignment operators are used to assign values to variables. They include the basic assignment operator (=) as well as compound assignment operators like +=, -=, *=, and /=.

    Example:

    let x = 5;
    x += 3; // x = x + 3
  • Unary Operators: Unary operators are used to perform operations on a single operand. They include the increment (++) and decrement (--) operators.

    Example:

    let y = 5;
    y++; // Increment
    y--; // Decrement
  • Binary Operators: Binary operators are used to perform operations on two operands.

    Example:

    let a = 5;
    let b = 10;
    let c = a + b; // Addition
  • Ternary Operators:It is a shorthand way of writing an if-else statement. Ternary operators take three operands and return a value based on a condition. It first evaluates the condition, and if it's true, it returns the first value; otherwise, it returns the second value.

    Example:

    let age = 18;
    const canVote = (age >= 18) ? "Yes" : "No";

Control Flow

The JavaScript if.else statement runs a code block when the given condition is true. When the condition is false then the else block will get executed. The if-else statements can be employed to manage the execution flow of a program based on varied conditions. While programming, there can be a time when you have to follow one out of a list of given paths. Under such circumstances, you must employ conditional statements in order for your program to make the right decisions and carry out the appropriate action. JavaScript provides support for conditional statements that are utilized to execute various actions for various conditions. In this case, we are going to discuss the if.else statement

Conditionals

Conditionals are used to perform different actions based on different conditions. The most common conditional statement is the if statement.

let age = 18;
if (age >= 18) {
  console.log("You are eligible to vote.");
} else {
  console.log("You are not eligible to vote.");
}
  • if: If statement is used to specify a block of code to be executed if a specified condition is true.

    Example:

    let age = 18;
    if (age >= 18) {
      console.log("You are eligible to vote.");
    }
  • else: The else statement is used to specify a block of code to be executed if the condition is false.

    Example:

    let age = 16;
    if (age >= 18) {
      console.log("You are eligible to vote.");
    } else {
      console.log("You are not eligible to vote.");
    }
  • else if: It is used to specify a new condition to test, if the first condition is false.

    Example:

    let age = 20;
    if (age < 18) {
      console.log("You are a minor.");
    } else if (age < 65) {
      console.log("You are an adult.");
    } else {
      console.log("You are a senior.");
    }
  • switch: A control statement that allows a variable to be tested for equality against a list of values. It is used when you want to perform different actions based on different conditions.
  • let fruit = "apple";
    switch (fruit) {
      case "banana":
        console.log("Banana is yellow.");
        break;
      case "apple":
        console.log("Apple is red.");
        break;
      default:
        console.log("Unknown fruit.");
    }

Loops

Alright, picture this: you’re knee-deep in coding, and suddenly you’re stuck doing the same thing, like, a thousand times.
Annoying, right? That’s where loops swoop in to save you from typing out the same line again and again. Instead of cluttering your code with repetitive nonsense, you just toss in a loop, and boom—way fewer lines, way less headache.

  • for loop:The most concise form of looping is the 'for' loop. It contains the following three significant components-
    • The loop initialization in which we set our counter to a beginning value. The initialization statement is run prior to the initiation of the loop.
    • The test statement that will check whether a given condition is true or false. If the condition is true, then the code provided within the loop will be executed, else the control will exit the loop.
    • The iteration statement in which you are allowed to increment or decrement your counter.

    syntax:

    for (initialization; condition; increment) {
      // code block to be executed
    }

    Example:

    for (let i = 0; i < 5; i++) {
      console.log(i);
    }
  • while loop: The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.

    syntax:

    while (condition) {
      // code block to be executed
    }

    Example:

    let i = 0;
    while (i < 5) {
      console.log(i);
      i++;
    }
  • do...while loop:Alright, so here’s the deal with do…while loops: they’re kinda like while loops’ rebellious cousin. The big difference? Instead of checking the condition first, a do…while loop just dives right in, does its thing once, and only then stops to ask, “Wait, should I keep going?” Even if the condition is straight-up false, you still get that first run. No exceptions. It’s like jumping into a pool and then checking if there’s water.

    syntax:

    do {
      // code block to be executed
    } while (condition);

    Example:

    let i = 0;
    do {
      console.log(i);
      i++;
    } while (i < 5);
    

Arrays

Arrays are used to store multiple values in a single variable. They are a special type of object in JavaScript.
Alright, here’s the thing: JavaScript arrays are basically these magical containers where you can dump a bunch of stuff—numbers, strings, whatever you want—into a single variable. You don’t have to stress about picking a size up front, either. Add ten things, take out three, chuck in a pineapple or a Boolean, it’s all good. The array just stretches or shrinks to fit whatever chaos you throw at it. Pretty chill, honestly.

let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Output: apple
  • Accessing Elements: You can access elements in an array using their index.

    Example:

    let fruits = ["apple", "banana", "cherry"];
    console.log(fruits[1]); // Output: banana
    

Array Methods

  • push(): Adds one or more elements to the end of an array.

    Example:

    let fruits = ["apple", "banana"];
    fruits.push("cherry");
    console.log(fruits); // Output: ["apple", "banana", "cherry"]
    
  • pop(): Removes the last element from an array and returns it.

    Example:

    let fruits = ["apple", "banana", "cherry"];
    let last = fruits.pop();
    console.log(last); // Output: cherry
    console.log(fruits); // Output: ["apple", "banana"]
    
  • shift(): Removes the first element from an array and returns it.

    Example:

    let fruits = ["apple", "banana", "cherry"];
    let first = fruits.shift();
    console.log(first); // Output: apple
    console.log(fruits); // Output: ["banana", "cherry"]
    
  • unshift(): Adds one or more elements to the beginning of an array.

    Example:

    let fruits = ["banana", "cherry"];
    fruits.unshift("apple");
    console.log(fruits); // Output: ["apple", "banana", "cherry"]
    
  • splice(): Adds or removes elements from an array at a specific index.

    Example:

    let fruits = ["apple", "banana", "cherry"];
    fruits.splice(1, 1, "orange");
    console.log(fruits); // Output: ["apple", "orange", "cherry"]
    
  • slice(): Returns a shallow copy of a portion of an array into a new array.

    Example:

    let fruits = ["apple", "banana", "cherry", "date"];
    let citrus = fruits.slice(1, 3);
    console.log(citrus); // Output: ["banana", "cherry"]
    
  • concat(): Merges two or more arrays and returns a new array.

    Example:

    let fruits = ["apple", "banana"];
    let moreFruits = ["cherry", "date"];
    let allFruits = fruits.concat(moreFruits);
    console.log(allFruits); // Output: ["apple", "banana", "cherry", "date"]
    

Strings

The String object in JavaScript works as a string of characters. It is a wrapper for the string primitive data type of JavaScript with a set of helper methods. As JavaScript will seamlessly switch between string primitives and String objects, you can call any one of the helper methods of the String object on a string primitive. A string is a sequence of characters, for example, "Hello" is a string. String primitives are unchangeable, i.e., they are not changeable once made. However, you can alter the value of the string by creating a new string.


Creating Strings

The strings can be created in JavaScript using a single quote, double quote, or backticks (template literals).
Template literals are convenient because they allow for multi-line strings and embedding of expressions.

Example:

let singleQuote = 'Hello, world!';
let doubleQuote = "Hello, world!";
let templateLiteral = `Hello, world!`;

String Methods

  • charAt(): Returns the character at a specified index.

    Example:

    let str = "Hello";
    console.log(str.charAt(0)); // Output: H
    
  • substring(): Returns a portion of the string between two specified indices.

    Example:

    let str = "Hello, world!";
    console.log(str.substring(0, 5)); // Output: Hello
    
  • toUpperCase(): Converts the string to uppercase.

    Example:

    let str = "Hello";
    console.log(str.toUpperCase()); // Output: HELLO
    
  • toLowerCase(): Converts the string to lowercase.

    Example:

    let str = "Hello";
    console.log(str.toLowerCase()); // Output: hello
    
  • trim(): Removes whitespace from both ends of the string.

    Example:

    let str = "   Hello, world!   ";
    console.log(str.trim()); // Output: "Hello, world!"
    
  • split(): Splits the string into an array of substrings based on a specified delimiter.

    Example:

    let str = "Hello, world!";
    console.log(str.split(", ")); // Output: ["Hello", "world!"]
    

DOM Manipulation

DOM stands for document object model. The web browser uses DOM to represent the HTML document internally. Additionally, it provides a set of functions and methods to modify the HTML document programmatically. These functions and methods are often called DOM Application Programming Interfaces or DOM API.

With the help of DOM API, we can add, delete, and modify HTML elements and attributes. We can also change the CSS styles of HTML elements.
DOM manipulation is a powerful feature that allows developers to create dynamic and interactive web applications.


HTML Element Manipulation

HTML element manipulation refers to the process of selecting, modifying, and deleting HTML elements using the DOM API.

  • getElementById(): It is used to select a single HTML element by its ID.

    Example:

    const element = document.getElementById("myElement");
    console.log(element); // Output: 
    ...

  • getElementsByClassName(): This method selects all HTML elements with a specific class name.

    Example:

    const elements = document.getElementsByClassName("myClass");
    console.log(elements); // Output: HTMLCollection(2) [div.myClass, div.myClass]
    

  • getElementsByTagName(): This method selects all HTML elements with a specific tag name.

    Example:

    const elements = document.getElementsByTagName("div");
    console.log(elements); // Output: HTMLCollection(3) [div, div, div]
    

  • querySelector(): It is used to select the first HTML element that matches a specified CSS selector.

    Example:

    const element = document.querySelector(".myClass");
    console.log(element); // Output: 
    ...

  • querySelectorAll(): It is used to select all HTML elements that match a specified CSS selector.

    Example:

    const elements = document.querySelectorAll(".myClass");
    console.log(elements); // Output: NodeList(2) [div.myClass, div.myClass]
    

Modifying HTML Elements

Modifying HTML elements involves changing their content, attributes, or styles using the DOM API.

  • Changing Text Content:

    You can change the text content of an element using the textContent property. Example:

    const element = document.getElementById("myElement");
    element.textContent = "New text content";
    

  • Changing HTML Content:

    You can change the HTML content of an element using the innerHTML property. Example:

    const element = document.getElementById("myElement");
    element.innerHTML = "New HTML content";
    

  • Changing Styles:

    You can change the styles of an element using the style property. Example:

    const element = document.getElementById("myElement");
    element.style.color = "blue";
    element.style.fontSize = "20px";
    

The DOM (Document Object Model) is a programming interface for web documents. It represents the structure of a document as a tree of objects, allowing developers to manipulate the content and structure of web pages.

// Find an element by its ID
const heading = document.getElementById("myHeading");

// Change its text content
heading.textContent = "Welcome to Developergtm!";

// Change its color
heading.style.color = "purple";

Objects

The JavaScript object is a non-primitive data type, which represents data in the form of key-value pairs. The key-value pairs are sometimes called properties. The key in a key-value pair, which is also known as "property name", is a string, and the value can be of any type. When the value of a property is a function, then the property is termed as a method.
Objects are defined with the usage of curly braces and each property can be distinguished by a colon. The elements within the object are not in the specific order. Hence, an object is an unordered collection of properties written as key: value pairs.

Objects are created using the Object constructor or the object literal syntax.

const car = {
  make: "Toyota",
  model: "Camry",
  year: 2020,
  start: function() {
    console.log("Car started");
  }
};

Common Object Methods

Methods are the functions that let the object do something or let something be done to it. There is a small difference between a function and a method at a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to performing complex mathematical operations on a group of local properties and parameters.

  • Object.keys() - Returns an array of a given object's property names.

    Example:

    const person = {
      name: "Alice",
      age: 30,
      city: "New York"
    };
    
    const keys = Object.keys(person);
    console.log(keys); // Output: ["name", "age", "city"]
    
  • Object.values() - Returns an array of a given object's property values.

    Example:

    const person = {
      name: "Alice",
      age: 30,
      city: "New York"
    };
    
    const values = Object.values(person);
    console.log(values); // Output: ["Alice", 30, "New York"]
    
  • Object.entries() - Returns an array of a given object's key-value pairs.

    Example:

    const person = {
      name: "Alice",
      age: 30,
      city: "New York"
    };
    
    const entries = Object.entries(person);
    console.log(entries); // Output: [["name", "Alice"], ["age", 30], ["city", "New York"]]
    

Creating New Objects

In JavaScript, everything, whether it's something you make or already there, comes from a basic thing called Object.
If you're making something, you can create it straight up using something called an object literal. You could also create a constructor, and then just use new with that constructor to get a new object.
There are are a few ways to make objects in JavaScript, and I'm going to show you all of them.

  • Object Literals: The easiest way to create an object is by using object literals.

    Example:

    const person = {
      name: "Alice",
      age: 30,
      city: "New York"
    };
    
  • Constructor Functions: You can create a constructor function and use the new keyword to create an object.

    Example:

    function Person(name, age, city) {
      this.name = name;
      this.age = age;
      this.city = city;
    }
    
    const person = new Person("Alice", 30, "New York");
    
  • Factory Functions: Another way to create objects is by using factory functions.

    Example:

    function createPerson(name, age, city) {
      return {
        name: name,
        age: age,
        city: city
      };
    }
    
    const person = createPerson("Alice", 30, "New York");
    
  • Object.create(): You can also create a new object with a specific prototype using Object.create().

    Example:

    const person = {
      name: "Alice",
      age: 30,
      city: "New York"
    };
    
    const employee = Object.create(person);
    employee.job = "Developer";
    

Events

In JavaScript, events are actions or occurrences that happen in the browser, which the JavaScript code can respond to. Events can be triggered by user interactions, such as clicks, keyboard input, or mouse movements, as well as by other means, such as timers or network requests.

Types of Events

  • Mouse Events: These events occur when the user interacts with the mouse, such as clicking, double-clicking, or moving the mouse over an element.

  • Keyboard Events: These events occur when the user interacts with the keyboard, such as pressing a key or releasing a key.
  • Form Events: These events occur when the user interacts with form elements, such as submitting a form or changing the value of an input field.
  • Window Events: These events occur when the user interacts with the browser window, such as resizing the window or scrolling the page.
  • Touch Events: These events occur when the user interacts with a touch screen, such as tapping or swiping.

Event Handling

  • Event Listeners: You can add event listeners to elements using the addEventListener method.

    Example:

    const button = document.getElementById("myButton");
    button.addEventListener("click", function() {
      alert("Button clicked!");
    });
    
  • Event Delegation: Instead of adding event listeners to individual elements, you can add a single event listener to a parent element and use event delegation to handle events for multiple child elements.

    Example:

    const list = document.getElementById("myList");
    list.addEventListener("click", function(event) {
      if (event.target.tagName === "LI") {
        alert("List item clicked: " + event.target.textContent);
      }
    });
    
  • Event Bubbling and Capturing: Events in the DOM can propagate in two phases: the capturing phase and the bubbling phase. In the capturing phase, the event starts from the root and goes down to the target element. In the bubbling phase, the event starts from the target element and goes up to the root.

Error Handling

JavaScript error handling, just to give a simple illustration, is the procedure of repairing the errors that have led the code to stop working. It is considered as a feature that every great application must have.

Types of Errors

  • Syntax Errors: A wrongly written code, for instance, an missing bracket will lead to a program that is not runnable.
  • Runtime Errors: These are errors that occur due to code execution that fail in any way, for example, if you try to access an object that is not there.
  • Logical Errors: The program is still running, but the result is not what you expected. Locating them can be very challenging.

Error Handling Techniques

  • Try...Catch: The try...catch statement allows you to test a block of code for errors and handle them gracefully.

    Example:

    try {
      // Code that may throw an error
    } catch (error) {
      // Handle the error
    }
    
  • Throwing Errors: You can create custom errors using the throw statement.

    Example:

    function validateInput(input) {
      if (!input) {
        throw new Error("Invalid input");
      }
    }
    
  • Finally Block: The finally block can be used to execute code after try...catch, regardless of whether an error occurred.

    Example:

    try {
      // Code that may throw an error
    } catch (error) {
      // Handle the error
    } finally {
      // Code to run regardless of error
    }
    

ES6 Features

ECMAScript 6 (ES6) introduced several new features that enhance the JavaScript language. Here are some of the key features:

  • Arrow Functions: A shorter syntax for writing function expressions.

    Example:

    const add = (a, b) => a + b;
    
  • Template Literals: A new syntax for string literals that allows for multi-line strings and string interpolation.

    Example:

    const name = "World";
    console.log(`Hello, ${name}!`);
    
  • Destructuring Assignment: A syntax that allows unpacking values from arrays or properties from objects into distinct variables.

    Example:

    const person = { name: "Alice", age: 25 };
    const { name, age } = person;
    
  • Default Parameters: A way to set default values for function parameters.

    Example:

    function multiply(a, b = 1) {
      return a * b;
    }
    
  • Spread Operator: A syntax for expanding arrays or objects.

    Example:

    const numbers = [1, 2, 3];
    const moreNumbers = [...numbers, 4, 5];
    

Asynchronous JS

Asynchronous programming is a technique that allows a program to perform tasks without blocking the main thread. In JavaScript, this is primarily achieved through callbacks, promises, and async/await syntax.

We can implement asynchronous operations in our JavaScript programs using callback functions, promises, async/await etc. The callback functions are functions passed as arguments to other functions. The promises are objects representing the success of failure of an asynchronous operation. The async/await syntax is simple implementation of promises. We will discuss these approaches in details in respective chapters.

  • Callbacks: Functions that are passed as arguments to other functions and are executed after a certain task is completed.

    Example:

    function fetchData(callback) {
      setTimeout(() => {
        const data = "Data received";
        callback(data);
      }, 1000);
    }
    fetchData((data) => {
      console.log(data);
    });
    
  • Promises: Objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value.

    Example:

    function fetchData() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          const data = "Data received";
          resolve(data);
        }, 1000);
      });
    }
    fetchData().then((data) => {
      console.log(data);
    });
    
  • Async/Await: Syntactic sugar built on top of promises, allowing for a more synchronous-looking code style.

    Example:

    async function fetchData() {
      const data = await new Promise((resolve) => {
        setTimeout(() => {
          resolve("Data received");
        }, 1000);
      });
      console.log(data);
    }
    fetchData();
    

JSON

JSON (JavaScript Object Notation) is a minimalistic data exchange format that is both simple for humans to understand and write and also easy for machines to interpret and create. Basically, it is used to move data from a server to a web app.
One can handle JSON in JavaScript through the use of the native JSON object which offers methods for parsing JSON strings and creating JavaScript objects.

  • Parsing JSON: To convert a JSON string into a JavaScript object, you can use the JSON.parse() method.

    Example:

    const jsonString = '{"name": "John", "age": 30}';
    const user = JSON.parse(jsonString);
    console.log(user.name); // John
    
  • Stringifying Objects: To convert a JavaScript object into a JSON string, you can use the JSON.stringify() method.

    Example:

    const user = { name: "John", age: 30 };
    const jsonString = JSON.stringify(user);
    console.log(jsonString); // {"name":"John","age":30}