React is a popular Javascript library used to build real-world applications. To become a proficient React developer, understanding some fundamental Javascript concepts is important. For many, learning React can seem difficult, but understanding these basic concepts could ease one's learning process.
In this article, I will cover 15 essential concepts every developer should know before starting React. Each concept is explained with an example to show it's importance.
If you're just starting with React or you're about to explore the library, this article is for you.
1.Callback Function
Functions are the building blocks of any program that allows code to be called multiple times without repetition.
One type of function is the Callback Function.
If you want a user to click on an arrow in the browser before any information is displayed or want some codes to be executed right after you're done fetching data from API, you can utilize the power of callbacks.
The callback function performs its task after a function or an event occurs and allows control over the execution of a function.
It's a function passed as an argument to another function and used to specify what should occur after the completion of an asynchronous operation or an event.
// The callback function function showText() { console.log('The written text should show after 2 seconds.'); } function showAfterDelay(callback, delay) { setTimeout(callback, delay); } showAfterDelay(showText, 2000);
2.Arrow Functions
Arrow Functions was introduced in ES6 and allows function syntax to be written more concisely. The arrow function are widely used in React due to its conciseness.
const showText = () => { console.log('This written text should show after 2 seconds.'); }; const showAfterDelay = (callback, delay) => { setTimeout(callback, delay); }; showAfterDelay(showText, 2000);
3.Array.Map() Method
Mutating the existing array is commonly discouraged in React as it could result in unnecessary bugs and performance issues. For that reason, developers employ the array methods. The functional array methods don't mutate the original array rather return a new array from the existing one.
One of the functional array methods is the Array.map() method.
Array.map() methods loop over an existing array and return a new array with the same length. Changes can be made to the new array without having any effect on the existing one.
Const BookNumbers = [1,2,3,4]; Const DoubleNumbers = BookNumbers.map((book)=> book *2); Console.log(DoubleNumbers); //Output BookNumbers= [2,4,6,8]
4.Array.Filter() Method
The Array.filter() method works in an interesting and logical way. These methods can be used to filter out some elements of the array based on a true or false condition.
When a statement is false, it automatically gets filtered out and when it is true, it keeps it making it a suitable approach for removing unwanted elements from an array.
// The callback function function showText() { console.log('The written text should show after 2 seconds.'); } function showAfterDelay(callback, delay) { setTimeout(callback, delay); } showAfterDelay(showText, 2000);
5.Array.reduce() Method
As the name implies, array.reduce() method reduces an entire array to a single value. It's one of the best methods of summing or grouping elements of an array.
const showText = () => { console.log('This written text should show after 2 seconds.'); }; const showAfterDelay = (callback, delay) => { setTimeout(callback, delay); }; showAfterDelay(showText, 2000);
6.Template Literals
Template literals allow strings to contain Javascript variables or any JavaScript expression.
It provides a simple approach to create strings in JavaScript using the backticks and dollar with curly braces ${}.
Const BookNumbers = [1,2,3,4]; Const DoubleNumbers = BookNumbers.map((book)=> book *2); Console.log(DoubleNumbers); //Output BookNumbers= [2,4,6,8]
7.Ternary operators
Ternary operators are conditional operators that offer a simple and concise way of writing an if..else statement.
React doesn't directly support the if..else statement as it isn't suitable for the syntax expression known as JSX that exists in React.
JSX is a syntax extension of JavaScript that allows the embedding of Javascript, CSS and React Component into HTML.
React Syntax is considered more as an expression than a statement and the ternary serves as the suitable operator for it.
Const BookNumbers = [1,2,3,4]; Const FilteredNumbers = BookNumbers.filter((book) => book % 2 !== 0 ); Console.log(FilteredNumbers); // Output 1,3
8.Short-circuiting and Logical operators
Logical operators are used to combine multiple conditions into a single expression. The main logical operators that exist in JavaScript are:
Short-circuiting is a behavior that occurs in logical operators where, under specific conditions, the second operand is not evaluated because the result of the entire expression can be determined solely by the first operand.
AND (&&)
OR (||)
// The callback function function showText() { console.log('The written text should show after 2 seconds.'); } function showAfterDelay(callback, delay) { setTimeout(callback, delay); } showAfterDelay(showText, 2000);
9.RestSpread Operator
In instances when you want to add a new property to an existing array or merge a group of existing arrays, the spread Operator is the go-to operator.
Spread Operator (...) denoted by 3 dots expands an array into individual elements and is used at the beginning of an array. It is used to:
const showText = () => { console.log('This written text should show after 2 seconds.'); }; const showAfterDelay = (callback, delay) => { setTimeout(callback, delay); }; showAfterDelay(showText, 2000);
Const BookNumbers = [1,2,3,4]; Const DoubleNumbers = BookNumbers.map((book)=> book *2); Console.log(DoubleNumbers); //Output BookNumbers= [2,4,6,8]
Const BookNumbers = [1,2,3,4]; Const FilteredNumbers = BookNumbers.filter((book) => book % 2 !== 0 ); Console.log(FilteredNumbers); // Output 1,3
const BookNumbers = [1, 2, 3, 4]; const NumberSum = BookNumbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // Output: 15
Rest Operator(...) is also denoted with the 3 dots but written at the end of an array. It is used to collect multiple properties from a destructured object/array.
Const NameValue = "Ade"; const NumValue = 5; const TempLit= `I am ${NameValue}, a ${NumValue} year old girl `
10.Optional chaining
Optional chaining handles null or undefined values in an easy way. It is used to access properties or any intermediate properties that appears to be null or undefined in the chain. It will automatically be short-circuited and rendered undefined. Ideally, without optional chaining, it returns an error.
In some instances you're not sure all the values exist in an object, consider using optional chaining as it is a syntax that offers checks for null and undefined values.
const BookNumbers = 4; const result = (BookNumbers % 2 === 0) ? "Even" : "Odd"; console.log(result); // Output: "Even"
11.Destructuring Array
Codes can become cumbersome when multiple properties have to be called at once from an array. With destructuring, this can be prevented.
Destructuring allows assembling values from an array into a distinct variable.
Destructuring can be used to
An essential concept that shouldn't be ignored before start React is Destructuring.
const idVerify = true; const displayMessage = idVerify && "Identified"; console.log(displayMessage); // Output: "Identified"
12.Working With Immutable Arrays
Arrays can be mutated in JavaScript meaning properties can be added, removed or updated in an array.
However, in React, immutability is often preferred to preserve state integrity and ensure React can detect changes. To work with immutable arrays in React, methods like map, filter, and the spread operator are commonly used for adding, deleting, and updating items in arrays without mutating the original array.
// The callback function function showText() { console.log('The written text should show after 2 seconds.'); } function showAfterDelay(callback, delay) { setTimeout(callback, delay); } showAfterDelay(showText, 2000);
const showText = () => { console.log('This written text should show after 2 seconds.'); }; const showAfterDelay = (callback, delay) => { setTimeout(callback, delay); }; showAfterDelay(showText, 2000);
Const BookNumbers = [1,2,3,4]; Const DoubleNumbers = BookNumbers.map((book)=> book *2); Console.log(DoubleNumbers); //Output BookNumbers= [2,4,6,8]
13.Async/await function
Async JavaScript governs how tasks that take time to complete are being performed. JavaScript is a synchronous language i.e runs a code one after the other in a single thread.
In instances when you're fetching data from a database, some codes may be required to load before the fetching is completed.
With the async function, code can be executed without waiting for the operations to complete, thus improving user experience and overall performance.
In React, you'll frequently work with Application Programming Interface (API), thus, it is important have insight into how this function works.
Const BookNumbers = [1,2,3,4]; Const FilteredNumbers = BookNumbers.filter((book) => book % 2 !== 0 ); Console.log(FilteredNumbers); // Output 1,3
14.Promises
Promises refers to built-in object that represents the eventual completion or failure of an asynchronous operation.
Promises exist in one of the three states:
Promises play a significant role in JavaScript, which makes it an important concept to learn about. It enables you to write cleaner code, systematically handle errors and boost overall performance.
15.Handling Errors using try.catch.finally
There are moments when errors pop up during data fetching leaving you pondering on how to find or fix these bugs.
With the use of the keywords, data fetching is handled in a more structured way.
Try..catch..finally block is a powerful error handling construct in JavaScript, that allows potential errors to be handled successfully and specific codes to be executed regardless of whether an error occurs.
It could be time-consuming to find certain errors in your code. By utilizing these blocks, it becomes easy.
const BookNumbers = [1, 2, 3, 4]; const NumberSum = BookNumbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // Output: 15
Gaining insights into the essential JavaScript concepts explained above will ease one's learning process and guide you toward becoming a proficient React developer.If you haven’t learned these concepts yet, make an effort to do so. Feel free to share your suggestions in the comment section!
The above is the detailed content of Essential JavaScript Concepts To Learn Before Starting React. For more information, please follow other related articles on the PHP Chinese website!