0% found this document useful (0 votes)
10 views

Unit One ES5

The document provides an introduction to React, highlighting its use of JSX and the importance of ES6 features such as classes, arrow functions, and destructuring. It explains variable declarations in ES6, including 'let' and 'const', and covers array methods and destructuring techniques. Overall, it serves as a foundational guide for understanding React and modern JavaScript syntax.

Uploaded by

kavaiyavishal20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit One ES5

The document provides an introduction to React, highlighting its use of JSX and the importance of ES6 features such as classes, arrow functions, and destructuring. It explains variable declarations in ES6, including 'let' and 'const', and covers array methods and destructuring techniques. Overall, it serves as a foundational guide for understanding React and modern JavaScript syntax.

Uploaded by

kavaiyavishal20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Getting started with React

Dr. Vivek Bhardwaj


Assistant Professor
Introduction to React and JSX
Introduction to React
- React is an open-source front-end framework
- React introduces JSX, or JavaScript XML
- JSX can be used to create React components
- React, sometimes referred to as a frontend JavaScript framework, is a JavaScript library
created by Facebook.
- React is a tool for building UI components.
What is ES6?
JavaScript ES6 brings new features and new syntax which has made
your code more readable and more modern. It enables you to do
more by writing less code. ES6 has also introduced to us a lot of great
features like template strings, modules, arrow functions, class
destruction… and more

Javascript ES6 is the version of Javascript released in 2015.


Informally, many developers call any version of Javascript released
after 2015 “ES6” because of the many new features the 2015
update added to the language.
ES6
React uses ES6, and you should be familiar with some of the new
features like:
• Classes
• Arrow Functions
• Variables (let, const, var)
• Array Methods like .map()
• Destructuring
• Modules
• Ternary Operator
• Spread Operator
Variables
Before ES6 there was only one way of defining your variables: with the
var keyword

var
var x = 5.6;

If you use var outside of a function, it belongs to the global scope.


If you use var inside of a function, it belongs to that function.
If you use var inside of a block, i.e. a for loop, the variable is still available
outside of that block.
Variables

ES6, there are three ways of defining your variables: var, let, and const

let
let x = 5.6;

let is the block scoped version of var, and is limited to the block (or expression)
where it is defined.
If you use let inside of a block, i.e. a for loop, the variable is only available inside of
that loop.
let has a block scope.
const
const x = 5.6;

const is a variable that once it has been created, its value can never
change.

const has a block scope.

Because of this you can NOT:


•Reassign a constant value
•Reassign a constant array
•Reassign a constant object
But you CAN:
•Change the elements of constant array
•Change the properties of constant object
Classes
ES6 introduced classes.
A class is a type of function, but instead of using the keyword function to initiate it, we use the
keyword class, and the properties are assigned inside a constructor() method.

Syntax: Class Declaration


1.class Class_name{
2.}

Example - Class Declaration Instantiating an Object from class


1.class Student{
2. constructor(name, age){
3. this.name = name; Syntax
4. this.age = age; 1.var obj_name = new class_name([arguements])
5. } Example
6. 1.var stu = new Student('Peter', 22)
7.}
Accessing functions

The object can access the attributes and functions of a class. We use the '.' dot
notation (or period) for accessing the data members of the class.
Syntax
1.obj.function_name();
1.class Student {
2. constructor(name, age) {
3. this.n = name;
4. this.a = age;
5. }
6. stu() {
7. console.log("The Name of the student is: ", this.n)
8. console.log("The Age of the student is: ",this. a)
9. }
10.}
11.
12.var stuObj = new Student('Peter',20);
13.stuObj.stu();
Classes

Example
A simple class constructor:
class Car { constructor(name) {
this.brand = name;
}
}
Create an object called "mycar" based on the Car class:

class Car { constructor(name) {


this.brand = name;
}
} const mycar = new Car("Ford");

The constructor function is called automatically when the object is initialized


You can add your own methods in a class:
Create a method named "present":
class Car { constructor(name)
{ this.brand = name; }

present() { return 'I have a ' + this.brand;


}
}

const mycar = new Car("Ford");


mycar.present();

