React uses ES6’s features such as class, arrow functions, variables(let, var, const), for..in, for..of, and others.
Classes
class User { constructor(name) { this.name = name; } present() { return 'Hi my name is ' + this.name; } } class Employee extends User { constructor(name, age) { super(name); this.age = age; } show() { return this.present() + ', I am ' + this.age + ' years old'; } } Jimmy = new Employee("Jimmy", 25);
A class can have attributes, methods, and state. You can extend a class and add functionality.
Arrow functions
Regular JS
sayHi = function(name) { return "Hi! my name is " + name; }
ES6 arrow function
sayHi = (name) => { return "Hi! my name is " + name; }
Default functions
In ES6, a function allows the parameters to be initialized with default values if no values are passed to it or it is undefined.
function add(a, b = 1) { return a+b; } console.log(add(4)) 5 console.log(add(4,2)) 6
Rest Parameters
You can pass in as many parameters to a method but the values passed must all be of the same type.
function fun1(...params) { console.log(params.length); } fun1(); 0 fun1(5); 1 fun1(5, 6, 7); 3
Variables
There are three ways to defined variables with ES6:
a. var(outside of a function) is used as a global variable.
b. var(inside of a function) only belongs to that function.
c. var(inside of a block, like if-statement or for-loop) is still available outside of the block.
d. let is block or function scope.
e. const is used to create variables that don’t change once initialized.
For in
for…in loop is used to loop through an object’s properties
for (variablename in object) {
statement or block to execute
}
var user = {name:"John", age:2, id:1}; for (var attribute in user) { console.log(user[attribute]); } // print out int the order they are organized. John 2 1
For of
for…of loop is used to iterate iterables like array and map.
let names = ['Folau', 'Lisa', 'Kinga', 'Fusi']; for (let name of names) { console.log(name); } Folau Lisa Kinga Fusi