Must know these JavaScript Topics Before Learning React Js

Must know these JavaScript Topics Before Learning React Js

Before you learn React.js, make sure you know these topics. This article breaks down must-know JavaScript topics in a simple way. From understanding variables to handling async tasks, it's your go-to guide for a smooth React learning journey."

  1. Basics of JS

    1. Variables = Named containers for storing data values.

       // Declaring a variable 'x' using 'var' and assigning the value 5
       var x = 5;
      
       // Declaring a variable 'y' using 'let' and assigning the value "Hello"
       let y = "Hello";
      
       // Declaring a constant variable 'z' using 'const' and assigning the value true
       const z = true;
      
    2. Hoisting of Variables = Process where variable declarations are moved to the top of their scope during compilation.

       // Logging the value of variable 'a' before its declaration and assignment
       // At this point, 'a' is hoisted to the top, but not yet assigned a value, so it's 'undefined'
       console.log(a); // Output: undefined
      
       // Variable 'a' is declared and assigned the value 10
       var a = 10;
      
  2. Functions = Blocks of reusable code; defined using the function keyword.

     // Defining a function 'add' that takes two parameters 'a' and 'b'
     // Returns the sum of 'a' and 'b'
     function add(a, b) {
       return a + b;
     }
    
     // Invoking the 'add' function with arguments 3 and 4
     // The result is the sum of 3 and 4
     const result = add(3, 4);
    
     // Logging the result to the console
     console.log(result); // Output: 7
    
    1. Arrow functions = Concise syntax for writing functions; () => {} instead of function() {}.

       // Defining a function 'multiply' using arrow function syntax
       // Takes two parameters 'a' and 'b' and returns their product
       const multiply = (a, b) => a * b;
      
       // Invoking the 'multiply' function with arguments 2 and 3
       // The result is the product of 2 and 3
       const result = multiply(2, 3);
      
       // Logging the result to the console
       console.log(result); // Output: 6
      
    2. Higher-order functions = Functions that operate on other functions, taking them as arguments or returning them.

       // Defining a function 'square' using arrow function syntax
       // Takes a parameter 'x' and returns the square of 'x'
       const square = (x) => x * x;
      
       // Defining a function 'applyOperation' using arrow function syntax
       // Takes two parameters 'num' and 'operation'; applies 'operation' to 'num'
       const applyOperation = (num, operation) => operation(num);
      
       // Invoking the 'applyOperation' function with arguments 5 and the 'square' function
       // The 'square' function is used as the 'operation', resulting in the square of 5
       const result = applyOperation(5, square);
      
       // Logging the result to the console
       console.log(result); // Output: 25
      
  3. Arrays and Objects \= Data structures to store collections of values (arrays) or key-value pairs (objects).

     // Creating an array 'numbers' with elements 1, 2, and 3
     const numbers = [1, 2, 3];
    
     // Creating an object 'person' with properties 'name' and 'age'
     const person = { name: "John", age: 30 };
    
    1. Array destructuring \= Extracting values from arrays into distinct variables.

       // Destructuring assignment to extract values from an array 'numbers'
       // Extracting the first and second elements into variables 'first' and 'second'
       const [first, second] = numbers;
      
       // Logging the value of the 'first' variable to the console
       console.log(first); // Output: 1
      
    2. Object destructuring = Extracting values from objects into distinct variables.

       // Destructuring assignment to extract properties from an object 'person'
       // Extracting the 'name' and 'age' properties into variables with the same names
       const { name, age } = person;
      
       // Logging the value of the 'name' variable to the console
       console.log(name); // Output: John
      
    3. Rest Operator = Collects remaining function arguments into an array.

       // Defining a function 'sum' using arrow function syntax
       // Takes two parameters 'a' and 'b', and collects additional parameters using the rest operator '...rest'
       const sum = (a, b, ...rest) => a + b + rest.reduce((acc, val) => acc + val, 0);
      
       // Invoking the 'sum' function with arguments 1, 2, 3, and 4
       // The function adds the numbers together, including any additional numbers passed through '...rest'
       const result = sum(1, 2, 3, 4);
      
       // Logging the result of the 'sum' function to the console
       console.log(result); // Output: 10
      
    4. Spread Operator = Expands array elements or object properties.

       // Creating an array arr1 with elements 1, 2, and 3
       const arr1 = [1, 2, 3];
      
       // Using the spread operator (...) to create a new array arr2
       // The new array includes all elements from arr1 and additional elements 4 and 5
       const arr2 = [...arr1, 4, 5];
      
       // Logging the resulting array arr2 to the console
       console.log(arr2); // Output: [1, 2, 3, 4, 5]
      
  4. Conditions in JS = Control flow structures to make decisions in code execution.

     // Assuming num is a numerical variable
     const num = 7;
    
     // Using if-else statements to check the value of num
     if (num > 0) {
       // If num is greater than 0, log "Positive" to the console
       console.log("Positive");
     } else if (num < 0) {
       // If num is less than 0, log "Negative" to the console
       console.log("Negative");
     } else {
       // If num is neither greater nor less than 0, log "Zero" to the console
       console.log("Zero");
     }
    
    1. if else = Conditional statement for branching logic.

       // Assuming isEven is a function that determines if a number is even or odd
       const isEven = (num) => (num % 2 === 0 ? "Even" : "Odd");
      
       // Invoking the isEven function with the argument 4
       // The result of the ternary operator determines if 4 is even or odd
       const result = isEven(4);
      
       // Logging the result to the console
       console.log(result); // Output: Even
      
    2. ternary operator \= Shorter syntax for simple if-else statements.

       // Assuming num is a numerical variable
       const num = 7;
      
       // Using the ternary operator to create a concise if-else statement
       // If num is greater than 0, assign "Positive" to result; otherwise, assign "Non-positive"
       const result = num > 0 ? "Positive" : "Non-positive";
      
       // Logging the final result to the console
       console.log(result);
      
    3. using && || \= Logical operators for AND and OR conditions.

       // Assuming isValid is a boolean variable
       const isValid = true;
      
       // Using the && and || operators for conditional logic
       // If isValid is true, assign "Valid input" to message; otherwise, assign "Invalid input"
       const message = isValid && "Valid input" || "Invalid input";
      
       // Logging the final message to the console
       console.log(message);
      
    4. optional chaining = Safely access nested properties without causing errors if any level is undefined or null.

       const person = { name: "John", address: { city: "New York" } };
       const city = person.address?.city;
       console.log(city); // New York
      
  5. Array Methods = Functions for manipulating arrays.

    1. map = Creates a new array by applying a function to each element of an existing array.

    2. filter = Creates a new array with elements that pass a provided function's test.

    3. reduce = Reduces an array to a single value using a function and an accumulator.

    4. sort = Sorts the elements of an array in place.

