Codeworx Logo

10 JavaScript Concepts to Revisit Pre-React

Mandar

Mandar J

Last updated:


10 JavaScript Concepts to Revisit Pre-React

Introduction:

JavaScript serves as the backbone of modern web development, and understanding its fundamentals is crucial before diving into frameworks like React. In this blog, we'll revisit essential JavaScript concepts that lay the foundation for React development. Each topic will be accompanied by a detailed example to ensure a comprehensive understanding.


1.Import and Export:

JavaScript's import and export statements facilitate modular code organization. They allow us to split our code into separate files and import functionalities from one file to another. For instance, consider a utility module exporting a function to calculate the square of a number:

// square.js
export function square(num) {
  return num * num;
}


In another file, we can import and utilize this function:

// app.js
import { square } from './square.js';
console.log(square(5)); // Output: 25


2.Variables and Values:

JavaScript variables hold data that can be manipulated or changed. They can store various types of values such as strings, numbers, Booleans, etc. For example:

let name = 'John';
let age = 30;
const PI = 3.14;


Explanation: In this example, name stores a string, age stores a number, and PI stores a constant value.


3.Operators:

JavaScript supports various operators for performing operations on operands. Examples include arithmetic, assignment, comparison, and logical operators. For instance:

  • Arithmetic Operators:
let x = 10;
let y = 5;
console.log(x + y); // Addition: 15
console.log(x - y); // Subtraction: 5
console.log(x * y); // Multiplication: 50
console.log(x / y); // Division: 2
console.log(x % y); // Modulus: 0 (remainder of x/y)
console.log(++x);   // Increment: 11
console.log(--y);   // Decrement: 4


  • Assignment Operators:
let a = 10;
let b = 5;
a += b; // Equivalent to: a = a + b (a = 15)
console.log(a);


  • Comparison Operators:
let p = 10;
let q = 5;
console.log(p > q);  // Greater than: true
console.log(p < q);  // Less than: false
console.log(p >= q); // Greater than or equal to: true
console.log(p <= q); // Less than or equal to: false
console.log(p === q); // Equal to: false
console.log(p !== q); // Not equal to: true


  • Logical Operators:
let isLoggedIn = true;
let isAdmin = false;
console.log(isLoggedIn && isAdmin); // AND: false
console.log(isLoggedIn || isAdmin); // OR: true
console.log(!isAdmin); // NOT: true


  • Bitwise Operators:
let m = 5;  // Binary: 0101
let n = 3;  // Binary: 0011
console.log(m & n);  // Bitwise AND: 1 (0001)
console.log(m | n);  // Bitwise OR: 7 (0111)
console.log(m ^ n);  // Bitwise XOR: 6 (0110)
console.log(~n);     // Bitwise NOT: -4 (1100)
console.log(m << 1); // Bitwise left shift: 10 (1010)
console.log(n >> 1); // Bitwise right shift: 1 (0001)


  • Unary Operators:
let num = 5;
console.log(-num);   // Unary negation: -5
console.log(+num);   // Unary plus: 5
console.log(++num);  // Pre-increment: 6
console.log(--num);  // Pre-decrement: 5


  • Ternary Operator(If-else):
let age = 18;
let allowed = (age >= 18) ? "Allowed" : "Not Allowed";
console.log(allowed); // "Allowed"


4.Functions and Parameters:

Functions in JavaScript allow us to encapsulate reusable blocks of code. They can accept parameters, enabling flexibility. Arrow functions provide a concise syntax for defining functions.

Example: Basic Function:

function greet(name) {
    return `Hello, ${name}!`;
}

console.log(greet('Alice')); // Output: Hello, Alice!


Explanation:

In this example, greet is a function that accepts a parameter name.

Inside the function, we use template literals to concatenate the name parameter with the greeting message.

The return statement sends the result back to the caller.

Example: Arrow Function

Arrow functions are a concise syntax introduced in ES6 for defining functions. They offer a more compact and readable way to write functions, especially for short, one-liner functions.

const square = (num) => num * num;

console.log(square(5)); // Output: 25


Explanation:

Here, `square` is an arrow function that takes a single parameter `num`.

The arrow (=>) signifies the function definition.

If the function body is a single expression, you can omit the curly braces {} and the `return` keyword.

The function implicitly returns the result of `num * num`.


5.Objects and Classes:

Objects are key-value pairs used extensively in React for representing components, state, props, and other data structures. They allow for organizing and accessing data in a structured manner.

Classes provide a blueprint for creating objects with predefined properties and methods. Example:

// Object
let person = {
    name: 'John',
    age: 30,
    greet() {
        return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
    }
};
console.log(person.greet()); // Output: Hello, my name is John and I am 30 years old.


