ES6 with Javascript Concepts for React JS
Tags: javascript, react, webdev, beginners
Published: 2022-12-17 08:55:53

Hello Everyone today i will discuss few concepts which you should know before moving onto React JS.

Let's get started...

# ES6 Arrow Functions - 
* Arrow function allows you to create functions with cleaner code and more readable format.
* Arrow function can return a statement both implicitely or explicitely.
* Syntax for arrow function
```js
function regularFunction(num){
  return num
}

const arrowFunction = (num) => num

// React JS
const App = () => {
  const user = 'Guest';

  return (
    <><h1>Hello World</h1></>
  );
}

```

* As you can see it is small and more cleaner than regular function and they both are doing the same thing.For the full reference of Arrow function, you can check it here-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

# Template Literals - 
* It is used to embed js variables or expression inside strings in a more readable and cleaner way.

```js
const price = "12.00$";

// Normal string with double quotes
const normalString = "You bill is: " + price

// Template literal
const templateLiteral = `You bill is: ${price}`
```
* Template literal is used with backtick(key below Esc) and for putting the js expression we have to use this notation ${}, inside the curly bracket you can pass any js expression or variable.


# map, reduce and filter - 
* These are the array methods which is commonly used in React Components for manipulating the data inside the array and render the UI with that data.
```js
const data = [1,2,3,4,5,6,7,8];

// map method - Multiplying all the numbers by 2
const mapping = data.map(item => item*2)
// [2,4,6,8,10,12,14,16]

//filter method - Return all the numbers greater than 5
const filtering = data.filter(item => item > 5)
// [6,7,8]


// Reduce method - Going through all the numbers and adding them and return the sum of all 
const reducing = data.reduce((previous,current) => previous + current,0)
// 36
```
```js
// React JS
import React, { useState } from 'react';
const heroes = [
  {
    id: 100,
    name: 'Ironman',
    strength: 910,
  },
  {
    id: 101,
    name: 'Hulk',
    strength: 780,
  },
  {
    id: 102,
    name: 'Thor',
    strength: 10000,
  },
];
export function App(props) {
  const [superHeroes, setSuperHeroes] = useState(heroes);

  const combineStrength = heroes.reduce((previous,current) => previous + current.strength,0);

  return (
    <div className='App'>
      {superHeroes
        .filter(hero => hero.strength > 800)
        .map(hero => {
          return (
            <div key={hero.id}>
              <h1>Hello I am {hero.name}</h1>
            </div>
          );
        })}

        <p>Combine Strength: {combineStrength}</p>
    </div>
  );
}
```
* For more examples, visit this site - 
https://www.freecodecamp.org/news/javascript-map-reduce-and-filter-explained-with-examples/

# Ternary Operator - 
* It is used to check the single line conditionals and we can use it in place of you if-else statement as it is more readable and cleaner approach.
```js
const superhero = "Ironman";

// Ternary operator with ? and :
// If the condition is tru execute the statement after the ? and if it is false execute the state after :
const universe = superhero === "Ironman" ? "Marvel Universe" : "DC Universe";
// Marvel Universe

// React js
import React, { useState } from 'react';

export function App(props) {
  const [superHero, setSuperHero] = useState("Ironman");


  return (
    <div className='App'>
     <h1>{superHero === "Ironman" ? "Shoot Repulsors" : "Hulk Smash"}</h1>
    </div>
  );
}
```

* It is quite easy to use and is used to render the UI conditionally in React JS.

# Import and Export Statements - 
* It is also a feature of ES6 where we can create multiple js files as components and can import them somewhere else
* For importing the variable or function we have to use the "import" keyword and for exporting we have to use the "export" keyword.
```js
// Superhero.js
export const superhero = "Thor"

// App.js
import {superhero} from './Superhero'
```
* As you can see we have exported the variable superhero and imported it in other file, i have used the curly brackets because it is a named export , if is a default export , we can remove the curly brackets.
* These works same in React JS
* For full reference visit here - https://blog.yogeshchavan.dev/es6-import-and-export-cheatsheet

# async / await -
```js
// React JS
import React, { useState, useEffect } from 'react';

function App() {
  const [users, setUsers] = useState([]);

  const getUsers = async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos')
    if (!response.ok) {
      throw new Error('Data coud not be fetched!')
    } else {
      return response.json()
    }
  };
  useEffect(() => {
   getUsers().then(response => setUsers(response))
  }, []);

  if (!users) return <div>Loading...</div>;

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.title}</li>
      ))}
    </ul>
  );
}
export default App
```
* These are used to work with promises to call the api asynchronously, it is more readable than promises and can be used with fetch api or libraries like axios
* For full reference visit here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

# Higher Order Function -
* Higher order function return another function from inside or take another function as an argument.
```js
let debounce = (fn, delay) => {
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn();
    }, delay);
  };
};
```
* Here i have a created a debouncing function using higher order function.For full reference visit here - 
https://www.freecodecamp.org/news/higher-order-functions-in-javascript/#:~:text=Basically%2C%20a%20function%20which%20takes,a%20function%20from%20another%20function

# Object Destructuring - 
It is used to extract Array items or object property values and assigning them to variables.
```js
const array = ["Ironman","Thor","Hulk"]
const superHero = {
  Marvel:"Ironman",
  DC:"Batman"
}
// array destructuring - will assign the value of 3 items in the array to these variables
const [ironman,thor,hulk] = array

// Object destructuring
const {Marvel,DC} = superHero

// React JS hooks example
const [user,setUser] = useState("Username")
// user is the state which stores the value and setUser is the //callback which changes the state or say value of the user
```
* For full reference visit here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

# Spread and Rest operator
* They both have the same notation "...", three dots, but works differently
* In destructuring it works as rest operator spreading the remaining values of the array into single variable and inside functions or parameters it works as spread operator to spread the single value as array or object.
* They both work similar in React JS.
* For full reference visit here - 
https://www.freecodecamp.org/news/javascript-rest-vs-spread-operators/

THANK YOU FOR CHECKING THIS POST
You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/css-iswherehas-and-not-2afd

https://dev.to/shubhamtiwari909/theme-changer-with-html-and-css-only-4144

https://dev.to/shubhamtiwari909/swiperjs-3802

https://dev.to/shubhamtiwari909/going-deep-in-array-sort-js-2n90