// Original array of numbers
const numbers = [1, 2, 3, 4, 5];

// Using the map method to create a new array with each element doubled
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]

// Using the filter method to create a new array with only the even numbers
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4]

// Using the reduce method to calculate the sum of all elements in the array
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 15

// Using the sort method to arrange the elements in ascending order
const sorted = numbers.sort((a, b) => a - b);
console.log(sorted); // Output: [1, 2, 3, 4, 5] (original array is modified)
  1. event listeners = Functions that wait for and respond to specific events.

    1. Onclick = Event listeners for click events.

    2. Onblur = Event listeners for blur events.

    3. Onchange = Event listeners for change events.

    4. Onfocus = Event listeners for focus events.

       const button = document.getElementById("myButton");
      
       button.addEventListener("click", () => {
         console.log("Button clicked!");
       });
      
       // Similar syntax for other events like blur, change, focus, etc.
      
    5. SetTimeout = Delays the execution of a function by a specified time.

       setTimeout(() => {
         console.log("Delayed message");
       }, 2000); //delay by 2 seconds
      
    6. SetInterval = Repeatedly calls a function with a fixed time delay between each call.

       // Initialize a counter variable
       let count = 0;
      
       // Set up an interval that runs every 1000 milliseconds (1 second)
       const intervalId = setInterval(() => {
         // Log the current count to the console
         console.log(`Count: ${count}`);
      
         // Increment the count
         count++;
      
         // Check if the count has reached 5
         if (count === 5) {
           // If count is 5, stop the interval by clearing it
           clearInterval(intervalId);
         }
       }, 1000);
      
  2. Asynchronous Events = Operations that do not block the execution of code.

     // A function fetchData that simulates fetching asynchronous data
     function fetchData(callback) {
       // Using setTimeout to mimic an asynchronous operation that takes 1000 milliseconds (1 second)
       setTimeout(() => {
         // Simulated data retrieved asynchronously
         const data = "Async data";
    
         // Calling the provided callback function with the retrieved data
         callback(data);
       }, 1000);
     }
    
     // Invoking fetchData with a callback function to handle the retrieved data
     fetchData(result => {
       // Logging the result to the console
       console.log(result);
     });
    
    1. callbacks = Functions passed as arguments to be executed later, often used in asynchronous code.

    2. callback hell = The nesting of multiple callbacks, leading to code that is hard to read and maintain.

       // Simulating an asynchronous operation with a callback
       function fetchData(callback) {
         setTimeout(() => {
           const data1 = "First data";
      
           // Nested asynchronous operation inside the callback
           callback(data1, (data2) => {
             console.log(data2);
           });
         }, 1000);
       }
      
       // Callback function with nested asynchronous operation
       fetchData((data1, innerCallback) => {
         console.log("Step 1:", data1);
      
         // Another asynchronous operation inside the callback
         setTimeout(() => {
           const data2 = "Second data";
           innerCallback(data2);
         }, 1000);
       });
      
    3. promises = Objects representing the eventual completion or failure of an asynchronous operation.

       // Promises Example
       const fetchData = new Promise((resolve, reject) => {
         // Simulating an asynchronous operation with setTimeout
         setTimeout(() => {
           const data = "Promise data";
      
           // Resolving the promise with the retrieved data
           resolve(data);
         }, 1000);
       });
      
       // Using then and catch to handle resolved and rejected states of the promise
       fetchData.then(result => {
         console.log(result);
       }).catch(error => {
         console.error(error);
       });
      
    4. Promise APIs = Methods like then, catch, and finally for handling promise states.

       // Promise APIs Example
       const promise1 = Promise.resolve("Resolved");
       const promise2 = Promise.reject("Rejected");
      
       // Handling resolved and rejected states of promises using then and catch
       promise1.then(result => console.log(result));
       promise2.catch(error => console.error(error));
      
  3. Async Await (alternative for promises) = Syntax for writing asynchronous code using promises in a more synchronous style.

     // Async Await Example
     function fetchData() {
       // Creating a promise to wrap the asynchronous operation
       return new Promise(resolve => {
         // Simulating an asynchronous operation with setTimeout
         setTimeout(() => {
           const data = "Async data";
    
           // Resolving the promise with the retrieved data
           resolve(data);
         }, 1000);
       });
     }
    
     // Using async function with await to handle asynchronous code in a synchronous style
     async function fetchDataAsync() {
       const result = await fetchData();
       console.log(result);
     }
    
     // Invoking the async function to demonstrate async/await usage
     fetchDataAsync();
    
  4. try, catch (for error handling) = Constructs for handling errors in a controlled manner.

     // Try, Catch Example
     function divide(a, b) {
       try {
         if (b === 0) {
           // Throwing an error when attempting to divide by zero
           throw new Error("Cannot divide by zero");
         }
         // Returning the result of the division if no error is thrown
         return a / b;
       } catch (error) {
         // Handling the caught error and logging the error message
         console.error(error.message);
       }
     }
    
     // Testing the divide function with valid and invalid inputs
     console.log(divide(6, 2)); // Output: 3
     console.log(divide(5, 0)); // Output: Error: Cannot divide by zero
    

Did you find this article valuable?

Support Subham Kumar by becoming a sponsor. Any amount is appreciated!