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.
Logical AND (&&) Operator
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
Notes:
b
is falsy, then the expression c
is not even going to be evaluated. shortcut evaluation
. Logical OR (||) Operator
Let's say we have the following expression - where
b
and c
are expressionsb || 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()
Syntax
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 the 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 undefined
b
is undefined or null
, then this expression evaluates to undefined
a.b.c
Syntax:
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 isornull
, and otherwise returns its left-hand side operand. - Taken from MDN Docsundefined
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.
Array Spread
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
Object Spread
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 Arguments
function sum(a, b, ...rest) {
// ...
}
sum(1, 2, 3, 4, 5, 6) // a = 1, b = 2, rest = [3, 4, 5, 6]
Usage with objects
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.
Array map() Method
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:
Array filter() Method
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:
Array reduce() method
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 an optional parameter.Array sort() method
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:
Array includes() Method
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)
Array slice() method
Syntax
array.slice(start, end)
Array slice will return the elements in the given range.
start
-1
refers to the last element of the array, -2
refers to last but one element, and so on.end
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:
Array splice() method
Syntax:
array.splice(index, count, item1, ....., itemX)
This method is used to add or remove elements in an array.
index
count
item1, ....., itemX
index
const 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
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 this article to know more about them.
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 also like the following React articles that I wrote:
Previously published at https://blog.bhanuteja.dev/epic-react-javascript-you-need-to-know-for-react