7 small Javascript concepts that can make a BIG difference

7 small Javascript concepts that can make a BIG difference

  1. Destructuring

    Destructuring in JavaScript allows you to extract specific values from objects or arrays and assign them to variables more concisely and conveniently.

Example-1

const person = {
  name: 'John',
  age: 30,
  location: 'New York'
};

const { name, age } = person;

console.log(name); // "John"
console.log(age); // 30

Example-2

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

const [first, second, ...rest] = numbers;

console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
  1. Rest parameters

    In JavaScript, rest parameters are a way to pass an indefinite number of arguments to a function as an array. This allows us to write functions that can accept any number of arguments, without having to specify them all individually.

    It's very much useful when you don't know how many arguments the user can pass in a function like in Example-1

Example-1

function sumAll(...numbers) {
  console.log(numbers)  // Output: [1,2,3,4]
  sum = 0
  for(i=0;i<numbers.length;i++){
    sum+=numbers[i]
  }
  console.log(sum)// Output: 10
}

sumAll(1, 2, 3, 4) // you can as many arguments as you like

Example-2

function demoFunc(number1, number2,...restNumbers) {
  console.log(number1,number2,restNumbers) // Output: 1 2 [3,4,5,6]
}

demoFunc(1, 2, 3, 4, 5, 6)
  1. Higher-Order Functions

    A higher-order function in JavaScript is a function that either takes another function as an argument or returns a function as its result.

Example-1

function sayHello() {
  console.log("Hello!");
}

function runFunction(func) {
  // running the function that is sent in the parameter(In our case sayHello)
  func();    // Output : Hello!
}

runFunction(sayHello);   // passing 'sayHello' function as a argument

Example-2

function createMultiplier(num) {
  return function(x) {
    return num * x;
  };
}

const double = createMultiplier(2);  
// Above code returns a function and assign that function to 'double'
// It's like saying 
// double = function(x){
//  return 2*x
// }

const triple = createMultiplier(3);

console.log(double(5)); // Output: 10
console.log(triple(5)); // Output: 15
  1. Spread Operator

    As the name suggests spread operator is a way to spread the elements of an array or an object into a new array or object.

    It is represented by three dots ...

Example-1: Spread Operator with arrays

const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];  // we are spreading the 'numbers' array
// It's like dismantling the array and re-assembling it again with added elements

console.log(newNumbers); // Output: [1, 2, 3, 4, 5]

Example-2: Spread Operator with objects

const person = {
  name: "John",
  age: 30,
};

const newPerson = {
  ...person,          // we are spreading the 'person' object
  email: "john@example.com",
};

console.log(newPerson); // Output: { name: 'John', age: 30, email: 'john@example.com'}
  1. Map/Filter/Reduce

    The map() method creates a new array by applying a function to each element in the original array.

    The filter() method creates a new array containing all elements that pass a given condition. The new array has a length that is less than or equal to the original array.

    The reduce() method applies a function to each element in the array to reduce the array to a single value.

Example:

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

// map function
const output1 = numbers.map((num) =>{ 
  return num * 2       // each number is multiplied by 2 and then return in a new array
});
console.log(output1);  // Output: [2, 4, 6, 8]

//filter function
const output2 = numbers.filter((num)=>{
  return num % 2 === 0  // Only those numbers are returned that follow the given condition
                        // In this case condition is `num % 2===0`
})
console.log(output2);  // Output: [2, 4]

//reduce function
const output3 = numbers.reduce((accumulator,num)=>{
  return accumulator+num  // reduce function reduce the array into a single value
                          // In this case return returns the sum of all numbers
},0)                      // 0 is the initial value of accumulator
console.log(output3);     // Output: [2, 4]
  1. Promises

    Promises are a way to handle asynchronous code that involves operations that may take some time to complete, such as fetching data from an API or reading a file from disk. They allow you to write code that waits for an operation to complete before continuing execution.

Example:

function getData() {
  return new Promise((resolve, reject) => {
    // Make an API call or perform other asynchronous operation
    // If successful, call resolve() with the data
    // If there's an error, call reject() with the error
  });
}

getData()
  .then(data => console.log(data))  // if promises resolves(success), cose inside then is run
  .catch(error => console.error(error));  // if promises rejects(failure), cose inside catch is run
  1. Async/Await

    async/await is a way of writing asynchronous code in a more synchronous style, making it easier to read and understand. It uses the async keyword to define a function that returns a promise, and the await keyword to wait for the promise to resolve before continuing execution.

    This is a newer way to handle asynchronous operations that is more concise and readable than using Promises.

Example:

async function getData() {
  try {
    // asynchronously do something that takes time like API call or some other processing
    // 'await' ensures that code execution won't move forward unless the API call in fulfilled
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

getData();

Conclusion

Hope you guys liked the post, follow for more such blogs and content. Also check out my previous blogs here: https://yashnirmal.hashnode.dev/

Did you find this article valuable?

Support Yash Nirmal by becoming a sponsor. Any amount is appreciated!