In Today’s World, Web Development is an essential field to master in Computer Science and engineering. As the days go by, more and more web development related technologies are getting updated. JavaScript Has Become one of the core languages to be used in web development. With ES6 Announced, developers were introduced to some advanced new features which enhance code readability and improve performance. Anyone who wants to build an application using React, has to have proper knowledge about JavaScript ES6.
React is a JavaScript Library that is used to build user interfaces. React uses many ES6 features that make the developer familiar with those advancements. In this article, we will go through some must learn ES6 features that are very much crucial and vital for react developers to begin with. Exploring these Features can help the developer to improve their development process and coding practices.
1. Arrow Functions
You can write functions in your code more efficiently with Arrow Functions. Using it makes your overall code shorter as the syntax of arrow function is shorter than the actual function syntax.
Example:
const sum = (a,b) => a+b;
Here, sum is an arrow function taking two arguments a & b and returning their sum. Which is much shorter than the traditional syntax given below -
function sum(a,b) {
return a+b;
}
Arrow Functions in react are useful in class components because they automatically bind the value of “This” to the component instant. So it gets easy using them while defining event handlers.
2. Template Literals
Forget the traditional way to create strings. When using react, you have to load data dynamically more often within the strings and with the traditional approach of creating strings, that is quite a challenge!.
Template Literals allow you to insert any expression or variable directly within the string. You just have to wrap up the whole string with ` `(backticks) and put the variable inside this ${ }.
Example:
const name = 'John';
const message = `Hello, ${name}!`; // "Hello, John!"
Here we created a string using template literal (wrapped with backticks “) that has the value of the “name” variable. The “${name}” portion is replaced with the value of the “name” variable and gives you an output. It is Helpful if you want to create any dynamic content in JSX.
3. Object Destructuring
Object Destructuring is a very powerful feature provided by JavaScript in their ES6 update. It allows a developer to extract properties from an object or array and assign them to a separate variable. When you will work with props or state in React, This feature will be very useful for you to access values from props or state.
Example:
const user = { name: 'Jane', age: 25 };
const { name, age } = user;
// name = 'Jane', age = 25
4. Default Parameters
In a function, you can set a default value for a function’s arguments if no value is assigned. Sometimes you have to work with props that may not always be passed. At that time setting a default parameter is useful in React. It Ensures that the components will work even if some props are not passed.
Example:
const greet = (name = 'Guest') => `Hello, ${name}!`;
In this example, when you call “greet” without a name, it will have “guest” as its default value -
greet(); // Output : "Hello, Guest!"
When you provide a value to the argument by yourself, it will override the default value.
greet('Alice'); // Output: "Hello, Alice!"
5. Spread Operators
This is one of the most useful features of ES6. Spread Operator (…) is used to expand arrays or objects. In other words it copies an array while keeping the main array intact
Example:
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
Value of arr2 // [1, 2, 3, 4, 5]
Here, we used spread operator (...) to copu the elements of “arr1” into “arr2” and then added 4 and 5.
You could do it without the spread operator. But then you would have to concatenate the arrays manually which is not that much convenient.
6. Modules and Import/Exports
You can divide your codes into smaller pieces and reuse them into different files of your project. While working on a project we find that there are repetitive codes or components. Also there are portions of codes which can be used in a different file. You can export variables, functions or components from one file and import them into another file.
Example:
// In user.js
export const User = () => <div>User Component</div>;
// In another file
import { User } from './user';
This makes your code shorter, cleaner and reusable which is definitely a good practice for Developers.
7. Promises & Async/Await
It is an Object that represents the eventual completion or failure in an asynchronous operation This is a must learn topic from ES6 if you want to fetch data from an API in your React Application. Here async and await gives you a cleaner syntax for working with promises.
Example:
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Data fetched'), 1000);
});
};
Here “fetchData” Returns a Promise that resolves after 1 Second.
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
Here, “fetchData” is an async function that uses “await” to pause the execution until the data is fetched from the API. Its makes the code easier to read and manage.
8. Map, Filter & Reduce
These are some array methods you should be familiar with by now. You can use these methods to transform any data, to filter any list, or to reduce any array to a single value. In React, They are used a lot when rendering lists of components.
Example:
const numbers = [1, 2, 3, 4, 5, 6, 7];
// Step 1: Map each number to its square
const squares = numbers.map(num => num * num); // [1, 4, 9, 16, 25, 36, 49]
// Step 2: Filter squares that are greater than 20
const filteredSquares = squares.filter(square => square > 20); // [25, 36, 49]
// Step 3: Reduce the remaining squares to get their sum
const sumOfFilteredSquares = filteredSquares.reduce((acc, curr) => acc + curr, 0); // 25 + 36 + 49 = 110
console.log(sumOfFilteredSquares); // Output: 110
At Emperal Tech, We work with react regularly and implement these features to make our code professional and clean. If You want to be a React developer, You have to have a good grasp of JavaScript ES6 features. These features make your life easier as you will be able to write cleaner and more efficient code which is a necessary skill to be a senior developer.
By mastering these ES6 features you will not just be a professional react developer but also a more confident JavaScript developer overall. Take time, invest in yourself, learn these features, and make yourself a better developer and watch how these features make your code professional!