JavaScript Concepts For React Js
JavaScript Concepts For React Js
function greet(name) {
return `Hello, ${name}!`;
}
Functions make our code more reusable. Instead of writing the same code multiple
times, we just call the function whenever we need it.
● We use the const keyword to declare the function. Arrow functions are usually
stored in variables.
● The function keyword is replaced by =>, making it look more concise.
You can make this function even shorter when there’s only one expression to return:
In this case, the curly braces {} and the return keyword can be omitted, because the
function only has a single line.
const student = {
name: 'Alizaib',
age: 21,
course: 'MERN Stack'
};
In this object:
But this can become hard to read when there are many variables. Template literals,
introduced in ES6, make this easier:
Template literals are enclosed in backticks (`) instead of quotes, and variables are
inserted using ${}. This makes the code much cleaner and easier to write, especially in
React when we need to create dynamic content.
Chapter 3: Destructuring
Destructuring is a convenient way to extract values from objects and arrays. This is
especially useful in React when dealing with props and state.
const student = {
name: 'Alizaib',
age: 21,
course: 'MERN Stack'
};
● The { name, age } on the left side is a way to “pick out” the properties you
want from the object on the right side.
● You now have variables name and age that directly store the values 'Alizaib'
and 21.
Instead of accessing each skill using the index, like skills[0], you can destructure the
array:
Array destructuring allows us to easily unpack values and work with them more directly,
which becomes very useful in React when handling data from API responses or props
passed to components.
The ...skills copies the existing array, and then we add 'Express' to the new array.
In React, you’ll often use the spread operator to copy and update the state without
modifying the original state (since state should always be immutable).
In this example, if the condition age >= 18 is true, the result is 'Yes', otherwise it’s
'No'.
Here, the StudentCard component will display "Adult" if the student’s age is 18 or
older, otherwise it will display "Minor".
Chapter 6: Optional Chaining and Short Circuiting
Optional chaining and short-circuiting are techniques that allow us to handle situations
where certain values might not exist, without throwing an error
If student.grade doesn’t exist, instead of throwing an error, the optional chaining will
simply return undefined.
If student.grade exists, it will display the grade; otherwise, it won’t render anything.