Crucial Javascript Concepts before Learning ReactJs
Basics every beginner needs to Master to Maximize the Power of ReactJs
Introduction
React is a great and popular Javascript library for building user interfaces. It is known for its virtual DOM, reactivity, and component-based attributes. You must first comprehend the basic JavaScript principles and methods if you wish to master React or any other JavaScript framework.
It might be intimidating to learn ReactJS, especially if you don’t know JavaScript. However, to work with ReactJS effectively, you need to understand some of the core concepts of JavaScript. In this article, we’re going to cover some of the most important JavaScript concepts that you should learn before trying to learn ReactJS.
Logical Operators
Logical Operators are used in determining the logic between variables or values. Javascript has three logical operators: && (AND), || (OR), and ! (NOT).
These operators allow you to compare variables and return the boolean values true or false, allowing you to base choices or actions on the comparison’s outcome. Moreover, they may be applied to values of any data type.
&& (AND)
The && operator returns true if both operands are true. It is used to combine two conditions that must both be true for the statement to be true.
Javascript Example:
let a = 5;
let b = 4;
if (a > 0 && b > 0) {
console.log (Both operands are true') ;
}
Output: Both operands are true
ReactJs Example:
const MyComponent = () => {
const isActive = true;
const isLoggedIn = false;
return (
<div>
{isActive && isLoggedIn && <div>Welcome!</div>}
</div>
);
};
In the above example, the div will only be rendered if both isActive and isLoggedIn are true. If either one of them is false, then the div will not be rendered.
|| (OR)
The || (OR) operator works similarly, but this time it only needs one of the conditions to be true for the code to be rendered. It returns true if one of the operands is true
Javascript Example:
let a = 5;
let b = 0;
if (a > 0 || b > 0) {
console.log('One of the operands is true');
}
Output: One of the operands is true
ReactJs Example:
const MyComponent = () => {
const isActive = true;
const isLoggedIn = false;
return (
<div>
{isActive || isLoggedIn && <div>Welcome!</div>}
</div>
);
};
In the above example, the div will be rendered if either isActive or isLoggedIn is true.
! (NOT)
The! (not) operator reverses the logical state of its operand, or we can say it reverses the truthiness of a value.
Javascript Example:
let a = 5;
if (!a) {
console.log('a is not true');
}
Output: a is not true
ReactJs Example:
const MyComponent = () => {
const isActive = true;
return (
<div>
{!isActive && <div>Welcome!</div>}
</div>
);
};
In the example above, the div will only be rendered if isActive is false.
Nullish Coalescing Operator
The nullish coalescing operator, which is a logical operator denoted by two question marks (?? ), was introduced with ES2020. It is a feature in JavaScript that allows you to provide a default value for a variable if the value is null or undefined. It can be used in ReactJS to simplify the code and reduce the risk of errors.
In ReactJS, Nullish Coalescing may be used to establish a prop’s default value if one is not provided. For instance, you may use Nullish Coalescing to create a default value if a component’s “name” argument isn’t handed in.
ReactJs Example:
const MyComponent = ({ name = 'John Doe' }) => {
return <div>{name}</div>;
};
In this example, if the name prop is not passed in, the default value of "John Doe" will be used.
Rest and Spread Operators
Three dots (...) are used by the spread and rest operators in JavaScript.
Rest operator
The Rest Operator merges a list of function arguments into an array. While the syntax of the rest operator is the same as that of the spread operator, their place of use makes all the difference.
Javascript Example:
const sum = (...nums) => nums.reduce((total, currVal) => total + currVal);
console.log(sum(1,2,3,4,5,6,7));
Output: 28
ReactJs Example:
const MyComponent = (props) => {
const { first, second, ...rest } = props;
return (
<div>
<p>First prop: {first}</p>
<p>Second prop: {second}</p>
<div>
<p>Remaining props:</p>
{rest.map((prop, index) => (
<div key={index}>{prop}</div>
))}
</div>
</div>
);
};
Spread operator
The Spread Operator allows an iterable item (e.g., an array) to be extracted into its parts and plugged into places that expect individual elements. With this syntax, you can split up object properties or array elements.
Javascript Example:
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);
Output: [1,2,3,4,5,6]
ReactJs Example:
const MyComponent = (props) => {
const { first, second } = props;
return (
<div>
<p>First prop: {first}</p>
<p>Second prop: {second}</p>
<div>
<p>Remaining elements:</p>
{[...props.elements].map((element, index) => (
<div key={index}>{element}</div>
))}
</div>
</div>
);
};
Destructuring
JavaScript has a feature called destructuring that makes it simple to take values out of objects or arrays and assign them to variables. It enables you to write less code and create easier-to-read code.
Object Destructuring
Object destructuring is a way of extracting data from an object and assigning it to variables. This is useful for extracting data from objects when you need to use it in multiple places.
Javascript Example:
const person = {
name: 'John',
age: 25,
address: {
city: 'New York',
state: 'NY'
}
};
let {name, age, address: {city, state}} = person;
console.log(name); // 'John'
console.log(age); // 25
console.log(city); // 'New York'
console.log(state); // 'NY'
ReactJs Example:
- Destructuring a Props Object:
const MyComponent = ({ title, message, color }) => {
return (
<div>
<h1>{title}</h1>
<p style={{ color }}>{message}</p>
</div>
);
};
export default MyComponent;
// The component can then be used like this:
<MyComponent
title="Hello World"
message="This is a message"
color="red"
/>
- Destructuring a State Object:
const MyComponent = ({ title, message, color }) => {
const [state, setState] = useState({
name: 'John Doe',
age: 30,
location: 'New York'
});
// Destructuring state
const { name, age, location } = state;
return (
<div>
<h1>{title}</h1>
<p style={{ color }}>{message}</p>
<p>Name: {name}</p>
<p>Age: {age}</p>
<p>Location: {location}</p>
</div>
);
};
export default MyComponent;
Array Destructuring
Array Destructuring is a method of extracting data from an array and assigning it to individual variables. It is a convenient way to extract multiple values from an array and assign them to separate variables.
Javascript Example:
let array = [1, 2, 3];
// Destructuring
let [a, b, c] = array;
console.log(a); // outputs 1
console.log(b); // outputs 2
console.log(c); // outputs 3
ReactJs Example:
const arr = [1,2,3,4,5];
const Component = () => {
const [a, b, c, d, e] = arr;
// a = 1, b = 2, c = 3, d = 4, e = 5
return (
<div>
a: {a}<br />
b: {b}<br />
c: {c}<br />
d: {d}<br />
e: {e}
</div>
);
}
Arrow Functions
The ECMAScript standard, often known as ES6, was updated in 2015 and brought a few new capabilities to JavaScript. One of them is a function of an Arrow Function.
They are a type of function expression that is shorter and more concise than a traditional function expression. Arrow functions allow you to write shorter, more concise functions without sacrificing readability. An arrow function expression has a shorter syntax than a regular function expression and does not have its own this, arguments, super, or new.target.
They come in handy when you need to pass a function, usually an anonymous function, as an argument to another function (as in the case of higher-order functions).
Javascript Example:
// Traditional Function
function add(a, b) {
return a + b;
}
// Arrow Function
const add = (a, b) => a + b;
ReactJs Example:
import React from 'react';
const MyComponent = () => {
const myList = [1,2,3,4,5];
return (
<div>
{myList.map((item) => {
return (
<div key={item}>{item}</div>
)
})}
</div>
)
}
export default MyComponent;
Conditional Ternary Operator
In JavaScript, a conditional ternary operator is a particular kind of if/else statement shortcut. The rapid evaluation of a condition and return of one of two values is possible.
The syntax is as follows:
condition ? value1 : value2;
If the condition evaluates to true, value1 is returned; otherwise, value2 is returned.
Javascript Example:
// using if-else statement
let result = 5;
if (result > 5) {
console.log("Number is greater than 5");
} else {
console.log("Number is less than 5");
}
// using ternary operator
let result = (number > 5) ? "Number is greater than 5" : "Number is less than 5";
console.log(result);
ReactJs Example:
const App = () => {
const userName = 'John';
return (
<div>
<h1>Hello { userName ? userName : 'Guest' }!</h1>
</div>
);
}
In this example, the ternary operator is checking the value of the userName variable. If userName is true, it will render the user’s name. Otherwise, it will render ‘Guest’.
Also, the ternary operator in React may be used to conditionally render components based on whether or not a condition is satisfied.
const App = () => {
const isLoggedIn = false;
return (
<div>
{ isLoggedIn ? <LoggedIn /> : <LoggedOut /> }
</div>
);
}
In this example, the ternary operator is checking the value of the isLoggedIn variable. If isLoggedIn is true, it will render the <LoggedIn /> component. Otherwise, it will render the <LoggedOut /> component.
Callback Functions
A function passed as an argument to another function is called a callback if the function invokes the argument at a later time. A lot of times it happens after performing asynchronous tasks like retrieving data from a remote endpoint, handling events, etc. The parent function or the function that invokes the callback is referred to as a higher-order function (HOF).
Javascript Example:
// Create a function that takes two numbers as arguments
const addFunction = (num1, num2) => {
console.log(num1 + num2);
};
// Create a second function that takes two numbers and a callback
const myOtherFunction2 = (num1, num2, callback) => {
// Execute the callback
callback(num1, num2);
};
// Call the second function, passing the first function as a callback
myOtherFunction2(2, 3, addFunction);
// Output: 5
ReactJs Example:
For example, let’s say we have a parent component called Parent.js and a child component called Child.js.
Parent.js
import React, { useState } from 'react';
export const Parent = () => {
const [message, setMessage] = useState('');
const handleClick = (text) => {
setMessage(text);
}
return (
<div>
<Child onClick={handleClick} />
<p>{message}</p>
</div>
);
};
Child.js
import React from 'react';
export const Child = (props) => {
return (
<button onClick={() => props.onClick('Hello World')}>
Click me
</button>
);
};
In this example, we have a Parent component that contains a state called message and a function called handleClick. We also have a Child component, which has a button that, when clicked, triggers handleClick from the Parent component with the text “Hello World” as an argument. handleClick then updates the message state, which is then displayed in the Parent component.
Also, several built-in JavaScript functions, including setTimout, setInterval, addEventListener, and array methods like search, filter, some, map, forEach, etc., accept a callback as input.
Template literals
Template literals are strings that are encapsulated in backticks (‘) rather than single or double quotes. They permit the incorporation of expressions, variables, and even functions.
Javascript Example:
let userName = 'Bob';
let greetingMessage = `Hello ${userName}!`;
console.log(greetingMessage); // Output: "Hello Bob!"
ReactJs Example:
const MyComponent = () => {
const data = {
name: 'John',
age: 23
};
return (
<div>
<p>My name is `${data.name}` and I am `${data.age}` years old.</p>
</div>
)
}
Switch statement
A switch statement is a form of control flow statement used to manage how programs are executed in JavaScript. It operates by comparing a statement to a list of potential situations. If a match is discovered, the corresponding code block is run.
Javascript Example:
let player = 'X';
switch (player) {
case 'X':
console.log('Player X is the winner!');
break;
case 'O':
console.log('Player O is the winner!');
break;
default:
console.log('It\'s a tie!');
break;
}
ReactJs Example:
It can also be useful when you need to choose a route for a certain value.
const App = () => {
const [value, setValue] = useState('A');
const handleChange = (e) => {
setValue(e.target.value);
};
switch (value) {
case 'A':
return (
<div>
<h1>Value is A</h1>
<select onChange={handleChange}>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
);
case 'B':
return (
<div>
<h1>Value is B</h1>
<select onChange={handleChange}>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
);
case 'C':
return (
<div>
<h1>Value is C</h1>
<select onChange={handleChange}>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
);
default:
return (
<div>
<h1>No value selected</h1>
<select onChange={handleChange}>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
);
}
};
export default App;
Promises
Promises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They are "thenable,” which means that they have a then() method that can be used to register callbacks that will be invoked when the Promise is resolved or rejected.
Javascript Example:
let myPromise = new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open('GET', 'https://example.com/api/data');
request.onload = () => {
if(request.status === 200){
// success
resolve(request.response);
} else {
// fail
reject(Error(request.statusText));
}
};
request.onerror = () => {
reject(Error('Network Error'));
};
request.send();
});
myPromise.then((response) => {
// do something with the response
}, (error) => {
// handle the error
});
ReactJs Example:
const MyComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://example.com/api');
const data = await response.json();
setData(data);
}
const promise = new Promise((resolve, reject) => {
fetchData().then(resolve).catch(reject);
});
promise
.then(() => console.log('Fetching data successful!'))
.catch(err => console.error(err));
}, []);
return (
<div>
{data && <p>Data loaded successfully!</p>}
</div>
);
}
The code above is a ReactJS functional component that uses a Promise object to handle an asynchronous operation. The component has a useEffect hook that uses the fetch API to get data from a remote API. After the fetch operation is complete, the response is assigned to the data state variable.
When the component is mounted, a new Promise object is created with the Promise constructor and passed a function that takes two parameters: resolve and reject. The fetchData function is then called within the promise function, and the resolve and reject functions are called depending on whether the fetch operation was successful.
If the Promise is resolved, the then() function will be called, which prints a message to the console. If the Promise is rejected, the catch() function will be called, which prints an error message to the console. Finally, the component renders the data state variable if it is not null.
Async/Await
Async/Await is a new feature of JavaScript that makes writing asynchronous code easier and more efficient. It allows developers to write code that is synchronous but still runs asynchronously. It is a combination of two keywords: async and await. Async allows the code to be written as if it were synchronous, and Await allows the code to wait for a promise to be resolved or rejected.
We can simply say it is a shorthand for promises, which allow developers to write code that is easier to read and debug.
Javascript Example:
async function getData() {
const response = await fetch('https://example.com/data');
constant data = await response. json();
console.log(data);
}
ReactJs Example:
const MyComponent = () => {
const getData = async () => {
const response = await fetch('https://example.com/data');
const jsonData = await response.json();
return jsonData;
}
useEffect(() => {
const data = getData();
// do something with the data
}, []);
return (
<div>
{/* Component code here */}
</div>
);
}
This code sample uses the useEffect hook to call the getData function asynchronously. The getData function uses the fetch API to make a network request and returns the response as JSON. The data received is then used to update the component state.
Array Methods
Array Methods in JavaScript are a group of methods that let you work with, navigate, and sort arrays. They are an effective tool for any developer and may be used for several activities, such as sorting, filtering, converting, and searching through data. Arrays are one of JavaScript’s most important and frequently used data structures.
map()
This method creates a new array by applying a function to each element of an existing array. Using the map() method, you can iterate over each item in an array and return a new array with the modified values. For example, let’s say you have an array of numbers and you want to double them and return a new array.
Javascript Example:
// JavaScript code sample
const numbers = [1, 2, 3, 4, 5];
// Create a new array with each number multiplied by 2
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
ReactJs Example:
//Functional component
const DoubleArray = ({ items }) => {
return items.map(item => item * 2);
};
//Using the DoubleArray component
const numbers = [1, 2, 3, 4, 5];
<DoubleArray items={numbers} />
//Output: [2, 4, 6, 8, 10]
filter()
This method creates a new array by filtering out elements from an existing array that don’t pass a given test. The filter() method can be used to filter an array by a given condition. For example, let’s say you have an array of numbers and you want to filter out any numbers that are greater than 5.
Javascript Example:
// JavaScript code sample
const numbers = [1, 2, 3, 4, 5];
// Create a new array with only even numbers
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
ReactJs Example:
//Functional component
const FilterArray = ({ items }) => {
return items. filter(item => item <= 5);
};
//Using the FilterArray component
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
<FilterArray items={numbers} />
//Output: [1, 2, 3, 4, 5]
reduce()
This method applies a function to each element of an array, accumulating the result into a single value. The reduce() method can be used to reduce a given array to a single value. For example, let’s say you have an array of numbers and you want to add them all up and return the sum.
Javascript Example:
// JavaScript code sample
const numbers = [1, 2, 3, 4, 5];
// Create a new variable with the sum of all the numbers
const sum = numbers. reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
ReactJs Example:
//Functional component
const ReduceArray = ({ items }) => {
return items. reduce((total, item) => total + item);
};
//Using the ReduceArray component
const numbers = [1, 2, 3, 4, 5];
<ReduceArray items={numbers} />
//Output: 15
sort()
This method sorts the elements of an array in place and returns the array. The sort() method can be used to sort an array in ascending or descending order. For example, let’s say you have an array of numbers and you want to sort them in ascending order.
Javascript Example:
// JavaScript code sample
const numbers = [2, 5, 3, 1, 4];
// Sort the numbers in ascending order
Count sorted = numbers. sort((a, b) => a - b);
console.log(sorted); // [1, 2, 3, 4, 5]
ReactJs Example:
//Functional component
const SortArray = ({ items }) => {
return items. sort((a, b) => a - b);
};
//Using the SortArray component
const numbers = [5, 4, 3, 2, 1];
<SortArray items={numbers} />
//Output: [1, 2, 3, 4, 5]
These are just a few of the many array methods available in JavaScript. For a more comprehensive list, you can check out the Mozilla documentation.
Conclusion
These concepts are essential for any JavaScript developer, but understanding them before learning ReactJS will make the learning process much easier. With a solid understanding of these concepts, developers can make the most of their learning experience and create powerful applications. You will start a lot more smoothly if you follow this learning route. I guarantee it.
Don’t forget to star and share! 👨💻🤓😊