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 - List - Append, Count, Extend, Index, Insert, Pop, Remove, Reverse, Sort

🐍 Advance List List is widely used and it's functionalities are heavily useful. Append Adds one element at the end of the list. Syntax list1.append(value) Input l1 = [1, 2, 3] l1.append(4) l1 Output [1, 2, 3, 4] append can be used to add any datatype in a list. It can even add list inside list. Caution: Append does not return anything. It just appends the list. Count .count(value) counts the number of occurrences of an element in the list. Syntax list1.count(value) Input l1 = [1, 2, 3, 4, 3] l1.count(3) Output 2 It returns 0 if the value is not found in the list. Extend .count(value) counts the number of occurrences of an element in the list. Syntax list1.extend(list) Input l1 = [1, 2, 3] l1.extend([4, 5]) Output [1, 2, 3, 4, 5] If we use append, entire list will be added to the first list like one element. Extend, i nstead of considering a list as one element, it joins the two lists one after other. Append works in the following way. Input l1 = [1, 2, 3] l1.append([4, 5]) Output...

Difference between .exec() and .execPopulate() in Mongoose?

Here I answer what is the difference between .exec() and .execPopulate() in Mongoose? .exec() is used with a query while .execPopulate() is used with a document Syntax for .exec() is as follows: Model.query() . populate ( 'field' ) . exec () // returns promise . then ( function ( document ) { console . log ( document ); }); Syntax for .execPopulate() is as follows: fetchedDocument . populate ( 'field' ) . execPopulate () // returns promise . then ( function ( document ) { console . log ( document ); }); When working with individual document use .execPopulate(), for model query use .exec(). Both returns a promise. One can do without .exec() or .execPopulate() but then has to pass a callback in populate.

683 K Empty Slots

  Approach #1: Insert Into Sorted Structure [Accepted] Intuition Let's add flowers in the order they bloom. When each flower blooms, we check it's neighbors to see if they can satisfy the condition with the current flower. Algorithm We'll maintain  active , a sorted data structure containing every flower that has currently bloomed. When we add a flower to  active , we should check it's lower and higher neighbors. If some neighbor satisfies the condition, we know the condition occurred first on this day. Complexity Analysis Time Complexity (Java):  O(N \log N) O ( N lo g N ) , where  N N  is the length of  flowers . Every insertion and search is  O(\log N) O ( lo g N ) . Time Complexity (Python):  O(N^2) O ( N 2 ) . As above, except  list.insert  is  O(N) O ( N ) . Space Complexity:  O(N) O ( N ) , the size of  active . Approach #2: Min Queue [Accepted] Intuition For each contiguous block ("window") of  k  po...