React Distilled #1.1: Vital JavaScript BEFORE learning React
Find out essential JavaScript you have to learn before diving into the world of React
Table of contents
Intro 🧐
Hey aspiring developers, welcome back! 🙋♂️
React is a JavaScript Library, therefore you should not jump directly into learning it without knowing the fundamentals of JavaScript.
You definitely don't need to be an expert right away, but the more you dive into React, the more JavaScript you need to learn. So please don't skip this crucial part, and thank me later 🤣
In this article, I'm going to help you review almost everything you need in order to speed up your process quickly with React.
Let's dig into it!
Classes
JavaScript is the only mainstream language with prototype-based inheritance. Prototype-based Inheritance in JS works differently when compared to “classical inheritance” in other programming languages. — I will talk more in-depth in my article about OOP.
Before ES2015, we didn't have Class syntax in JavaScript.
Class is just a syntactic sugar over their inner working. It really just a modern alternative to Constructor Function syntax – an older way to create objects from a function before ES6 Class. But changed a lot in how we build JavaScript programs in the OOP model.
class Shoes {
constructor(brand) {
this.brand = brand;
}
introduce() {
return `This shoes from ${this.brand}`
}
}
class Sneaker extends Shoes {
constructor(brand, type) {
super(brand);
this.type = type;
};
sayHi() {
return this.introduce() + ` and it's a ${this.type} shoes`
}
}
const nikeRunning = new Sneaker('Nike', 'running');
const adidasHiking = new Sneaker('Adidas', 'hiking');
nikeRunning.sayHi() // ⮑ This shoes from Nike and it's a running shoes
nikeRunning.sayHi() // ⮑This shoes from Adidas and it's a hiking shoes
Constructor method
A special method of Class which is executed when a Class is instantiated via new keyword.
Super
The method used to reference the Parent class.
🤔 Quick thought on new Class syntax
With ES6 Class, the prototype property just goes away, we have much cleaner syntax and look more like “Real Class”. But it already hides all the “behind the scenes” or the nature of Prototypal Inheritance in JS. If you're curious to learn more about it, go ahead and check it out yourself.
Getters and Setters
I've used this new syntax many times before I know it is called Proxy Pattern.
🚨 Spoiler: This syntax no longer popular now, hence React Functional Component is widely used.
The get
syntax binds an object property
to a Function
that will be invoked when the property attached to it is looked up.
The set
is a method that allows you to set the value of a property in an object, also we can do some kind of validation before set the value. It is a great way to ensure that the value of a property is always set correctly.
This works in both plain JS Object and in Class.
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName() {
return `${this.firstName} ${this.lastName}`
}
set gender(gender) {
if (typeof gender !== 'string') {
throw new Error('gender must be a string!');
}
this.theGender = gender;
}
}
const johnSmith = new Person('John', 'Smith');
// get the value of `fullName` property - just like regular object property lookup
console.log(johnSmith.fullName) // ⮑ John Smith
// Set the Person gender
johnSmith.gender = 2023;
// 🔴 Error: gender must be a string!
johnSmith.gender = 'male';
console.log(johnSmith) // ⮑ { firstName: 'John', lastName: 'Smith', theGender: 'male' }
Destructuring Objecs and Array
This operator is super popular, scattered over all React code based out there. Therefore, it's worth to learn about.
Give an Object, you can extract just some values you're interested in, and put them into named variables:
const book = {
name: "The way of superior man",
author: "David DeiDa",
publisher: "Unknown",
pages: 300,
}
const {name, pages} = book;
so name
and pages
are desired values you want to get from the book
object.
We also have the same syntax for Arrays:
const x = [1,2,3,4];
const [first, second] = x;
// OR 👻
const [first, ,third, fourth] = x;
// This statement generates 3 new variables by getting the items with index 0, 2, 3 from array `x`
Rest / Spread operator
Spread operator
You can expand an array, object, or string by using spread operator ...
// 1️⃣ With ARRAY
const x = [1,2,3];
// 👉 Create a COPY of an array
const a = [...x];
// 👉 Create new Array based on another array
const b = [...x, 4,5,6,7]; // 👉 [1,2,3,4,5,6,7]
// 2️⃣ With OBJECT
// 👉 Create a COPY of an Object without mutate the current one.
const newObj = {...oldObj};
// Merge two simple objects into one:
const object1 = { name: 'Howard Phung', age: 24};
const object2 = {project: 'Web Dev Distilled'};
const object3 = {...object1, ...object2}
// 3️⃣ With String
const hello = 'hello';
const arrayOfHello = [...hello] // ['h','e','l','l','o']
✅ This operator has pretty useful applications. The most useful one is the ability to use one single array as function argument
⬇️
function add (num1, num2) {
return num1 + num2;
};
const a = [3,4];
add(...a);
// ⮑ add (3,4)
// ⮑ 7 ✅
Behind the back, the spread operator will take the array argument [3,4]
"expand" it to 3,4 and then put it into the function call in the exact order.
The Rest Parameters
Instead of expand
array or object like Spread operator
. This one works in the completely opposite.
The Rest Pattern parameters will compress
a sequence of arguments (can be a infinite number of arguments) into one single array.
Let's take a look at its applications 🔽
👉 In Array Destructuring
⚠️ One caveat: the Rest parameter MUST be the LAST ONE in the parameter list.
const a = [1,2,3,4,5];
// Take out just the `rest` - a sublist of an array
// Pretty useful in case you just need one part of an array.
const [first, second, ...rest] = a;
console.log(first, second); // 1,2
console.log(rest) // ⮑ [3,4,5]
🤟 In Functions Parameters
// Example 1️⃣
function sum(...args) {
let total = 0;
for (const num of args) {
total += num;
}
return total;
}
sum(1,2,3,4) // 10 ✅
// Example 2️⃣
function exampFun(a, b, ...restArgs) {
console.log("a", a);
console.log("b", b);
console.log("restArgs", restArgs);
};
exampFun(1,2,3,4,5,6);
// OUTPUT:
// a, 1
// b, 2
// restArgs: [3,4,5,6]
Does it seem a bit confusing between the Spread operator and Rest parameters?
Let me distill it for you here 👇
👉 If you saw ...
in the parameters of Function Declaration like this fn(...args) {}
, or in Array Destructuring it's the REST Parameters 🤟
👉 If you saw ...
in the argument of a Function Call like this add(...arr)
, or inside an Array [...x]
or an Object {...someObj}
➡️ SPREAD OPERATOR
Object Literals
Pretty straight forward and easy to understand.
In ES6 Object Literals became really powerful, with simpler syntax to include variables, we can write less code to achieve the same behavior as before.
// Instead of doing this
// Before ES2015 way 👇
const publisher = "Unknown Publisher";
const book = {
name: "the obstacle is the way",
author: "ryan holiday",
publisher: publisher,
}
///////////////////////////////////////////
// Now we can do ✅
const publisher = "Unknown Publisher";
const book = {
name: "the obstacle is the way",
author: "ryan holiday",
publisher,
}
Quick review on variable declaration
let and const
✅ var is the traditional way before ES6 to declare a variable that has function scoped. Can be overwritten and re-assigned to a new value.
✅ let is the new preferred approach to variable declaration, that has block-scoped. Can be re-assigned to a new value, but cannot be overwritten.
✅ const is just like let, but for constant value, variables declared with const are immutable. This means we cannot re-assign a new value or overwrite when this variable is already declared.
🥊 Block-scoped: inside an if-else statements, or in a plain block, or a loop.
👻 Variable declared with let and const only can be accessible from INSIDE the block. In other words, the block is not going to let that variable “escape” outside itself. 😏
👉 In the modern day of JavaScript, you'll see very little var declarations, it is almost no longer used in code bases anymore, while let and const became super popular.
Especially const is very widely used nowadays deal to the immutability being very popular.
Default Parameters
This syntax is also widely used in React functional components, in order to set the default value of props
.
Regular functions
const myFunction = function(firstName = "howard", age = 24) {
// doing smth
}
myFunction();
React Components
const TestComponent = function ({isOpen: true, title = "Web Dev Distilled"}) {
if (!isOpen) return;
return <div>{title}</div>
}
Conclusion
We still have much more to cover.
But this article starts goes pretty long.
In the next one, I will cover more vital JavaScript concepts you need before learning React.
Include ternaries operator, Arrow Function, Promise and Async await, Short-circuiting and Logical operators, Optional Chaining.
High order array methods like .map, .filter, .reduce, .sort.
Thank you so much for spending your time reading all the way to the end of this article. It means the world to me.
I hope you enjoy it! See you in the next one very soon!
Howard Phung from Web Dev Distilled