Skip to main content

New in Javascript ES6

New String Functions in Javascript ES6

Input

let name = "Vinit Khandelwal"
console.log(name.startsWith("v"));
console.log(name.startsWith("V"));
console.log(name.includes("t K"));
console.log(name.includes("l "));
console.log(name.repeat(3));

Output

false
true
true
false
Vinit KhandelwalVinit KhandelwalVinit Khandelwal

New Arrow Function in Javascript ES6

Input

birthYears = [1989, 1986, 1985, 1991, 1965]
// ES5
var ages5 = birthYears.map(function(birthYear) {
return 2019-birthYear;
});
console.log(ages5);

// ES6
// Single line
let ages6 = birthYears.map(birthYear => 2019-birthYear);
console.log(ages6);

// Map with Element and index
ages6 = birthYears.map((birthYear, index) => `index ${index} age ${2019-birthYear}`);
console.log(ages6);

// Multi line function inside map
ages6 = birthYears.map((birthYear, index) => {
const str = `index ${index} age ${2019-birthYear}`;
return str;
});
console.log(ages6);

Output

[ 30, 33, 34, 28, 54 ]
[ 30, 33, 34, 28, 54 ]
[ 'index 0 age 30',
  'index 1 age 33',
  'index 2 age 34',
  'index 3 age 28',
  'index 4 age 54' ]
[ 'index 0 age 30',
  'index 1 age 33',
  'index 2 age 34',
  'index 3 age 28',
  'index 4 age 54' ]

Use of this inside functions - ES5 vs ES6

// ES5 way
var box5 = {
name: "VK",
showName: function() {
var self = this;
document.querySelector('body').addEventListener("click", function() {
alert(self.name);
});
}
}
box5.showName();

// ES6 way
const box6 = {
name: "VK",
showName: function() {
document.querySelector('body').addEventListener("click", () => {
alert(this.name);
});
}
}
box6.showName();

Destructuring

Array destructuring

const list = [1, 2];
const [j, k] = list
console.log([j, k], list);

Object destructuring

const obj = {
a: 1,
b: 2
};
const {a: x, b: y} = obj;
const {a, b} = obj;
console.log({x, y, a, b}, obj);

Dealing with Array of nodes in DOM

// ES5
boxes = document.querySelectorAll('.list-brief__item__content');
var boxesArr5 = Array.prototype.slice.call(boxes);
boxesArr5.forEach(function(cur) {
cur.style.backgroundColor = 'blue';
});

// ES6
Array.from(boxes).forEach(cur => cur.style.backgroundColor = 'green');

Array functions

var ages = [10,20,30,40,35,25];

console.log("ES5");
var full = ages.map(function(cur) {
return cur >= 35;
});
console.log(full);
console.log(full.indexOf(true)); // returns index of first instance found
console.log(ages[full.indexOf(true)]); // To return the value of that index

console.log("ES6");
console.log(ages.findIndex(age => age >= 35)); // returns index of first instance found
console.log(ages.find(age => age >= 35)); // returns value of first instance found

Spread Operator

function addAges (a, b, c, d) {
return a+b+c+d;
}

var ages = [18, 30, 15, 36];

console.log("ES5");
var sum1 = addAges.apply(null, ages);
console.log(sum1);

console.log("ES6");
const sum2 = addAges(...ages); // Spread Operator ...
console.log(sum2);

Output

ES5
99
ES6
99

Spread Operator to combine two or more arrays into one

const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr = [...arr1, 7, ...arr2];
console.log(arr);

Output

[ 1, 2, 3, 7, 4, 5, 6 ]

Convert Node List to Array

const node_list = document.querySelectorAll('.some_class');
Array.from(node_list).forEach(node => node.style.color = 'green');

Passing Variable Arguments in Functions

function func1() {
console.log('ES5 uses arguments keyword to access arguments. It needs to be converted to an array to use.');
var argsArr = Array.prototype.slice.call(arguments);
argsArr.forEach(function(age) {
console.log((2016-age) >= 18);
})
}

function func2(...ages) {
console.log('ES6 uses Rest operator which passes any number of arguments as list.');
ages.forEach(age => console.log((2016-age) >= 18));
}

ageList = [1990, 1999, 1965, 2015, 1987];
func1(ageList);
func2(ageList);

Output

ES5 uses arguments keyword to access arguments. It needs to be converted to an array to use.
false
ES6 uses Rest operator which passes any number of arguments as list.
false

Default Parameters

// ES5
function func1 (name, age) {
name === undefined ? name = 'Alex' : name = name;
age === undefined ? age = 18 : age = age;
this.name = name;
this.age = age;
}

// ES6
function func2 (name = "Alex", age = 18) {
this.name = name;
this.age = age;
}

var john = new func1('John');
console.log(john);
var emily = new func1('Emily', 35);
console.log(emily);
var alex = new func1();
console.log(alex);