// Class
class Car {
    constructor(brand) {
        this.brand = brand;
    }
    drive() {
        return `Driving ${this.brand}`;
    }
}
let myCar = new Car('Toyota');
console.log(myCar.drive()); // Output: Driving Toyota


Explanation: Here, we define an object person with properties and a method. We also create a Car class with a constructor and a method.


6.Arrays and Array Methods:

Arrays in JavaScript store collections of data and provide numerous methods for manipulation. Arrays are fundamental data structures in JavaScript, widely used in React for managing and manipulating data. They provide flexibility for storing collections of elements and offer various methods for efficient data manipulation.

Example:

let numbers = [1, 2, 3, 4, 5];

//Array.map method
console.log(numbers.map(num => num * 2)); // Output: [2, 4, 6, 8, 10]


Explanation: The map method iterates over each element of the numbers array and multiplies each element by 2.

Lets see one more Array method: filter()

Suppose we have an array of user objects and we want to filter out users who are active.

const users = [
    { blogId: 1, name: 'Alice', active: true },
    { blogId: 2, name: 'Bob', active: false },
    { blogId: 3, name: 'Charlie', active: true }
];


const activeUsers = users.filter(user => user.active);
console.log(activeUsers);


Explanation:

users.filter() is an array method used to create a new array containing elements that pass a certain condition.

In this example, we use filter() to create a new array activeUsers containing only users with active property set to true.


7.Destructuring and Spread Operator:

Destructuring allows us to extract values from objects or arrays into distinct variables. The spread operator spreads array elements or object properties. Example:

// Destructuring
let person = {name:'John', age: 30};
console.log(name, age); // Output: John 30


// Spread Operator
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combinedArray = [...arr1, ...arr2];
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]


Explanation: Here, we destructure name and age from the person object, and use the spread operator to combine two arrays.


8.Asynchronous JavaScript:

Asynchronous programming is crucial in React for handling tasks such as data fetching, handling user interactions, and managing state updates. Callback functions are a common mechanism for managing asynchronous operations in JavaScript.

Example: Fetching Data from an API in React

Suppose we want to fetch data from an API and update the UI accordingly:

// Function to fetch data from API
function fetchData() {
    // Fetch data from an API endpoint
    fetch('https://api.example.com/data')
        .then(response => {
            // Check if response is successful
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            // Parse JSON response
            return response.json();
        })
        .then(data => {
            // Call a function to update UI with fetched data
            updateUI(data);
        })
        .catch(error => {
            // Handle any errors
            console.error('Error fetching data:', error);
        });
}


// Function to update UI with fetched data
function updateUI(data) {
    // Example: Update UI with fetched data
    const dataList = document.getElementById('data-list');
    dataList.innerHTML = ''; // Clear previous data
    data.forEach(item => {
        const listItem = document.createElement('li');
        listItem.textContent = item.name; // Assuming data has 'name' property
        dataList.appendChild(listItem);
    });
}


// Call fetchData function to initiate data fetching and UI update
fetchData();


Explanation:

The fetchData function makes a request to an API endpoint using the fetch API.

It handles the asynchronous nature of the fetch operation using .then() and .catch() methods.

Once the data is successfully fetched, it calls the updateUI function to update the UI with the fetched data.

The updateUI function receives the fetched data as a parameter and updates the UI accordingly. In this example, it assumes that the data is an array of objects with a name property.

Finally, we call the fetchData function to initiate the process of fetching data and updating the UI.


9. Control Structures:

Control structures like if-else statements and loops (for, while) enable conditional execution and iteration. Example:

// If-Else Statement
let num = 10;
if (num > 0) {
  console.log('Positive');
} else {
  console.log('Negative');
}

// Loop
for (let i = 0; i < 5; i++) {
  console.log(i);
}


Explanation: Here, we use an if-else statement to determine if num is positive or negative, and a for loop to iterate from 0 to 4.


10.Template Literals:

Template literals provide a more readable and convenient syntax for string interpolation and multiline strings. Example:

let name = 'Alice';
console.log(`Hello, ${name}!`);


Explanation: Template literals allow us to embed variables within strings using `${}`(backticks`` and ${}) syntax.


Conclusion:

Understanding these fundamental JavaScript concepts lays a solid groundwork for mastering React. By grasping import/export, variables, functions, objects, and other concepts, developers can effectively leverage the power of JavaScript in React applications. As you embark on your journey with React, remember to revisit and reinforce these core concepts for a smoother learning experience. Happy coding.


External Links:

JS Documentation

Best tutorials and examples

Related Blogs

CodeWorx

© Copyright 2024 - Codeworx