10 Essential JavaScript Concepts Every React Developer Must Master in 2024
PRANKUR PANDEY
Posted on May 12, 2022
Web development has revolutionized the world and has become a vital component of businesses across the globe. In the world of web development, JavaScript or JS is the most popular language, powering the web. When I started with web development two months ago, I realized that most web development tools rely on JavaScript. Being from a Java coding background, I expected JavaScript to be the same, but I soon realized that it is quite different, with some concepts being similar but with additional limitations and features.
This article is all about my experience with JS and its most important ES6 concept, which will help you in learning React JS. Before we delve into that, let's take a look at some important facts about JS:
JS is an Object-Oriented Programming Language that is used to program the web for browsers.
It is a case-sensitive language, which means that 'ABC' and 'abc' are different things.
JS has support in almost all operating systems and web browsers.
JS is versatile and allows developers to accomplish almost anything they want on the web, with the support of a large community.
It is an interpreted language that executes one command at a time.
Now, let's talk about the backbone of JS: ES6. ES6 stands for the 6th revision of ECMAScript and introduces several new features that have revolutionized the way we write JavaScript. Some of these features include:
- Var, Let, and Const
- Template Strings
- Fat Arrow Functions
- Functions with Default Parameters
- Array and Object Destructuring
- Rest and Spread Operators
- Modules
- Promises
- Map(), Filter(), and Reduce()
Before we begin, it is essential to understand two crucial concepts: block and scope. In JS, a block refers to a group of statements enclosed in brackets that form a block. The scope, on the other hand, refers to the opportunity to perform tasks within the area between the block's starting and ending points.
Before we start its time to understand two important things
what is a block?
In JS block means many js statements formed in a group enclosed in brackets and it forms a block, now come to the scope
what is the scope?
In general English scope means the chance or opportunity to do something, so this same theory applies to JS scope too.
Scope gives you the open opportunity to perform the operations inside the block.
Look at the below image, in this image we have brackets, from where the brackets start it will be the starting point of the block, and where the block ends it is the endpoint of the block.
The area between block starts & ends is the area of scope where we will get the opportunity to perform tasks.
{ // block starts
// scope area
} // block ends
When ES6 come into the picture there were many new changes, 'let, const & var' was one of that changes, it gives you more access to manage and use data and its operations.
Before understanding this first understand this :
Function Scope: When a variable is declared inside a function, it is only accessible within that function and cannot be used outside that function.
//Function scoped
function myFunc() {
var functionScoped = "I am available inside this function";
console.log(functionScoped);
}
myFunc();
// I am available inside this function
console.log(functionScoped);
// ReferenceError: functionScoped is not defined
Block Scope: A variable when declared inside the if or switch conditions or inside for or while loops, are accessible within that particular condition or loop.
To be concise the variables declared inside the curly braces are called within block scope.
//for loop is block scoped
for (var i = 0; i < 10; i++) {
var iAmInside = "I am available outside of the loop";
}
console.log(iAmInside);
// I am available outside of the loop
//block scope
if (true) {
var inside = "Inside";
}
console.log(inside);
// Inside
var ,let & const :
When ES6 was introduced, it brought many new changes, one of which was the introduction of 'let, const & var,' which offers more options to manage and use data and its operations. It's essential to understand function scope and block scope when working with these features. A variable declared using the var keyword has function scope, meaning it is accessible throughout the function, while variables declared using let and const are block-scoped, which means they are accessible within that particular block.
Var is called a function scope that is if a variable is declared using the var keyword it will be accessible throughout the function.
let & const are also called block scope that is they are accessible within that particular block.
Here let is used for a variable that can be changed as we proceed through the program whereas const is used for a variable that doesn’t change till the program ends, that is it remains constant throughout the program.
// a fucntion with var,let and const
function varLetConst() {
if (true) {
var a = 10;
let b = 20;
const c = 30;
console.log(a); //10
console.log(b); //20
console.log(c); //30
}
console.log("outside if statement"); //outside if statement
console.log(a); //10
console.log(b); //error
console.log(c); //error
}
varLetConst()
Template Strings
Template literals are a type of string literal that allow for embedded expressions. They provide a way to format strings in JavaScript that is more efficient than the manual formatting syntax used in ES5. In ES6, instead of using the standard single or double quotes, template literals use back-ticks. By using a new syntax ${PARAMETER} inside the back-ticked string, variable values can be defined. In contrast to ES5, where string concatenation was a laborious process, in ES6, the same output can be achieved with ease using template literals. For example, in ES5, we would have to break the strings into pieces, but with ES6, we can achieve the same result without the need for additional tedious work.
In ES5, we have to break strings like below.
var name = 'Your name is ' + firstName + ' ' + lastName //ES5
with ES6 we can achieve the same output without doing more tedious work
var name = `Your name is ${firstName} ${lastName}//ES6
Fat arrow functions
Fat arrow function or arrow functions are the most amazing this of es6 because it systematically reduces the code size without compromising the code quality and features.
Arrow functions as it sounds is the new syntax (=>) of declaring a function. But it behaves differently from the traditional functions of Javascript.
//without arrow function
function add(a, b) {
return a + b;
}
add(5, 10);
//with arrow function
const add = (a, b) => {
return a + b;
}
add(5, 10)
Function with default parameters
If you have understood the functions then you have the idea about it, in this, we have the option to make it with parameters like if there is a function called demo function (), so we can pass at least two parameters then our functions will be like demoFunction (a,b) where a and b are parameters.
Now when we will be calling this then we have to provide the parameter values otherwise it will throw the error, and here the noted thing is that we can't just pass one value we have to give both the values.
Now, what to do?
here the default parameter comes to rescue you, by using this you can declare the default values to your arguments so that when the function is invoked and you didn't pass any value then also your function will work.
//without default parameters
const add = (a, b) => {
return a + b;
}
add(5) //error
//with default parameters
const add = (a, b = 10) => {
return a + b;
}
add(5) // 15
Array and Object Destructuring
Destructuring is a new feature introduced in ES6 to unpack values from arrays or properties from an object. It helps in improving the readability and performance of our code.
//before es6
// Example 1 - Object Destructuring
var user = {
name: 'Deepak',
username: 'dipakkr',
password: 12345
}
const name = user.name; // Deepak
const username = user.username; // dipakkr
const password = user.password // 12345
//Example 2 - Array Destructing
const fruits = ["apple", "mango", "banana", "grapes"];
const fruit1 = fruits[0];
const fruit2 = fruits[1];
const fruit3 = fruits[2];
//after es6
// Example 1 - Object Destructuring
var user = {
name: 'Deepak',
username: 'dipakkr',
password: 12345
}
const {
name,
username,
password
} = user;
console.log(name);
console.log(username);
console.log(password);
//Example 2 - Array Destructing
const fruits = ["apple", "mango", "banana", "grapes"];
const [fruit1, fruit2, fruit3] = fruits;
console.log(fruit1); // apple
console.log(fruit2); // mango
console.log(fruit3); // banana
Rest and spread operators
The (...) is the spread syntax that allows you to specify an array that should be split and have its items passed in as separate arguments to a function.
it can be used in 2 ways, one as Spread Operator and other as Rest Parameter
Rest parameter
- It collects all the remaining elements into an array.
- Rest Parameter can collect any number of arguments into an array.
-
Rest Parameter has to be the last argument.
//Before ES6 let arr = [1, 2, 3, 4, 5]; console.log(Math.max.apply(null, arr)); //After ES6 let arr = [1, 2, 3, 4, 5]; console.log(Math.max(...arr)); // 5 ```
Spread operator
The spread syntax can be used when all elements from an object or array need to be included in a list of some kind.
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
Modules
Modules give you the access to separate the code in another file and when required we can import it from that file; by doing this we can manage the code and its files easily. The real power of modules is the ability to export and import only bindings you need, rather than whole code.
export const API_URL = 'http://localhost:8080';
export const MAX_THREADS = 8;
import {MAX_THREADS,API_URL} from './constants.js';
console.log(MAX_THREADS);
console.log(API_URL);
Promises
Consider a scenario where
I will give the pen when I will get it from the store when I say this to someone so I am giving a promise to someone that when I will get the pen from the store I will give this to you for sure, now three conditions can occur
- I will get the pen for sure, which means I am successful in delivering my promise
- I will not get the pen, which means I am unsuccessful in delivering my promise
- I have seen the pen has arrived at the store but I haven't gotten it at my hands, It's pending, it can either be a success or reject This is the same story of promises
According to MDN:-
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
A promise represents whether asynchronous code completed or failed and eventually returned its resulting value.
A Promise has three states.
Pending: Initial state, neither fulfilled nor rejected.
Fulfilled: It means that the operation was completed.
Rejected: It means that the operation failed.
const count = true;
let countValue = new Promise(function (resolve, reject) {
if (count) {
resolve("There is a count value.");
} else {
reject("There is no count value");
}
});
map(),filter() & Reduce()
Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function.
Map :
The map() method is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]
Filter :
The filter() method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]
Reduce:
The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function (result, item) {
return result + item;
}, 0);
console.log(sum); // 10
Conclusion :
In conclusion, ES6 has introduced many new features that make writing JavaScript more comfortable and enjoyable. These features are essential to understand if you want to master web development, particularly React JS. I hope this article has been helpful in your journey to becoming a JavaScript expert.if you find it useful share your views in comments .
So guys this is all end from my side and if you find this article useful then do like and share it and connect me here
Posted on May 12, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.