JavaScript concepts for React JS ⚛️

·

4 min read

JavaScript concepts for React JS ⚛️

Introduction

In this blog, we will see the important JavaScript concepts before jumping into ReactJS.

1. Variable declaration

The variables can be declared using var, let and const keywords.

var: Once a variable is declared using the ‘var’ keyword, it can be updated and reassigned in the scope many times.

let: Once a variable is created using the ‘let’ keyword, it can be updated but cannot be redeclared.

const: Once a variable is created with the ‘const’ keyword, it can neither be updated, nor redeclared.

// var example
var x = 10;
console.log(x); // 10
x = 20;
console.log(x); // 20

// let example
let a = 10;
console.log(a); // 10
a = 20; // error

// const example
const PI = 3.14;
console.log(PI);
const z; // error
PI = 3.144; // error

2. Objects

Imagine an object as a box. You can label the box (the key) and put things inside (the value). You can have different labeled compartments (multiple key-value pairs) within the box to organize the contents.

// Simple Object Example
const Person = {
    name: "Rd",
    age: 20,
    city: "Delhi"
};

// Accessing the properties
console.log(Person.name); // Output: Rd
console.log(Person["age"]); // Output: 20
// Object with method
const Person = {
    name: "Rd",
    age: 20,
    city: "Delhi",
    greeting: function(){
        console.log("Hello!");
    }
};

Person.greeting();

3. Arrow Functions

Arrow functions are a concise and a convenient way to write JavaScript functions.

Syntax:

const <function_name> = (arguements) =>{
    function_statements;
    return <return_statement>;
};

There are two ways to write arrow functions:

a. Implicit Return

const greet = (name) => 'Hello, ${name}!';

b. Explicit Return

const multiply = (x, y) => {
  const result = x * y;
  return result;
};

4. Array methods

Map: Creates a new array with the results of calling a provided function on every element in the original array.

const users = [
  { name: "Rd", age: 20 },
  { name: "Rupa", age: 25 },
];

const greetings = users.map((user) => `Hello, ${user.name}!`);

console.log(greetings); 
// ["Hello, Rd!", "Hello, Rupa!"]

Filter: Creates a new array with elements that pass a test implemented by the provided function.

const products = [
  { name: "Rupa", price: 20 },
  { name: "R", price: 15 },
  { name: "Rd", price: 50 },
];

const expensiveProducts = products.filter((product) => product.price > 25);

console.log(expensiveProducts); // Output: [{ name: "Rd", price: 50 }]

Reduce: Applies a function against an accumulator and each element in the array to reduce it to a single value.

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

const sum = numbers.reduce((a, b) => a + b, 0);

console.log(sum); // Output: 15

5. Promises

In JavaScript, a promise represents the eventual outcome of an asynchronous operation like fetching data from an API or reading a file.

// Syntax
let myPromise = new Promise((myResolve, myReject) => {
    myResolve(); // when successfull
    myReject(); // when error
});

myPromise.then(
    function(value) {
        // when successfull
    },
    function(error){
        // when error
    }
);
// Example
function getUser(userId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const user = {
        id: userId,
        name: "Alice",
      };
      resolve(user);
    }, 1000);
  });
}

getUser(123)
  .then(user => console.log(user.name)) // Output: "Alice" after 1 second delay
  .catch(error => console.error(error));

6. Async / wait

Async/await allows you to write asynchronous code in a way that resembles synchronous code. It uses the async and await keywords to achieve this.

async - Keyword to declare the function as asynchronous

await - Keyword to pauses the execution until the promise resolves

// Example
async function fetchData(){
    const response = await fetch('https://api');
    const data = await response.json();
    return data;
}

// Function call
fetchData()
    .then(data => console.log(data));
    .catch(error => console.log(error));

Async functions can be used with try...catch to handle potential errors from asynchronous operations like fetching data or performing file operations.

// Example
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

fetchData()
  .then(data => console.log(data))
  .catch(error => console.error(error));

7. Spread operator

The spread operator can be used to create copies of arrays, concatenate arrays, or merge elements into new arrays.

// Example: Copying arrays
const numbers = [1,2,3];
const copy_numbers = [...numbers];
console.log(copy_numbers); // 1, 2, 3

// Example: Concatenating Arrays
const fruits = ["apple", "banana"];
const veggies = ["carrot", "broccoli"];
const produce = [...fruits, ...veggies];
console.log(produce); 
// ["apple", "banana", "carrot", "broccoli"]

// Example: Merging into a new array
const colors = ["red", "green"];
const moreColors = ["blue", "yellow"];
const allColors = [...colors, "purple", ...moreColors];
// ["red", "green", "purple", "blue", "yellow"]

The spread operator can also be used for objects and strings.

Conclusion

These are the seven main important JavaScript concepts to know before learning ReactJS.