JavaScript to know before moving into React.
In this article, I’ll show you some basic JavaScript you should know before moving into React. When I started my journey to learn React I always used to get confused about arrow function, the spread operator, promises, and destructuring. Now my confusion is clear and I want to share that knowledge with you so that the same does not happen to you. So let’s get started.
1. Arrow Function
An arrow function is a feature introduced in ES6. It helps us write javascript functions in a shorter and concise way.
Syntax
(param1, param2, …, paramN) => { statements }
- The first or common way to write an arrow function.
- Arrow function without curly braces if the return statement is one.
- Arrow function without parenthesis if there is one argument.
- Arrow function if there is no argument
- Arrow function in object literal.
Usage in React
- Arrow function usage with the javascript map function. Here we are fetching data from jsonplaceholder using Axios and then Iterating using the map function of javascript.
- Arrow function with async-await.
- Arrow function usage in functional components.
2. Map
The map() method creates a new array with the results of calling a function for every array element.
Syntax
let new_array = old_arr.map((val, index, arr)=> {
// return element to new Array
})* new_array => the new array that is returned.
* old_arr => the array on which map function to be run.
* val => the current element being processed in the array.
* index => the index of the current element being processed in the array. (optional)
* arr => The array map was called upon.(optional)
- Example 1
- Example 2 — Return object with value and index.
Usage in React
Here I am creating two functions mapMethod and createObject to demonstrate the above two examples in React.
3. Template literals
Template literals are string literals allowing embedded expressions.
Syntax
`string text``string text line 1
string text line 2``string text ${expression} string text`tag`string text ${expression} string text`
Example 1
For creating template literal you should use backticks (``):
Example 2 — Multi-line string
Example 3 — Interpolation, allows you to put expression inside the template literal.
4. Import and Export
Export
Export statement is used when we want to export a variable, function or a class from one file to be used by another file through Import statement.
The import statement is used to import a variable, function, or a class that is exported by another module.
Example 1 — Exporting array, const, class, and function before declaring and then importing
Export
Import
Example 2 — Exporting array, const, class, and function after declaring and then importing.
Export
Import
Example 3 — Export “as”
Import
Example 4 — Export default (You can only export one default per file) and then importing
Export
Import
Example 5 — You can also import all the exported variables, functions, classes at once.
5. Destructuring
Destructuring helps us create variables from values in arrays or properties from objects. It makes our code look simpler and prettier.
Array destructuring
Example 1 — Assigning array values to custom variables. Here the position of variable represents the position of values.
Example 2 — Assigning the first two values as a custom variable and rest values as an array.
Example 3 — Setting a default value for the variable if the passed array doesn’t have enough values.
Example 4 — Accessing the nested array
Example 5 — Swapping variables
Object Destructuring
Example 1 — Assigning object values to custom variables. This is most commonly used in React.
Example 2 — Assigning previously declared object variables to new variable names.
Example 3 — Default Value. If the declared variable doesn’t exist it will return an undefined error so assigning default value if a variable does not exist in the destructured object.
Example 4 — Assigning previously declared object variables to new variable names and providing default values. So it’s basically a combination of examples 2 and 3.
Example 5 — Nested Object Destructuring.
Example 6 — Nested Object Destructuring with the default value.
Example 7 — Assigning the first two values as a custom variable and rest values as an object.
Mixed Destructuring
Sometimes you have to deal with complex objects which include a combination of objects and arrays. So here is an example to show how to deal with them.
6. Promises
Promises are used to handle asynchronous operations in javascript. It’s basically an object that may produce some value in the future either a resolved one or rejected one.
Syntax
var mypromise = new Promise(function(resolve, reject){
//do something
});* Promise take one parameter which is a callback function.
* The callback function inside Promise takes two parameter resolve and reject.
* If operation is successful it will call resolve.
* If operation is unsuccessful it will call reject.
Example 1
Promise Consumers — then() , catch(), finally
- then() — If promises get resolved
syntax
.then(function(result){
//handle success
}, function(error){
//handle error
})* First function is executed if condition satisfy.
* Second function executed if condition doesn't satisy.
Example
- catch() — If promises fail.
syntax
.catch(function(error){
//handle error
})
* Used to handle promise rejection or error handling.
- finally() — this method can be useful if you want to do some processing or cleanup once the promise is settled.
syntax
.finally(function(error){
//post processing
})
Example
Chaining in promise
If you want to execute two or more asynchronous operation back to back, where each execution starts after completion of previous operation.
Example
Note:
- Each execution takes place after completion of the previous operation.
- Passing the value of a in resolve to get that as resposnse in then() and multiplying it with 2 in each step.
Chaining after a catch
Usage in react
Here we have created the getData method to create a new Promise to fetch data from jsonplaceholder API using Axios. If there is a response from API it will resolve and console the response else it will reject and respond with the error message from the API.
7. Spread Operator
Spread syntax (…) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected
Spread in function calls
Example
Spread in array literals
- Copying Arrays
- Merging Arrays
- In Destructuring variable
Spread in object literals
- Copying Objects
- Merging Objects
- In Destructuring variable
String to a single character array
Spread Operator in console.log
Remove Duplicate entries from an Array
8. Conditional (ternary) operator
A Conditional (ternary) operator allows us to specify that a particular code will be executed if a certain condition is met. It’s similar to the if-else statement with a shorter version of code.
syntax
condition ? epressionIfTrue : expressionIfFalse
Single condition checking
Multiple condition checking
9. Filter
The filter() method creates an array filled with all array elements that passes a certain condition
Basic Example
Example with some dummy data
10. Reduce
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value
syntax
array.reduce(function(accumulator, currentValue, currentIndex, arr), initialValue)* accumulator - The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback—or initialValue, if it was supplied* currentValue - The current element being processed in the array.* currentIndex - Optional. The array index of the current element* arr - Optional. The array object the current element belongs to* initialValue - Optional. A value to be passed to the function as the initial value
Basic Example
Example with some dummy data
That’s it for all today. Below I have shared the live code and GitHub repository for reference and practice.