Javascript You Need To Know For React

Full-Stack Developer, Entrepreneur and Co-Founder of Coderplex.
Building https://coderplex.in
Checkout my portfolio at https://bhanuteja.dev
Search for a command to run...

Full-Stack Developer, Entrepreneur and Co-Founder of Coderplex.
Building https://coderplex.in
Checkout my portfolio at https://bhanuteja.dev
Very detailed article. Thanks for compiling this! I'm adding a small resource to learn JavaScript in a fun way. JavaScript Quiz
Thanks for the feedback @Alp3n. I will add an actual React snippet at the end that uses some of these concepts.
Bhanu Teja Pachipulusu Thank you. I started my first real React project few days ago and already used most of these. What I learn here is optional chaining and I think I have a place for that in my app :D Also default parameters, I have read about them before, but now I might use them too :)
Finally read the article, awesome. I'll have to revisit many times. Thanks for sharing.
Thanks to Bhanu Teja Pachipulusu for adding my article link! Such a great article about JavaScript topics, their explanations, and related links. Saved it for future reference.
Thanks for the mention. Also, a great resource. Bookmarked. Thanks for sharing. π
Your articles are amazing to read. Please keep publishing awesome content.
Thanks Bhanu Teja Pachipulusu for sharing. I think I'll revisit this article multiple times in the future. Shall bookmark.
Thank you for adding my article reference!
Your article has the best explanation I could find on ES Modules. Even though your article was published in May, I still could not find a better article than yours explaining this.
Awesome Job writing it π
Your article is very good. I didn't know about Promise.race and Promise.allSettled before.
Thanks Jatin π
In this series, I will write different blog posts based on workshop content from [Kent C. Dodds](https://kentcdodds.com)'s [EpicReact.Dev](https://epicreact.dev) as I go through it.
Hello World π Welcome to the third article of the My Review of Kent C. Dodds's EpicReact.Dev Series which is based on the workshop material from EpicReact.Dev by Kent C. Dodds. If you haven't read the previous articles of the series yet, please go a...
Authored in connection with the Write With Fauna program. Table of Contents Authentication Setting up Fauna in Next.js Installing Fauna Setting up Migrations Tool Authentication and Authorization in Fauna Next.js Serverless Function Setup for Fa...

I wanted to start blogging in Aug of 2020. I decided to use @hashnode for my blog. It was the best decision that I made. I wrote 27 technical articles so far. Most of them are about frontend web development. A thread π§΅ about each of these articles i...

Next.js has become my go-to framework for almost every project that I make. So, I made a starter template that I can just use and get started easily. In this article, I will show you how to use the starter template that I made and deploy it with Verc...

In this article, I will list out all the git commands that I use very frequently. This is not in any way a complete list, just the commands that I use very often. This is intended to be used as a quick reference to perform an action that you want. ...

In this article, we will see the order in which different useEffect callbacks and cleanups happen. We will also see how it differs when the app mounts, unmounts, updates. This image is taken from https://github.com/donavon/hook-flow. I took the ex...

Bhanu Teja Pachipulusu's blog
29 posts
Developer, Indie Maker and Blogger. Currently building MDX.one
Checkout my portfolio
Welcome to the second article of the My Review of Kent C. Dodds's EpicReact.Dev series which is based on the workshop material from EpicReact.Dev by Kent C. Dodds. In the previous article, you looked at the different topics that are going to be covered in EpicReact.Dev workshop. If you haven't read the previous article of the series, please go and read it now and come back. In this article, I am going to explain the basic javascript concepts that you need to know before you start learning React.
Let's get to it.
I am one of those persons who learned React before properly learning the basic concepts of javascript. Because of this, in the early days of my React journey, I didn't know which part of the code is React and which part is the vanilla js. It's important to know the basic javascript concepts to understand better which part of the puzzle is React solving.
In this blog post, I will be writing about different concepts of javascript that you see yourself using very often while working with React. It's better to know these before you deep dive into learning React.
I will be covering the following topics. Feel free to skip over the topics that you already know.
Let's say we have the following expression - where b and c are expressions
b && c
This will be evaluated to the value of c only if b is truthy, otherwise, it will be evaluated to the value of b
Note:
b is falsy, then the expression c is not even going to be evaluated. short-circuit evaluation. Let's say we have the following expression - where b and c are expressions
b || c
This will be evaluated to the value of b if b is truthy, otherwise, it will be evaluated to the value of c.
Note:
b is truthy, then the expression c is not even going to be evaluated.This is a new ES6 way to create strings.
Let's see an example.
Assume that you want to create the following type of strings:
3 blog posts were written by Bhanu Teja in a span of 2 weeks. You will be given count (number of blogs), name (name of the user), span (time span it took) as variables.
Without using template literals
const count = 3
const user = 'Bhanu Teja'
const span = 2
const result = count + ' blog posts were written by '
+ name + ' in a span of ' + span
+ ' weeks.'
Using template literals
const count = 3
const name = 'Bhanu Teja'
const span = 2
const result = `${count} blog posts were written by ${name} in a span of ${span} weeks.`
Template literals start and end with a backtick(`) and you can write strings of text inside them and you have to wrap the javascript expressions around with ${ and }
Let's add another use-case to the above example.
blog post instead of blog posts week instead of weeks.Without using template literals
function pluralize(text, count) {
if (count === 1) {
return text
}
return text + 's'
}
const result = count + ' ' + pluralize('blog post', count)
+ ' were written by ' + name
+ ' in a span of ' + span
+ ' ' + pluralize('week', span) + '.'
Using template literals
function pluralize(text, count) {
if (count === 1) {
return text
}
return text + 's'
}
const result = `${count} ${pluralize('blog post', count)} were written by ${name} in a span of ${span} ${pluralize('week', span)}.`
This is a shorthand representation of the if-else statements.
This is best explained using an example.
if (condition) {
doSomething()
} else {
doSomethingElse()
}
The above example when written using ternary operator
condition ? doSomething() : doSomethingElse()
condition ? expressionIfTrue : expressionIfFalse
const id = 2
const name = 'Bhanu'
const count = 2
// This is the normal way
const user = {
id: id,
blogs: count,
name: name,
}
// Using shorthand property names
const user = {
id,
blogs: count,
name,
}
If the name of the variable and the name of the property of the object are same, then you can just write the variable name and omit the rest.
This is one of the things that I did not know when I was initially learning React, and you usually see this being used a lot in code and documentation.
This is a short-hand way to get the properties of an object into variables.
// we have a `user` variable that looks like this
const user = {
name: 'Bhanu Teja',
blogs: 3,
timeSpan: 2.
}
// without using object destructuring
const name = user.name
const blogs = user.blogs
const timeSpan = user.timeSpan
// using object destructuring
const { name, blogs, timeSpan } = user
Note: The name of the destructured variables should be same as the name of the object properties.
This is a short-hand way to get the elements of an array into variables.
// we have a `name` variable that looks like this
const name = [ 'Bhanu Teja', 'P']
// without using array destructuring
const firstName = name[0]
const lastName = name[1]
// using array destructuring
const [firstName, lastName] = name
You often want the function parameters to take some default values if that is not passed while calling the function.
Let's see an example
function sum(a = 2, b = 5) {
return a + b
}
sum(5, 7) // a = 5, b = 7, result = 12
sum(4) // a = 4, b = 5(default value of b), result = 9
sum() // a = 2(default a), b = 5(default b), result = 7
So, whenever you want a parameter to take a default value, simply add a = sign after the parameter and add your default value there.
This is a relatively new feature of javascript.
The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.
- Taken from MDN Docs
Consider the expression a?.b.
This expression evaluates to a.b if a is not null and not undefined, otherwise, it evaluates to undefined.
You can even chain this multiple times like a?.b?.c
a is undefined or null, then this expression evaluates to undefinedb is undefined or null, then this expression evaluates to undefineda.b.cSyntax:
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is
nullorundefined, and otherwise returns its left-hand side operand.
- Taken from MDN Docs
Consider the expression a ?? b.
This evaluates to b if a is null or undefined, otherwise, it evaluates to a
This operator spreads the values of an iterable object.
const a = [1, 2, 3]
const b = [5, 6]
console.log(...a) // 1 2 3
// Now, if you want to have an array with values 0, 1, 2, 3, 4, 5, 6
const c = [0, ...a, 4, ...b]
console.log(c) // 0 1 2 3 4 5 6
const first = {a: 1, b: 2}
const second = {c: 3}
// Now to create an object {a: 1, b: 2, c: 3, d: 4}
const result = {...first, ...second, d: 4}
console.log(result) // {a: 1, b: 2, c: 3, d: 4}
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
- Taken from MDN Docs
function sum(a, b, ...rest) {
// ...
}
sum(1, 2, 3, 4, 5, 6) // a = 1, b = 2, rest = [3, 4, 5, 6]
const user = {
name: 'Bhanu Teja',
blogs: 3,
span: 2,
}
const {name, ...rest} = user
console.log(name) // Bhanu Teja
console.log(rest) // { blogs: 3, span: 2}
This is a new ES6 way to write functions.
// without using arrow functions
const sum = function (a, b) {
return a + b
}
// (or)
function sum (a, b) {
return a + b
}
// Using arrow functions
const sum = (a, b) => {
return a + b
}
// (or)
const sum = (a, b) => a+ b
const multiplyBy2 = (a) => a * 2
(or)
const multiplyBy2 = a => a * 2
As you can see from the above example, converting the normal function to arrow functions can be done as follows:
function keyword.=> after the parameters.Note
return keyword and also need not wrap it between { and }There are so many array methods, but we frequently use some of these. I will be covering the following array methods.
This method creates a new array from an existing array by calling a function for every element of the array.
I always remember this as mapping the values in an array to some other values.
Let's see an example.
const names = [
{ firstName: 'Bhanu Teja', lastName: 'P' },
{ firstName: 'Florin', lastName: 'Pop'},
{ firstName: 'Brad', lastName: 'Traversy'},
]
// Let's say we have to create a new array with full names.
// First let's write a callback function which takes an array element as an argument.
function callback(name) {
return name.firstName + ' ' + name.lastName
}
// Now let's call .map() method on the array
console.log(names.map(callback)) // ["Bhanu Teja P", "Florin Pop", "Brad Traversy"]
// You can even inline the callback function which is how most of the people write this.
names.map(function(name) { return name.firstName + ' ' + name.lastName })
// Let's write the same using arrow functions and template literals that we just learned earlier
names.map((name) => `${name.firstName} ${name.lastName}`)
// You can even omit the parenthesis around name
names.map(name => `${name.firstName} ${name.lastName}`)
// Let's use object destructuring
names.map(({firstName, lastName}) => `${firstName} ${lastName}`)
Syntax:
// callback takes a single array element as an argument.
// values is an array
values.map(callback)
Note:
Now that we know the Array map method, it's easy to understand other array methods. They all have a similar syntax.
The array filter method creates a new array with elements that satisfy some given criteria.
I always remember this as the filter method filters out elements that do not satisfy the criteria.
// consider the following array of users
const users = [
{id: 1, posts: 2},
{id: 2, posts: 1},
{id: 3, posts: 5},
{id: 4, posts: 4},
{id: 5, posts: 3},
]
// Let's say we want to have all users who have at least 3 posts.
users.filter((user) => user.posts >= 3) // [{id: 3, posts: 5}, {id: 4, posts: 4}, {id: 5, posts: 3}]
Syntax:
// callback takes a single array element as an argument.
// values is an array
values.filter(callback)
Note:
The array reduce method reduces the array of values into a single value. It executes the callback function for each value of the array.
Lets see the syntax of the reduce method before seeing an example.
array.reduce(function(totalValue, currentValue, currentIndex, arr), initialValue)
const values = [2, 4, 6, 7, 8]
// Let's say that we want to have a sum of all these values.
// Let's see how we do it using a traditional for loop
let total = 0
for(let i = 0; i < values.length; i++) {
const value = values[i]
total = total + value
}
console.log(total)
// Let's use reduce method now
const initialValue = 0
values.reduce((total, currentValue) => total + currentValue, initialValue)
Notes:
initialValue is optional parameter.The callback function takes two different values as arguments. Based on the return value of the callback function, the two elements' positions are decided.
const values = [4, 10, 2, 1, 55]
// Let's say we want to sort this array in descending order
// so if a and b are given
// a should be before b if a > b
// a should be after b if a < b
// a and b can be at their own places if a === b
values.sort((a, b) => {
if(a > b) {
return -1
}
if(a < b) {
return 1
}
return 0
}) // [55, 10, 4, 2, 1]
// You can also do this as follows
values.sort((a, b) => b - a)
Note:
This returns true if the element is included in the array, otherwise returns false.
Syntax:
array.includes(element)
const values = [2, 3, 4]
values.includes(1) // false
values.includes(2) // true
Note:
array.includes(element, startIndex)Syntax
array.slice(start, end)
Array slice will return the elements in the given range.
-1 refers to the last element of the array, -2 refers to last but one element, and so on.end will not be selectedconst numbers = [0, 1, 2, 3, 4, 5, 6, 7]
console.log(numbers.slice()) // [0, 1, 2, 3, 4, 5, 6, 7]
console.log(numbers.slice(2)) // [2, 3, 4, 5, 6, 7]
console.log(numbers.slice(2, 6)) // [2, 3, 4, 5]
console.log(numbers.slice(-1)) // [7]
console.log(numbers.slice(-3)) // [5, 6, 7]
console.log(numbers.slice(-3, -1)) // [5, 6]
Note:
Syntax:
array.splice(index, count, item1, ....., itemX)
This method is used to add or remove elements in an array.
indexconst numbers = [0, 1, 2, 100, 6, 7]
// let's say we have to convert this array to [0, 1, 2, 3, 4, 5, 6, 7]
numbers.splice(3, 1, 3, 4, 5)
console.log(numbers) // [0, 1, 2, 3, 4, 5, 6, 7]
Note:
To know more about different array methods, check out the amazing series Javascript Array Methods made by @aman__tyagi
You often see yourself using ES Modules imports and exports while working with React. It's important to know how to import them when they are exported as default exports vs when they are exported as named exports.
Check out the following amazing articles to read about these.
You also need to have a basic knowledge of what promises are and how to work them. They will be used quite often in React.
Check out the following amazing articles to read about these.
It is also good to be familiar with basic Document Apis like createElement, getElementById etc. If you know these, you will appreciate the similarity and differences between React APIs and Document APIs.
If you are working with javascript for a while now, it is most likely that you already know basic Document APIs.
MDN Docs are the best place to read up on these.
You might already know some of the topics that I have explained in this article. Even if you didn't before, now you know. These concepts are enough for you to follow along with EpicReact series. If you find something that can be improved or added to this article, feel free to comment on this article. I will try to incorporate your suggestions. Subscribe to my blog if you don't want to miss the next article in this series.
In the next article, we are actually going to start the workshop - starting with React Fundamentals workshop.
If this was helpful to you, Please Like and Share so that it reaches others as well. To get email notifications on my latest articles, please subscribe to my blog by hitting the Subscribe button at the top of the page. You can also follow me on twitter @pbteja1998.
If you want to learn more about the topics mentioned in this article, you can go through the following articles that I found being published on Hashnode. Will be adding more articles to this list as they come along. Different people will find different explanations better.
The next article in this series is already live. Click on the link belowπ