JavaScript Concepts You Need To Know Before Learning React
1. The Ternary Operator
// Below is the example of ternary operator (?) being used in a conditional
// expression
condition ? (if condtion is true, run this ):(if condition is false, run this);
Above is the example of a Ternary Operator (?) used as a conditional expression. This shorthand use of the conditional expression is more preferred over the if-else statement for situations where you have to specifically choose between two situations to run some arithematic logic or render something on your page quickly.
How this expression basically works is that the condition is checked first, if the condition is true then the statement after the ternary operator ( ? ) will run, and if that’s not the case then the statement after the colon ( : ) will run.
2. Destructing
const objects = ['table', 'iPhone', 'apple']
const [furniture, mobile, fruit] = objects
The JavaScript destruction feature allows you to smoothly assign values or objects in one go on the left side of the assignment operator to variables (as shown in above example).
One other example:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}
myVehicle(vehicleOne);
function myVehicle({type, color, brand, model}) {
const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';
}
3. Spread Operator
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];
To put it simple a spread operator takes an iterable and divides it into individual elements into an another array or object.
Here’s another example:
const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'
}
const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'
}
const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}
4. Array Methods
.map() method:
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)
function myFunction(num) {
return num * 10;
}
//this function is called by the .map() method where the numbers array
//each element is taken as parameter
.pop() and .push():
.pop() removes item at the end of an array and .push() adds element at the end of an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi", "Lemon"); // adds Kiwi and Lemon after Mango
fruits.pop(); // removes Lemon at the end of an array
There are some other methods like filter, reduce, sort, includes, find, forEach, splice, concat, shift and unshift and so on.
5. Arrow Functions
Helps us to create functions in a more simpler manner:
let hello = () => 'hello' //here we created an arrow function
// assigned it to hello
// this function returns 'hello'
let square = num => num * num // we can ignore bracketts
//if we only have one parameter
// num in this case
6. Promises
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Promises are used just like real human promises which ensure some future result, which means they are an asynchronous event. The promises can either be:
- Resolved — If it completes it’s function
- Rejected — If the function it tries to do is not successful
- Pending — When result of the function is not yet determined
The .then() function is used when a promise is either resolved or rejected and it takes two callback functions as parameters, first function runs when promise is resolved and the second is optional and runs when the promise is rejected and not resolved.
The .catch() function is used for error handling in promise.
7. The Fetch API
fetch('http://example.com/books.json') // fetching the resource URL
.then(response => response.json()); // calling .json() method on the promise
.then(data => setState(data)); // updating the state with the JSON data
The fetch()
method starts the process of fetching a resource from a server.
The fetch()
method returns a Promise that resolves to a Response object.
8. Async/Await
Async/Await functionality provides a better and cleaner way to deal with Promises. JavaScript is synchronous in nature and async/await helps us write promise-based functions in such a way as if they were synchronous by stopping the execution of further code until the promise is resolved or rejected.
To make it work, you have to first use the async keyword before declaring a function. For example, async function promise() {}
. Putting async before a function means that the function will always return a promise.
Inside an async function, you can use the keyword await
to suspend further execution of code until that promise is resolved or rejected. You can use await only inside of an async function.
Now, let’s quickly finish off this section with an example:
async function asyncFunction() {
let promise = new Promise(resolve => {
resolve();
});
let response = await promise; // further execution will be stopped until the promise is resolved or rejected
return console.log(response);
9. Import/Export Components
function Component() {
return(
<div>This is a component</div>
)
}
export default Component
import Component from './Component'
function App() {
return (
<Component />
)
}
In React, you have to render every component you declare in the App.js component.
In the above example, we created a component called Component and exported it with our code export default Component
. Next, we go to App.js and import the Component with the following code: import Component from './Component'
.
Took help from here. on freecodecamp.