< / >
Published on

JavaScript Concepts 'this' Keyword, Prototypes, Closures, Async-style Code, Promises, Timers

Table of Contents

JavaScript Concepts: 'this' Keyword, Prototypes, Closures, Async-style Code, Promises, Timers

  1. this Keyword:

    • In JavaScript, the this keyword refers to the object to which the current code context belongs.
    • The value of this depends on how a function is called.
    • In the global scope, this refers to the global object (window in web browsers, global in Node.js).
    • Inside a function, this refers to the object that invoked the function (the object before the dot in the function call).
    • Arrow functions do not have their own this value; they inherit this from the surrounding lexical context.

    Example:

    const obj = {
      name: 'Rajnish',
      greet: function () {
        console.log(`Hello, ${this.name}!`)
      },
    }
    
    obj.greet() // Output: Hello, Rajnish!
    
  2. Prototypes:

    • Prototypes are a mechanism in JavaScript that allows objects to inherit properties and methods from other objects.
    • Every JavaScript object has a prototype property that points to another object. Properties and methods defined on the prototype are accessible to all instances of the object.
    • Prototypal inheritance allows objects to share behavior and avoid duplication.

    Example:

    function Person(name) {
      this.name = name
    }
    
    Person.prototype.greet = function () {
      console.log(`Hello, my name is ${this.name}.`)
    }
    
    const name = new Person('Rajnish')
    name.greet() // Output: Hello, my name is Rajnish.
    
  3. Closures:

    • Closures are functions that have access to the outer scope in which they were created, even after the outer scope has closed.
    • Closures are commonly used to create private variables and encapsulation in JavaScript.
    • They allow functions to "remember" and access variables from their lexical scope even when executed outside that scope.

    Example:

    function outerFunction() {
      const outerVariable = 'I am outer function.'
    
      function innerFunction() {
        console.log(outerVariable)
      }
      return innerFunction
    }
    
    const innerFunc = outerFunction()
    innerFunc() // Output: I am outer function.
    
  4. Async-style Code:

    • Asynchronous programming in JavaScript allows code to execute non-blocking operations, such as fetching data from a server or waiting for a timer to expire.

    • Async-style code typically involves callbacks, promises, or async/await syntax to handle asynchronous operations.

    • It helps improve performance and responsiveness in web applications by allowing tasks to run concurrently without blocking the main thread.

    Example:

    function fetchData(callback) {
      setTimeout(() => {
        callback('Data received')
      }, 2000)
    }
    
    fetchData((data) => {
      console.log(data) // Output: Data received
    })
    
  5. Promises:

    • Promises are a built-in feature in JavaScript for handling asynchronous operations.
    • A promise represents a value that may be available now, in the future, or never.
    • Promises can be in one of three states: pending, fulfilled, or rejected.
    • They allow chaining of asynchronous operations and provide a more structured way to handle asynchronous code than callbacks.

    Example:

    function fetchData() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('Data received')
        }, 2000)
      })
    }
    
    fetchData()
      .then((data) => {
        console.log(data) // Output: Data received
      })
      .catch((error) => {
        console.error(error)
      })
    
  6. Timers (setTimeout, setInterval):

    • setTimeout and setInterval are functions in JavaScript used to execute code after a specified delay or at regular intervals, respectively.
    • setTimeout executes the specified function once after the specified delay.
    • setInterval executes the specified function repeatedly, with a fixed time delay between each execution.
    • Both functions return a unique identifier (timeout ID) that can be used to cancel the execution using clearTimeout or clearInterval.

    Example:

    setTimeout(() => {
      console.log('Delayed log')
    }, 3000) // Output after 3 seconds: Delayed log
    
    let count = 0
    const intervalId = setInterval(() => {
      console.log(`Interval ${count}`)
      count++
      if (count === 5) {
        clearInterval(intervalId)
      }
    }, 1000) // Output every second for 5 seconds: Interval 0, Interval 1, ..., Interval 4