var johnny = new func2('John');
console.log(johnny);
var jemily = new func2('Emily', 35);
console.log(jemily);
var alexa = new func2();
console.log(alexa);

Output

func1 { name: 'John', age: 18 }
func1 { name: 'Emily', age: 35 }
func1 { name: 'Alex', age: 18 }
func2 { name: 'John', age: 18 }
func2 { name: 'Emily', age: 35 }
func2 { name: 'Alex', age: 18 }

Maps in ES6 for HashMap

const q = new Map();
q.set('q1', 'What is your name?');
q.set('q2', 'What is your age?');
console.log(q);
console.log(q.get('q2'));
console.log(q.get('q1'));
console.log(q.size);
q.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
for (let pair of q.entries()) {
console.log(typeof(pair));
console.log(pair);
}
for (let [key, value] of q.entries()) {
console.log(typeof(key));
console.log(`${key}: ${value}`);
}
q.delete('q1');
q.delete('q1');
console.log(q);
console.log(q.has('q2'));
q.clear();
console.log(q);

Output

Map { 'q1' => 'What is your name?', 'q2' => 'What is your age?' }
What is your age?
What is your name?
2
q1: What is your name?
q2: What is your age?
object
[ 'q1', 'What is your name?' ]
object
[ 'q2', 'What is your age?' ]
string
q1: What is your name?
string
q2: What is your age?
Map { 'q2' => 'What is your age?' }
true
Map {}
Classes in ES6
// ES5
var Person5 = function(name, yob, job) {
this.name = name;
this.yob = yob;
this.job = job;
}

Person5.prototype.calcAge = function() {
var age = 2019 - this.yob;
console.log(age);
}

var john5 = new Person5('John', 1990, 'techer');
john5.calcAge();

// ES6
class Person6 {
constructor (name, yob, job) {
this.name = name;
this.yob = yob;
this.job = job;
}

calcAge() {
console.log(2019-yob);
}

static greeting() {
console.log("Hey there!");
}
}

const jimmy = new Person5('Jimmy', 1989, 'software engineer');
jimmy.calcAge();
Person6.greeting();

Output

29
30
Hey there!

Comments

Popular posts from this blog

Python - Mathematical Functions - Hexadecimal, Binary, Exponential, Absolute, Round

🐍 Some mathematical functions are in-built in python. Here are some of them. Convert Decimal to Hexadecimal hex(246) Output: '0xf6' hex(512) Output: '0x200' 0x is prefix to all hexadecimal numbers in output. The number after 0x is the hexadecimal value. Convert Decimal to Binary bin(1234) Output: '0b10011010010' bin(246) Output: '0b11110110' bin(512) Output: '0b1000000000' Exponential Function pow() function is similar to num1**num2, but it comes useful when you want to execute (num1**num2)%num3. Passing three arguments to pow(), does this. pow(3,4) Output: 81 This works just like 3**4 pow(3,4,5) Output: 1 But this, works equivalent to (3**4)%5. Either of the two ways can be used. At this point I feel (3**4)%5 is better, as anybody reading the code will understand what is being done immediately. While with pow(2,3,4), the person may have to refer to documentation to understand how this function works. Absolute Value The function abs() is used ...

Two Ways of rendering in React Examples

Two Ways of rendering in React Examples 1 - Render twice HTML < div id = "p1" ></ div > < div id = "p2" ></ div > CSS . person { display : inline - block ; margin : 10px ; border : 1px solid # eee ; box - shadow : 0 2px 2px # ccc ; } JAVASCRIPT (Babel) function Person ( props ) { return ( < div className = ' person "> < h1 >{ props . name }</ h1 > < p > Age :{ props . age }</ p > </ div > ); } ReactDOM . render (< Person name = "VK" age = "29" />, document . querySselector ( '#p1' )); ReactDOM . render (< Person name = "HK" age = "28" />, document . querySselector ( '#p2' )); 2 Render all at once HTML < div id = "app" ></ div > CSS . person { display : inline - block ; margin : 1...

Binary Tree Traversal in Python - In Order, Pre Order, Post Order

Binary Tree Traversal in Python - In Order, Pre Order, Post Order Run the code here to see output:  https://repl.it/@VinitKhandelwal/iterative-traversal-of-binary-tree # Node Class to Create Object of Nodes class Node (): def __init__ ( self , value , left= None , right= None ): self .value = value self .left = left self .right = right # Creation of a Binary Tree class BinaryTree (): def __init__ ( self , mylist ): self .mylist = mylist self .root=Node ( None ) for value in self .mylist : self .curr= self .root self ._add ( value ) def _add ( self , value ): if self .curr.value == None : self .curr.value = value else : if self .curr.value > value : if self .curr.left == None : self .curr.left = Node ( value ) else : self .curr = self .curr.left self ._add ( value ) else : if self...