you call the method by referring to the object's method name followed by
parentheses
The Static keyword
The static keyword is used for making the static functions in the class.
Static functions are referenced only by using the class name.
Example
1.'use strict'
2.class Example {
3. static show() {
4. console.log("Static Function")
5. }
6.}

7.Example.show() //invoke the static method


React ES6 Arrow Functions
Arrow functions allow us to write shorter function syntax:

Syntax for defining the arrow function


1.const functionName = (arg1, arg2, ?..) => {
2. //body of the function
3.}

There are three parts to an Arrow Function or Lambda Function:


•Parameters: Any function may optionally have the parameters.
•Fat arrow notation/lambda notation: It is the notation for the arrow
(=>).
•Statements: It represents the instruction set of the function.
1./ function expression
2.
3.var myfun1 = function show() {
4. console.log("It is a Function Expression");
5.}
6.
7.//Arrow function
8.
9.var myfun2 = () => {
10. console.log("It is an Arrow Function");
11. };
12.
13.myfun1();
14.myfun2();
Syntactic Variations
There are some syntactic variations for the arrow functions that are as follows:
•Optional parentheses for the single parameter
1.var num = x => {
2. console.log(x);
3.}
4.num(140);

•Optional braces for single statement and the empty braces if there is not any parameter required.
1.var show = () => console.log("Hello World");
2.show();

Arrow Function with Parameters


If you require to pass more than one parameter by using an arrow function, then you have to pass them
within the parentheses.
For example
1.var show = (a,b,c) => {
2. console.log(a + " " + b + " " + c );
3.}
4.show(100,200,300);
Arrow function with default parameters

var show = (a, b=200) =>


{ console.log(a + " " + b); Arrow Function without Parentheses
} 1. var show = x => {
show(100); 2. console.log(x);
3.}
4.show("Hello World");
1.var show = (a, b=200) => {
2. console.log(a + " " + b);
3.}
4.show(100,500);
React ES6 Arrow Functions
Arrow functions allow us to write shorter function syntax:

Before:
hello = function() {
return "Hello World!"; }

With Arrow Function:


hello = () => {
return "Hello World!";
}
Arrow Functions Return Value by Default:
hello = () => "Hello World!";

Arrow Function With Parameters:


hello = (val) => "Hello " + val;

Arrow Function Without Parentheses:


hello = val => "Hello " + val;
Arrays
Syntax
There are two ways of declaring an array.
1.var array_name = new Array(); // By using the new keyword
2.
3.var array_name = [value1, value2,....valueN]; //By using Array literals
4. or,
5.var array_name; //Declaration
6.array_name=[value1, value2,…..valueN]; //Initialization
Accessing Array elements

Arrays are indexed from 0. The array name followed by the subscript
is used for referring an array element.
Syntax
1.array_name[subscript];

Example
1.var num;
2.num = [2,4,6,8];
3.console.log(num[0]);
4.console.log(num[1]);
Array Constructor
You create an array by using the array constructor. Array constructor can be
passed as:
•A list of values separated by comma or,
•A numeric value which indicates the size of array
Example - Single Numeric Value
1.var num = new Array(5); // This single numeric value indicates the siz
e of array.
2.var i;
3.for(i=0;i<num.length;i++){ Example - Comma Separated Values
4.num[i]=i*5; 1.var num = new Array(1,2,3,4,5);
5.console.log(num[i]); 2.var i;
6.} 3.for(i=0;i<num.length;i++){
4.console.log(num[i]);
5.}
ES6 Multidimensional Arrays

ES6 also supports the multidimensional array concept. A multidimensional


array can be defined as an array reference to another array for its value.
a two-dimensional array is the simplest form of a multidimensional array.

Declaration
The following syntax illustrates you how to declare two-dimensional array
in JavaScript.
1.var array_name = [[value1,value2,value3],[val1,val2,val3]];

Accessing of Two-dimensional element of array


