All The Javascript Concepts You Need To Know Before Learning React (Part 1)
Mark Jaily Peña
Posted on July 1, 2024
Newbie here don't bash :D
Recently, I was sparked with the inspiration to improve my web development skills by learning new technologies, which include React. React is a popular open-source JavaScript library used for building user interfaces.
When exploring new technologies, adequate preparation will ensure smooth sailing and make life much easier. With this, I would like to share Javascript concepts that will help you in your journey towards learning React. You should have at least understood the fundamentals of Javascript before reading this article :>
1. Arrow Functions
When creating functions in Javascript, the keyword function
is used, combined with the function name and, optionally, its arguments.
function DoSomething(args) {
// your code here
}
However, there is another way to create functions without using function
.
const DoSomething = (args) => {
// your code here
}
It is like creating a variable and assigning it to a function. You can choose
let
instead ofconst
if you want to reassign your variable, butconst
is more standard.
At first, you may think that you are writing much longer code compared to the default way of creating a function. That was my first thought also, but it is actually helpful when dealing with callbacks, which is a common thing in React. There are some instance where it is actually much concise when using arrow function.
// Using "function" keyword
function add(a, b) {
return a + b;
};
// Using arrow function
const add = (a, b) => a + b;
When using the arrow function without the curly braces {}
, the function implicitly returns the expression directly following the arrow =>
.
Exporting Using Arrow Function
Another perk of using the arrow function is that it can export a function in a "concise" way.
// Using "function" keyword
export default function add(a, b) {
return a + b;
};
You need to use export default
keyword to export the function to be used in another file.
// Using arrow function
export const add = (a, b) => a + b;
You can remove default
when exporting a function.
Make sure you add
"type": "module"
in yourpackage.json
.
Exporting is important, especially in React, as you will export your components or functions to improve code readability.
export myComponent = () => {
return <div></div>;
}
In case you are not aware, React uses JSX as its markup syntax which lets you write HTML elements within Javascript.
Above is an example of how to export a component in React.
Anonymous Function
Arrow functions are helpful, especially when using anonymous functions.
<button onClick={() => {
console.log("Hello World");
}}>
</button>
In normal Javascript, inside the onclick function is your chosen named function. However, in React, you can also utilize anonymous functions, which are commonly used. Anonymous functions, or lambda functions, are functions without function names.
2. Ternary Operator
I know you probably learned about ternary operator ?
, but for those who don't know, ternary operator is just a concise version of if-else
. It is useful in React for conditionally rendering components and making your code less compact.
let age = 25;
let message = age >= 18 ? "You are an adult" : "You are not yet an adult"; // Output: You are an adult
The ?
serves as a conditional trigger: if the condition before ?
evaluates to true, the statement immediately before :
executes; otherwise, the statement after :
executes instead.
const App = () => {
let isLoggedIn = true;
return isLoggedIn ? <p>User is logged in</p> : <p>User is not logged in</p>
// The function returns the first p tag because isLoggin is true
}
In this React example, the function App
will conditionally render p
tag depending on the value of isLogginIn
. The ternary operator ?
provides explicit control for both true and false conditions.
3. Short Circuit &&
and ||
&&
and ||
are logical operators that play important roles in conditionally rendering components based on certain conditions in React.
let age = 25;
let message = age >= 18 && "You are an adult"; // Output: You are an adult
Here, when age >= 18
is true
, "You are an adult"
is assigned to the message
variable. Otherwise, nothing will be assigned to the message
variable.
Basically, the code after
&&
will only work if the condition before&&
istrue
. Do this/these if the condition/s is/are satisfied.
const App = () => {
let isLoggedIn = true;
return isLoggedIn && <p>User is logged in</p>
// The function returns the p tag because isLoggin is true
}
In this React example, if isLoggedIn
is true
, the p
element with the text "User is logged in"
will be rendered. If isLoggedIn
is false
, nothing will be rendered.
const App = () => {
let message = null;
return <p>{message || "No new messages"}</p>
// The function returns "No new messages" since message is null
}
const App = () => {
let message = "Message received";
return <p>{message || "No new messages"}</p>
// The function returns "Message received" since message has a truthy value.
}
||
has the unique quality of rendering fallback or default component or element. If message is null
(or any falsy value), the text "No new messages"
will be rendered. If message
has a truthy value, that value will be displayed instead.
Basically, if there is no value, do this/these; if there is a value, use that value.
Here is a vanilla javascript example.
let userInput = ""; // User did not provide any input
// Use the logical || operator to provide a default value
let message = userInput || "Default message";
The &&
(logical AND) and ||
(logical OR) operators in JavaScript are called "short-circuit" operators because they evaluate expressions from left to right and stop (short-circuit) as soon as the outcome is determined:
4. Objects
Understanding objects is essential not only in React but in other libraries/frameworks, as well. Objects can be used to store and group data flexibly, and this knowledge will be helpful when dealing with APIs as they rely heavily on objects for configuration, event handling, and data management. Objects follow key-value pair structures, making it easy to access, update, and manage data efficiently.
Destructuring Objects
const person = {
name: "Makku",
age: 19,
isStudent: true,
};
// Accessing object properties without destructuring
const name = person.name;
const age = person.age;
const isStudent = person.isStudent;
Here, we have a person
object with keys as the properties and values as their corresponding data. To access the properties of the person
object without destructuring, you would need to reference each property by its key individually, which is tiresome.
const person = {
name: "Makku",
age: 19,
isStudent: true,
};
// Destructring an object
const { name, age, isStudent } = person;
Destructuring assigns variables name
, age
, and isStudent
with the corresponding values from the person
object. You can then use these variables in your program. Destructuring objects is useful, especially when you're working with props in React.
Defining Objects
const name = "Makku";
const age = 19;
const isStudent = true;
const person = {
name,
age,
isStudent,
};
There are many ways to create objects in Javascript and an example of one is the code snippet above. You can create objects by putting defined variables directly inside the curly braces, creating an object with the keys as the variable names and the values as the data of the referenced variables.
const person = {
name: "Makku",
age: 19,
isStudent: true,
};
const person2 = {...person, name: "Kuma" };
The code block above creates another object with the same properties and values as person
, except that the name
property is replaced with "Kuma"
. This is done using the spread operator ...
, which allows an iterable (like an array or object) to be expanded into individual elements or properties.
5. .map
and .filter
Functions
let names = ["Yldevier", "Precious", "Francis", "Lance", "Adriel", "Karl" ];
Let's say we have an array of names, and we want to add er
in the end of each name. We can use the for
loop or forEach
to do this, but we can also utilize .map
, which will make this concise and easy.
The .map
function creates a new array by applying a provided callback function to each element of the original array.
let names = ["Yldevier", "Precious", "Francis", "Lance", "Adriel", "Karl" ];
let namesList = names.map((name) => {
return name + "er";
});
/* Output
[
"Yldevierer",
"Preciouser",
"Franciser",
"Lanceer",
"Adrieler",
"Karler"
]
*/
In this code snippet, the .map
function is used on the names array. The .map
function iterates over each element (name)
in the names array and applies a transformation function name => name + "er"
.
const App = () => {
let names = ["Yldevier", "Precious", "Francis", "Lance", "Adriel", "Karl"];
const NamesList = () => {
return (
<div>
{names.map((name) => (
<h1>{name}</h1>
))}
</div>
);
};
}
In this React example, the .map
function is used to iterate over the names array and dynamically generate <h1>
elements for each name. This approach leverages JavaScript's array function within JSX to render a list of names as headers <h1>
elements inside a React functional component.
On the other hand, the .filter
function creates a new array containing all elements of the original array that pass a specified test implemented by a provided callback function.
let names = ["Yldevier", "Precious", "Francis", "Lance", "Adriel", "Karl" ];
let nameList = names.filter((name) => {
return name.length > 5;
}); // Output: [ "Yldevier", "Precious", "Francis", "Adriel" ]
In this code snippet, we filter the names
array and create a new array containing elements with lengths greater than 5.
These functions .map
and .filter
are fundamental in React for managing dynamic content and efficiently rendering lists based on specific conditions or transformations of data.
This concludes the first part of the discussion, as I want to grasp the next concepts more. The second article will be posted as soon as I am confident about it.
I hope you learn something from this article! Happy Coding!
References:
https://www.youtube.com/watch?v=m55PTVUrlnA
Posted on July 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.