DEV Community

Cover image for 15 Essential JavaScript Concepts To Learn Before Starting React
Muslimat Mojeed
Muslimat Mojeed

Posted on

15 Essential JavaScript Concepts To Learn Before Starting React

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.

15 Essential JavaScript Concepts

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.

Example

// 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);

Enter fullscreen mode Exit fullscreen mode

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.

Example

const showText = () => {
  console.log('This written text should show after 2 seconds.');
};
const showAfterDelay = (callback, delay) => {
  setTimeout(callback, delay);
};
showAfterDelay(showText, 2000);

Enter fullscreen mode Exit fullscreen mode

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.

Example

Const BookNumbers = [1,2,3,4];
Const DoubleNumbers = BookNumbers.map((book)=> book *2);
Console.log(DoubleNumbers);
//Output BookNumbers= [2,4,6,8]
Enter fullscreen mode Exit fullscreen mode

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.

Example

Const BookNumbers = [1,2,3,4];
Const FilteredNumbers = BookNumbers.filter((book) => book % 2 !== 0 );
Console.log(FilteredNumbers);
// Output 1,3
Enter fullscreen mode Exit fullscreen mode

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.

3 Important Keywords in Reduce Method

  • The initial Value (optional): A starting value for the accumulator. If not provided, the first array element is used as the initial value, and the iteration starts from the second element.
  • Accumulator (required):The accumulated result from previous iterations.
  • Current Value( required): The current element being processed.

Example

const BookNumbers = [1, 2, 3, 4];
const NumberSum = BookNumbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 15
Enter fullscreen mode Exit fullscreen mode

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 ${}.

Example

Const NameValue = "Ade";
const NumValue = 5;
const TempLit= `I am ${NameValue}, a ${NumValue} year old girl `
Enter fullscreen mode Exit fullscreen mode

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.

Example

const BookNumbers = 4;
const result = (BookNumbers % 2 === 0) ? "Even" : "Odd";
console.log(result); 
// Output: "Even"

Enter fullscreen mode Exit fullscreen mode

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:

  • AND- returns true only if both operands are true.
  • OR- returns true if at least one operand is true.
  • NOT- invert true values of its operand..

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.

How Short-circuiting works

AND (&&)

  • if the first operand is false, the entire expression is false, so the second operand is not assessed.
  • if the first operand is true, the second operand is assessed to determine the value that will be returned.

OR (||)

  • if the first operand is true, the entire expression is true, so the second operand isn't evaluated.
  • if the operand is false, the second operand is assessed to determine the value to be returned.
const idVerify = true;
const displayMessage = idVerify && "Identified";

console.log(displayMessage); 
// Output: "Identified"

Enter fullscreen mode Exit fullscreen mode

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:

  • Merge array
const OriginalArray1 = [1, 2, 3];
const OriginalArray2 = [4, 5, 6];

const MergedArray = [...array1, ...array2];

console.log(MergedArray); 
// Output: [1, 2, 3, 4, 5, 6]

Enter fullscreen mode Exit fullscreen mode
  • Copy array
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];

console.log(copiedArray); 
// Output: [1, 2, 3]

Enter fullscreen mode Exit fullscreen mode
  • add a new property to an existing array
const users = [
  { name: "John", age: 20},
];
const updatedUsers = users.map(user => ({ ...user, id: 001 }));

console.log(updatedUsers);
/*
Output:
[
  { name: "John", age: 20, id : 001 },
]
*/

Enter fullscreen mode Exit fullscreen mode
  • pass an argument to a function
const numbers = [2, 4, 6];
const maxNumber = Math.max(...numbers);

console.log(maxNumber); 
// Output: 6
Enter fullscreen mode Exit fullscreen mode

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.

Example

Const BookNumbers= [1,2,3,4,5];
const [first, second, ...rest] = BookNumbers;

console.log(first);  // Output: 1
console.log(second); // Output: 2
console.log(rest);   // Output: [3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

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 user = {
  name: "John",
  World() {
    return "Hello World!";
  }
};

const greeting = user.greet?.();
console.log(greeting); 
 // Output: "Hello World!"

const farewell = user.farewell?.();
console.log(farewell); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

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

  • Skip an element
  • Nest elements
  • Set default values.

An essential concept that shouldn't be ignored before start React is Destructuring.

Const Book = [ 
{title: 'Everyday Smile', 
Author: 'Pitty Butter'}
];
Const [title, author] = book;
Console.log(title);
 //Output Everyday Smile
Enter fullscreen mode Exit fullscreen mode

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.

Example

  • Adding an item
const Book = [ 
  { title: 'Everyday Smile', author: 'Pitty Butter' }
]; 
const newBook = [
  { title: 'Love', author: 'Pascal Rowland' }
];
// Combining two arrays immutably
const addBook = [...newBook, ...Book];
console.log(addBook);
Enter fullscreen mode Exit fullscreen mode
  • To delete an item
const idToDelete = 1;
const books = [
  { id: 1, title: 'Everyday Smile', author: 'Pitty Butter' },
  { id: 2, title: 'Love', author: 'Pascal Rowland' }
];

// Using filter to remove a book by ID
const updatedBooks = books.filter((book) => book.id !== idToDelete);

console.log(updatedBooks);
//Output [
  { id: 2, title: 'Love', author: 'Pascal Rowland' }
]
Enter fullscreen mode Exit fullscreen mode
  • To update an item
const idToUpdate = 1;
const books = [
  { id: 1, title: 'Everyday Smile', author: 'Pitty Butter' },
  { id: 2, title: 'Love', author: 'Pascal Rowland' }
];

// Using map to update a book by ID
const updatedBooks = books.map((book) =>
  book.id === idToUpdate ? { ...book, author: 'Pit Bren' } : book
);

console.log(updatedBooks);
//Output [
  { id: 1, title: 'Everyday Smile', author: 'Pit Bren' },
  { id: 2, title: 'Love', author: 'Pascal Rowland' }
]

Enter fullscreen mode Exit fullscreen mode

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.

Example

async function fetchData(){
Const res = await fetch(https://api.example.com);
Const data = await res.json();
return data;
Enter fullscreen mode Exit fullscreen mode

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:

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: operation completed successfully
  • Rejected: The operation encountered an error.

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.

  • Try- Encloses the code that might throw an error.
  • Catch- execute if an error is thrown within the try block. Receives error objects as an argument.
  • Finally - Execute regardless of whether an error occurs.

Example

async function fetchData() {
  try {
    const res = await fetch("https://API.example.com");
    if (!res.ok) {
      throw new Error("Error fetching data");
    }
    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.error(error.message);
  } finally {
    console.log("Fetching completed");
  }
}
fetchData();

Enter fullscreen mode Exit fullscreen mode

Conclusion

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!

Top comments (0)