1.var array_name[initial_array_index][referenced_array_index]
1.var multi = [[2,3,4],[4,9,16]]
2.console.log(multi[0][0])
3.console.log(multi[0][1])
4.console.log(multi[0][2])
5.console.log(multi[1][0])
6.console.log(multi[1][1])
7.console.log(multi[1][2])
Passing Array to function
Passing array as an argument to a function, you have to specify the array
name (a reference to an array) without brackets. Let us try to understand it
with the following example.
Example
1.var rainbow = new Array("Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red“);

2.function show(rainbow) {
var rainbow = new Array("Violet", "Indigo", "Blue",
3. for(var i = 0;i<rainbow.length;i++) {
"Green", "Yellow", "Orange", "Red");
4. console.log(rainbow[i])
var show =(rainbow)=>{
5. }
for(var i = 0;i<rainbow.length;i++)
6.}
{
7.show(rainbow)
console.log(rainbow[i])
}
}
show(rainbow)
Return Array from function
1.function show() {
2. return new Array("Blue", "Red", "Green", "Yellow")
3. }
4. var colors = show()
5. for(var i in colors) {
6. console.log(colors[i])
7. }
ES6 Array methods
The array methods introduced in ES6 are tabulated below.

S.no. Methods Description


1. Array.from() It converts array-like values and iterable values into arrays.
2. Array.of() It creates an instance from a variable number of arguments instead of the
number of arguments or type of arguments.

3. Array.prototype.copyWithi It copies the part of an array to a different location within the same array.
n()
4. Array.prototype.find() It finds a value from an array, based on the specific criteria that are passed to
this method.
5. Array.prototype.findIndex( The Array.prototype.findIndex() returns the index of the first element of the
) given array that satisfies the given condition.

6. Array.prototype.entries() It returns an array iterator object, which can be used to loop through keys
and values of arrays.
7. Array.prototype.keys() It returns an array iterator object along with the keys of the array.

8. Array.prototype.values() it provides the value of each key.


9. Array.prototype.fill() It fills the specified array elements with a static value
Array.from()
It converts array-like values and iterable values into arrays.
Example
1.let name = Array.from('javaTpoint')
2.
3.console.log(name)
Array.of()
In ES5, when a single numeric value gets passed in the array constructor, then it will create an array of that
size. Array.of() is a new way of creating an array which fixes this behavior of ES5. By using this method, if
you are creating an array only with a single numeric value, then it will create an array only with that value
instead of creating the array of that size.
let name = Array.of(42,10)

console.log(name)
console.log(name.length)
)
Array.copyWithin()
This method copies the part of an array to a different location within the same array.
It returns the modified array without any modification in its length.

Syntax
1.array.copyWithin(target, start, end)

1.const num = [1,2,3,4,5,6,7,8,9,10];


2.const num1 = [1,2,3,4,5,6,7,8,9,10];
3.const num2 = [1,2,3,4,5,6,7,8,9,10];
4.console.log(num.copyWithin(1,3,5));
5.console.log(num1.copyWithin(1,3)); //omitting the parameter end
6.console.log(num2.copyWithin(1)); //omitting the parameters start a
nd end
Array.prototype.find()

It finds a value from an array, based on the specific criteria that are passed to this method.
It returns the first element value that satisfies the given condition.

const numbers4 = [4, 9, 16, 25, 29];


let first = numbers4.find(myFunction);

function myFunction(value,index, array) {


return value > 7;
}
console.log(first);
Array Methods

map() creates a new array from calling a function for every array element.
map() calls a function once for each element in an array.
map() does not execute the function for empty elements.
map() does not change the original array.

const numbers = [65, 44, 12, 4];


const newArr = numbers.map(myFunction)
const numbers1 = [4, 9, 16, 25];
function myFunction(num) { const newArr1 = numbers1.map(Math.sqrt)
return num * 10; console.log(newArr1);
}
console.log(newArr);
The map() method creates a new array populated with the results of calling a provided function on every
element in the calling array.

const array1 = [1, 4, 9, 16];// Pass a function to map

const map1 = array1.map(x => x * 2);

console.log(map1);

// Expected output: Array [2, 8, 18, 32]


React ES6 Destructuring
Destructuring means to break down a complex structure into simpler parts.
With the syntax of destructuring, you can extract smaller fragments from
objects and arrays. It can be used for assignments and declaration of a
variable.
ES6 Array destructuring
Object destructuring
Destructuring is an efficient way to extract multiple values from data that is
stored in arrays or objects. When destructuring an array, we use their
positions (or index) in an assignment.
Before:
const vehicles = ['mustang', 'f-150', 'expedition']; // old way
const car = vehicles[0];
const truck = vehicles[1];
const suv = vehicles[2];

