DEV Community

Cover image for ES6 with Javascript Concepts for React JS
Shubham Tiwari
Shubham Tiwari

Posted on • Edited on

ES6 with Javascript Concepts for React JS

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
function regularFunction(num){
  return num
}

const arrowFunction = (num) => num

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

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

Enter fullscreen mode Exit fullscreen mode

Template Literals -

  • It is used to embed js variables or expression inside strings in a more readable and cleaner way.
const price = "12.00$";

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

// Template literal
const templateLiteral = `You bill is: ${price}`
Enter fullscreen mode Exit fullscreen mode
  • 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.
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
Enter fullscreen mode Exit fullscreen mode
// 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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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.
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>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • 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.
// Superhero.js
export const superhero = "Thor"

// App.js
import {superhero} from './Superhero'
Enter fullscreen mode Exit fullscreen mode
  • 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 -

// 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
Enter fullscreen mode Exit fullscreen mode

Higher Order Function -

  • Higher order function return another function from inside or take another function as an argument.
let debounce = (fn, delay) => {
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn();
    }, delay);
  };
};
Enter fullscreen mode Exit fullscreen mode

Object Destructuring -

It is used to extract Array items or object property values and assigning them to variables.

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (12)

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited
function regularFunction(num){
  return num
}

const arrowFunction = (num) => num
Enter fullscreen mode Exit fullscreen mode

These two things are not the same, in some cases the differences may not matter, but:

  • arrow functions have the this of the enclosing scope in which they are defined meaning they can't be used in prototypes or classes.
  • arrow functions are not hoisted meaning they must exist in the source code before their use, this can cause weird ordering issues for self referencing pairs of functions and means the purpose of your code will come after all of the utility functions it uses.

Arrow functions are incredibly useful, but they are also not actually shorter to declare if they are multiline and you are declaring the function as a variable to be called. However, you could define a map or a filter function with the whole function style shenanigans, if fact you used to have to, now that's nasty and arrow functions really shine in this area.

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Actually I wrote they are doing the same thing , not they are same thing, what i meant is they are returning the number in the parameters
That's why i attached a link for the complete reference of the topic

Collapse
 
jonrandy profile image
Jon Randy 🎖️

A lot of stuff here is not related to ES6 at all

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Which one's?

Collapse
 
brense profile image
Rense Bakker

map, filter, reduce is ES5. Ternary operator has been there from the start.

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Yeah but we can use these with ES6 features for more shorted code

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Well, if we want shorter code using ES6 features, we could rewrite your debounce:

const debounce = (fn, delay) => {
  let timer
  return () => {
    clearTimeout(timer)
    timer = setTimeout(fn, delay)
  }
}
Enter fullscreen mode Exit fullscreen mode

I'm not entirely sure why you wrapped fn in another function in the original?

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Yeah The title should be ES6 combined with Javascript

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Higher order functions are just a programming concept made possible in languages where functions are treated as values, as JS does and always has.

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

But we can combine higher order function with ES6 features to make it more shorter that's i put it there

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

I think I should say ES6 with javascript combine

Collapse
 
codingjlu profile image
codingjlu

You might want to clarify on the React part. I think you should add relevant React snippets if you want to name your posts as so.