With destructuring:

const vehicles = ['mustang', 'f-150', 'expedition’];


const [car, truck, suv] = vehicles;
Array destructuring
Example
1.var arr = ["Hello", "World"]
2.
3.// destructuring assignment
4.var [first, second] = arr;
5.
6.console.log(first); // Hello
7.console.log(second); // World
Example
1.var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"];

2.
3.// destructuring assignment
4.var[color1, color2, color3] = colors;
5.
6.console.log(color1); // Violet
7.console.log(color2); // Indigo
8.console.log(color3); // Blue
Example
If you want to choose random elements from the given array then in array
destructuring you can perform it as follows:

1.var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"];


2.
3.// destructuring assignment
4.var[color1, ,color3, ,color5] = colors; //Leave space for unpick elements
5.console.log(color1); // Violet
6.console.log(color3); // Blue
7.console.log(color5); // Yellow
Array destructuring and Rest operator
By using the rest operator (…) in array destructuring, you can put all the
remaining elements of an array in a new array.

1.var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"];


2.
3.// destructuring assignment
4.var [a,b,...args] = colors;
5.console.log(a);
6.console.log(b);
7.console.log(args);
Array destructuring and Default values

If you are taking a value from the array and that value is undefined, then you can assign a
default value to a variable.

1.var x, y;
2.
3.Var [x=50, y=70] = [100];
4.console.log(x); // 100
5.console.log(y); // 70
Swapping Variables
The values of the two variables can be swapped in one destructuring
expression. The array destructuring makes it easy to swap the values of
variables without using any temporary variable.

1.var x = 100, y = 200;


2.Var [x, y] = [y, x];
3.console.log(x); // 200
4.console.log(y); // 100
Parsing returned array from functions
A function can return an array of values. It is always possible to return an
array from a function, but array destructuring makes it more concise to
parse the returned array from functions.

Example
1.function array() {
2. return [100, 200, 300];
3.}
4.
5.var [x, y, z] = array();
6.
7.console.log(x); // 100
8.console.log(y); // 200
9.console.log(z); // 300
function calculate(a, b) {
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;

return [add, subtract, multiply, divide];


}

const [add, subtract, multiply, divide] = calculate(4, 7);


console.log(add);
console.log(subtract);
React ES6 Spread Operator
The JavaScript spread operator (...) allows us to quickly copy all or part
of an existing array or object into another array or object.

Syntax
1.var variablename1 = [...value];
Constructing array literal
When we construct an array using the literal form, the spread operator
allows us to insert another array within an initialized array.

Example
1.let colors = ['Red', 'Yellow'];
2.let newColors = [...colors, 'Violet', 'Orange', 'Green'];
3.console.log(newColors);

Concatenating arrays
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];
console.log(numbersCombined);
Copying an array
Example
Without using spread operator
1.let colors = ['Red', 'Yellow'];
1.let colors = ['Red', 'Yellow']; 2.let newColors = colors;
2.let newColors = [...colors]; 3.newColors.push('Green');
3.console.log(newColors); 4.console.log(newColors);
5.console.log(colors);
Using spread operator
1.let colors = ['Red', 'Yellow'];
2.let newColors = [...colors];
3.newColors.push('Green');
4.console.log(newColors);
5.console.log(colors);
If we copy the array elements without using the spread operator, then inserting a new element
to the copied array will affect the original array.
But if we are copying the array by using the spread operator, then inserting an element in the
copied array will not affect the original array.
Destructuring Objects

const vehicleOne = {
const vehicleOne = {
brand: 'Ford',
brand: 'Ford',
model: 'Mustang',
model: 'Mustang',
type: 'car',
type: 'car',
year: 2021,
year: 2021,
color: 'red'
color: 'red'
}
}
myVehicle(vehicleOne);
myVehicle(vehicleOne);
// old way
function myVehicle({type, color, brand, model}) {
function myVehicle(vehicle) {
const message = 'My ' + type + ' is a ' + color + ' ‘
const message = 'My ' + vehicle.type + ' is a ‘
+ brand + ' ' + model + '.';
+ vehicle.color + ' ' + vehicle.brand + ‘
}
' + vehicle.model + '.';
}

You might also like