Rachel Cole

Rachel Cole

1560933486

ES6 and Beyond

How about learning some cool features of ES6 and Beyond (like, ES7, ES8).

Hello folks,

ES6, pretty much hyped topic these days in front-end world.

So, how about learning some cool features of ES6 and Beyond (like, ES7, ES8).

First thing first.

What ES means?
ES stands for ECMAScript.
What is the different between ECMAScript and JavaScript then?* ECMAScript is the standard whereas JavaScript is also the standard. But,

  • ECMAScript is specification whereas JavaScript is the implementation of ECMAScript specifications.

So, let’s get started.

What we are going to learn?

  • let
  • const
  • Object Rest/Spread properties
  • Arrow Function
  • String interpolation
  • Exponential **
  • Array.prototype.includes
  • String.prototype.padStart
  • String.prototype.padEnd
  • Object.values
  • Object.entries

Let

let is the new var but the advantage is that it is accessible & available within the scope only. Let’s see an example.

function let_n_var() {
    console.log(foo);
    if(true) {
        let foo = 'foo';
    }
}
let_n_var();
// Output: Uncaught ReferenceError: foo is not defined

In the above example, if you replace let with var, the output would be undefined and there will be no error. So, as you can see, let helps us to catch early errors and no scope mess.

Const

This is again a new way to declare var but the difference is that once a const is defined, we can not re-assign a value to it.

const baz = 'baz';
console.log('baz: ', baz);
// Output: baz
baz = 'baaz'
// Output: Uncaught TypeError: Assignment to constant variable.

As we know that JavaScript is dynamic language and we tend to do mistakes while updating the variables with different data type or data, const helps us to not override the values once set.

Object Rest/Spread properties

Lets look at it by example.

// Rest
const vowels = ['A', 'E', 'I', 'O', 'U'];
const [firstVowel, secondVowel, ...restVowels] = vowels;
console.log(firstVowel); // Output: 'A'
console.log(secondVowel);// Output: 'E'
console.log(restVowels); // Output: ['I', 'O', 'U']

In the above code snippet, I am trying to get the values from variable vowels into separate variables for first two vowel and remaining in rest variable.

Here are the steps to achieve the same.

  • Create a variable with array notation: [firstVowel, secondVowel]. Assign it the vowels variable. This will give us first two vowels in respective variables (based on index)
  • Now, part of third value in array notation, use ... with a variable name. eg. restVowels. So, the variable will look like const [firstVowel, secondVowel, ...restVowels]=vowels;
  • When code executes, it will create variables with values shown above. The alternate way of achieving the same result could be:
const firstVowel = vowels[0];
const secondVowel = vowels[1];
const restVowels = vowels.slice(2); // all remaining values

But, rest approach makes code more readable and manageable.

Here is the code sample for **spread **considering the above code block (used for rest)

// Rest
const vowels = ['A', 'E', 'I', 'O', 'U'];
const [firstVowel, secondVowel, ...restVowels] = vowels;
// Spread
const vowelsWithOneConsonant = ['B', ...vowels];
console.log(vowelsWithOneConsonant); // Output: ['B', 'A', 'E', 'I', 'O', 'U']

As you can see above, it is very easy to spread the variable vowels to create a new variable with same and one added value too.

These same concepts can be applied on objects too. Go ahead and do some practice. It is fun to use once you learn get used to it.

Arrow Function

This is short hand notation of function but the binding of this works differently.

Let’s understand the syntax first.

// standard way of defining function
function getName() {
   console.log('getName function');
}
// converted to arrow function
const getName = () => {
   console.log('getName function');
}

This becomes more interesting and simple when returning values from function.

const getName = (name) => 'Hello' + name;
console.log(getName('Anand')); // Output: Hello Anand

At first glance, it may look confusing but lets break down the code little bit.

  1. We have created a const variable named getName
  2. Assigned a function shorthand used for arrow function () => {//function body}
  3. By default, arrow function do not need any {} brackets if our code do not expect more than one line. Use curly brackets if we need to. Without curly bracket, arrow function returns the executed code line. In the above example, it returns Hello Anand

So, the above code can also be written as shown below and the output will be same.

const getName = (name) => {
     return 'Hello' + name;
}
console.log(getName('Anand')); // Output: Hello Anand

After some practice, you will get it. Go ahead, fire up the browser console and do some practice. An exercise for you is to check how this behaves with arrow function in comparison to the normal function.

String interpolation

Early days in javascript, if we need to create string with some dynamic values, we used to use +. Sooner or later, it gets more confusing if it gets really bigger.

So, the string interpolation came to rescue. The syntax is to use back-tick (`) instead of single/double quotes. And, ${} helps us to put dynamic data without worrying about opening/closing of the sentance or going wrong about missing+ or single/double quotes.

Lets look at the example below:

// Old approach
var guest = 'all';
var name = 'Anand';
var age = 32;
var hobby1= "listening to music";
var hobby2 = "mobiles games";
const sayHello = "Hello " + guest + "! My name is " + name + ". My age is " + age + " years. My hobbies are " + hobby1 + ", "+ hobby2 + '.';
console.log(sayHello); // Output: Hello all! My name is Anand. My age is 32 years. My hobbies are listening to music, mobiles games.

I am sure, it is already looking confusing to you guys. Now look at the below example

// New approach
const guest = 'all';
const name = 'Anand';
const age = 32;
const hobby1= "listening to music";
const hobby2 = "mobiles games";
const sayHello = `Hello ${guest}! My name is ${name}. My age is ${age} years. My hobbies are ${hobby1}, ${hobby2}.`;
console.log(sayHello); // Output: Hello all! My name is Anand. My age is 32 years. My hobbies are listening to music, mobiles games.

Isn’t that cool. 😎

Exponential

I am sure you all know Exponent in mathematics. In Javascript, we used to use Math.pow(5, 6); // Output: 15625 to get the exponent.

Now, we have a short hand to get the same result by doing 3 ** 4; // Output: 15625.

So, we can say following:

Math.pow(5, 6) == 5 ** 6;

Array.prototype.includes

As it’s name suggests, we can use includes to get true or false result value by checking if the value is included or not.

Example:

[1, 2].includes(1); // true
[1, 3].includes(2); // false
var foo = 'foo';
foo.includes('f'); // true
foo.includes('F'); // false
// So, it is case sensitive too. Please take care.

String.prototype.padStart/String.prototype.padEnd

This one is quite interesting. Lets define it first.

padStart and padEnd is used to pad the current string with another string until the given string length reaches.

padStart applies padding from start (left) of the string. On the other hand padEnd applies padding from end (right) of the string.

These functions can apply padding to the current string with another string multiple times as well, if needed.
Let’s have a look to an example

// padStart
const cardNumber = '1234567812345678';
const last3Digit = cardNumber.slice(-3);
const maskedCardNumber = last3Digit.padStart(16, 'X');
console.log(maskedCardNumber); // Output: "XXXXXXXXXXXXX678"
// padEnd
const loremIpsum = "Lorem Ipsum is simply dummy text of the printing and";
const loremIpsumWithDots = loremIpsum.padEnd(loremIpsum.length+3, '.');
console.log(loremIpsumWithDots);
// Output: Lorem Ipsum is simply dummy text of the printing and...

How cool is that? It is pretty interesting and useful. Do practice though.

Object.values

Earlier, we used to use Object.keys if we need to iterate over an object. But now, we can use values or entries instead keys as per our need.

So, with Object.values, it returns all the enumerable properties values as an array. Then, it is easy to consume these values directly.

Example:

const objectFoo = {
   name: 'foo',
   isAvailable: false
};
Object.values(objectFoo);
// Output: ['foo', false]

Object.entries

On the other hand, Object.entries also gives an array but it contains objects’ own enumerable string key property [key, value] pairs. The order remains same as in provided by for...in.

Example:

const objectFoo = {
   name: 'foo',
   isAvailable: false
};
Object.entries(objectFoo);
// Output: [['name', 'foo'], ['isAvailable', false]]

Summary

That’s it for this post.

Posts

1

Thanks for reading ❤

2

If you liked this post, share it with all of your programming buddies!

3

Follow me on **[Facebook]( https://www.facebook.com/moriohdotcom)** | **[Twitter]( https://twitter.com/moriohdotcom)**

4

5

### Learn More

6

7

☞ [The Complete JavaScript Course 2019: Build Real Projects!](http://learnstartup.net/p/rJWeUz65Z "The Complete JavaScript Course 2019: Build Real Projects!") 

8

☞ [Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)](http://learnstartup.net/p/BJBa7-l-g "Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)")

9

☞ [JavaScript Bootcamp - Build Real World Applications](http://learnstartup.net/p/-J13WdymB "JavaScript Bootcamp - Build Real World Applications") 

10

☞ [The Web Developer Bootcamp](https://learnstartup.net/p/SJQU6Gxbg "")

11

☞ [JavaScript: Understanding the Weird Parts](http://learnstartup.net/p/HyUQWUMTqW "JavaScript: Understanding the Weird Parts")

12

☞ [ES6 Cool stuffs — A big fat Arrow](http://tech.learn4startup.com/15a776baf1 "")

13

☞ [Dropbox API / JavaScript ES6 Tutorial - Expense Organizer](http://tech.learn4startup.com/76794978c8 "")

14

☞ [ES6 Arrow Functions Cheatsheet](http://dev.edupioneer.net/4c6ec0b2ec "")

15

☞ [Modern JS with ES6](http://dev.edupioneer.net/b6cffce368 "")

16

☞ [These are the features in ES6 that you should know](http://dev.edupioneer.net/0b33b15561 "")

17

☞ [Get started with Next-Gen Javascript](http://dev.edupioneer.net/acd070a7a3 "")

18

19

*Originally published on [https://hackernoon.com](https://hackernoon.com/es6-and-beyond-28aed8574e00)*

#javascript #es6

What is GEEK

Buddha Community

ES6 and Beyond

ES6 Reduce Helper and ES6-Equivalent Code Using Reduce

Consider a simple scenario where you have an array of numbers and you want to return the sum of all elements in that array.

We will see that it’s a solution in ES5 and that it’s equivalent in ES6 to using reduce helper.

ES5 Code

  1. var numbers=[10,70,50,20];   
  2. var sum=0;  
  3. function additionOfElementsInArray(){  
  4.    for(var i=0;i<numbers.length;i++){  
  5.          sum += numbers[i]  
  6.    }  
  7.    return(sum);  
  8. }  
  9.    
  10. additionOfElementsInArray();  

The above code will return an output of 150.

ES6-Equivalent Code Using Reduce

  1. const numbers=[10,70,50,20];   
  2.    
  3. numbers.reduce(function(sum,numberElement){  
  4.    
  5.    return sum += numberElement;  
  6.    
  7. } ,0 );  

The above code will also return output as 150.

You can write the same code in ES6 using Reduce Helper with arrow function as follows, which will return the same output.

  1. const numbers=[10,70,50,20];  
  2.    
  3. numbers.reduce((sum,numberElement)=>sum += numberElement,0);

#es6 #es5 code #es6-equivalent code

Rachel Cole

Rachel Cole

1560933486

ES6 and Beyond

How about learning some cool features of ES6 and Beyond (like, ES7, ES8).

Hello folks,

ES6, pretty much hyped topic these days in front-end world.

So, how about learning some cool features of ES6 and Beyond (like, ES7, ES8).

First thing first.

What ES means?
ES stands for ECMAScript.
What is the different between ECMAScript and JavaScript then?* ECMAScript is the standard whereas JavaScript is also the standard. But,

  • ECMAScript is specification whereas JavaScript is the implementation of ECMAScript specifications.

So, let’s get started.

What we are going to learn?

  • let
  • const
  • Object Rest/Spread properties
  • Arrow Function
  • String interpolation
  • Exponential **
  • Array.prototype.includes
  • String.prototype.padStart
  • String.prototype.padEnd
  • Object.values
  • Object.entries

Let

let is the new var but the advantage is that it is accessible & available within the scope only. Let’s see an example.

function let_n_var() {
    console.log(foo);
    if(true) {
        let foo = 'foo';
    }
}
let_n_var();
// Output: Uncaught ReferenceError: foo is not defined

In the above example, if you replace let with var, the output would be undefined and there will be no error. So, as you can see, let helps us to catch early errors and no scope mess.

Const

This is again a new way to declare var but the difference is that once a const is defined, we can not re-assign a value to it.

const baz = 'baz';
console.log('baz: ', baz);
// Output: baz
baz = 'baaz'
// Output: Uncaught TypeError: Assignment to constant variable.

As we know that JavaScript is dynamic language and we tend to do mistakes while updating the variables with different data type or data, const helps us to not override the values once set.

Object Rest/Spread properties

Lets look at it by example.

// Rest
const vowels = ['A', 'E', 'I', 'O', 'U'];
const [firstVowel, secondVowel, ...restVowels] = vowels;
console.log(firstVowel); // Output: 'A'
console.log(secondVowel);// Output: 'E'
console.log(restVowels); // Output: ['I', 'O', 'U']

In the above code snippet, I am trying to get the values from variable vowels into separate variables for first two vowel and remaining in rest variable.

Here are the steps to achieve the same.

  • Create a variable with array notation: [firstVowel, secondVowel]. Assign it the vowels variable. This will give us first two vowels in respective variables (based on index)
  • Now, part of third value in array notation, use ... with a variable name. eg. restVowels. So, the variable will look like const [firstVowel, secondVowel, ...restVowels]=vowels;
  • When code executes, it will create variables with values shown above. The alternate way of achieving the same result could be:
const firstVowel = vowels[0];
const secondVowel = vowels[1];
const restVowels = vowels.slice(2); // all remaining values

But, rest approach makes code more readable and manageable.

Here is the code sample for **spread **considering the above code block (used for rest)

// Rest
const vowels = ['A', 'E', 'I', 'O', 'U'];
const [firstVowel, secondVowel, ...restVowels] = vowels;
// Spread
const vowelsWithOneConsonant = ['B', ...vowels];
console.log(vowelsWithOneConsonant); // Output: ['B', 'A', 'E', 'I', 'O', 'U']

As you can see above, it is very easy to spread the variable vowels to create a new variable with same and one added value too.

These same concepts can be applied on objects too. Go ahead and do some practice. It is fun to use once you learn get used to it.

Arrow Function

This is short hand notation of function but the binding of this works differently.

Let’s understand the syntax first.

// standard way of defining function
function getName() {
   console.log('getName function');
}
// converted to arrow function
const getName = () => {
   console.log('getName function');
}

This becomes more interesting and simple when returning values from function.

const getName = (name) => 'Hello' + name;
console.log(getName('Anand')); // Output: Hello Anand

At first glance, it may look confusing but lets break down the code little bit.

  1. We have created a const variable named getName
  2. Assigned a function shorthand used for arrow function () => {//function body}
  3. By default, arrow function do not need any {} brackets if our code do not expect more than one line. Use curly brackets if we need to. Without curly bracket, arrow function returns the executed code line. In the above example, it returns Hello Anand

So, the above code can also be written as shown below and the output will be same.

const getName = (name) => {
     return 'Hello' + name;
}
console.log(getName('Anand')); // Output: Hello Anand

After some practice, you will get it. Go ahead, fire up the browser console and do some practice. An exercise for you is to check how this behaves with arrow function in comparison to the normal function.

String interpolation

Early days in javascript, if we need to create string with some dynamic values, we used to use +. Sooner or later, it gets more confusing if it gets really bigger.

So, the string interpolation came to rescue. The syntax is to use back-tick (`) instead of single/double quotes. And, ${} helps us to put dynamic data without worrying about opening/closing of the sentance or going wrong about missing+ or single/double quotes.

Lets look at the example below:

// Old approach
var guest = 'all';
var name = 'Anand';
var age = 32;
var hobby1= "listening to music";
var hobby2 = "mobiles games";
const sayHello = "Hello " + guest + "! My name is " + name + ". My age is " + age + " years. My hobbies are " + hobby1 + ", "+ hobby2 + '.';
console.log(sayHello); // Output: Hello all! My name is Anand. My age is 32 years. My hobbies are listening to music, mobiles games.

I am sure, it is already looking confusing to you guys. Now look at the below example

// New approach
const guest = 'all';
const name = 'Anand';
const age = 32;
const hobby1= "listening to music";
const hobby2 = "mobiles games";
const sayHello = `Hello ${guest}! My name is ${name}. My age is ${age} years. My hobbies are ${hobby1}, ${hobby2}.`;
console.log(sayHello); // Output: Hello all! My name is Anand. My age is 32 years. My hobbies are listening to music, mobiles games.

Isn’t that cool. 😎

Exponential

I am sure you all know Exponent in mathematics. In Javascript, we used to use Math.pow(5, 6); // Output: 15625 to get the exponent.

Now, we have a short hand to get the same result by doing 3 ** 4; // Output: 15625.

So, we can say following:

Math.pow(5, 6) == 5 ** 6;

Array.prototype.includes

As it’s name suggests, we can use includes to get true or false result value by checking if the value is included or not.

Example:

[1, 2].includes(1); // true
[1, 3].includes(2); // false
var foo = 'foo';
foo.includes('f'); // true
foo.includes('F'); // false
// So, it is case sensitive too. Please take care.

String.prototype.padStart/String.prototype.padEnd

This one is quite interesting. Lets define it first.

padStart and padEnd is used to pad the current string with another string until the given string length reaches.

padStart applies padding from start (left) of the string. On the other hand padEnd applies padding from end (right) of the string.

These functions can apply padding to the current string with another string multiple times as well, if needed.
Let’s have a look to an example

// padStart
const cardNumber = '1234567812345678';
const last3Digit = cardNumber.slice(-3);
const maskedCardNumber = last3Digit.padStart(16, 'X');
console.log(maskedCardNumber); // Output: "XXXXXXXXXXXXX678"
// padEnd
const loremIpsum = "Lorem Ipsum is simply dummy text of the printing and";
const loremIpsumWithDots = loremIpsum.padEnd(loremIpsum.length+3, '.');
console.log(loremIpsumWithDots);
// Output: Lorem Ipsum is simply dummy text of the printing and...

How cool is that? It is pretty interesting and useful. Do practice though.

Object.values

Earlier, we used to use Object.keys if we need to iterate over an object. But now, we can use values or entries instead keys as per our need.

So, with Object.values, it returns all the enumerable properties values as an array. Then, it is easy to consume these values directly.

Example:

const objectFoo = {
   name: 'foo',
   isAvailable: false
};
Object.values(objectFoo);
// Output: ['foo', false]

Object.entries

On the other hand, Object.entries also gives an array but it contains objects’ own enumerable string key property [key, value] pairs. The order remains same as in provided by for...in.

Example:

const objectFoo = {
   name: 'foo',
   isAvailable: false
};
Object.entries(objectFoo);
// Output: [['name', 'foo'], ['isAvailable', false]]

Summary

That’s it for this post.

Posts

1

Thanks for reading ❤

2

If you liked this post, share it with all of your programming buddies!

3

Follow me on **[Facebook]( https://www.facebook.com/moriohdotcom)** | **[Twitter]( https://twitter.com/moriohdotcom)**

4

5

### Learn More

6

7

☞ [The Complete JavaScript Course 2019: Build Real Projects!](http://learnstartup.net/p/rJWeUz65Z "The Complete JavaScript Course 2019: Build Real Projects!") 

8

☞ [Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)](http://learnstartup.net/p/BJBa7-l-g "Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)")

9

☞ [JavaScript Bootcamp - Build Real World Applications](http://learnstartup.net/p/-J13WdymB "JavaScript Bootcamp - Build Real World Applications") 

10

☞ [The Web Developer Bootcamp](https://learnstartup.net/p/SJQU6Gxbg "")

11

☞ [JavaScript: Understanding the Weird Parts](http://learnstartup.net/p/HyUQWUMTqW "JavaScript: Understanding the Weird Parts")

12

☞ [ES6 Cool stuffs — A big fat Arrow](http://tech.learn4startup.com/15a776baf1 "")

13

☞ [Dropbox API / JavaScript ES6 Tutorial - Expense Organizer](http://tech.learn4startup.com/76794978c8 "")

14

☞ [ES6 Arrow Functions Cheatsheet](http://dev.edupioneer.net/4c6ec0b2ec "")

15

☞ [Modern JS with ES6](http://dev.edupioneer.net/b6cffce368 "")

16

☞ [These are the features in ES6 that you should know](http://dev.edupioneer.net/0b33b15561 "")

17

☞ [Get started with Next-Gen Javascript](http://dev.edupioneer.net/acd070a7a3 "")

18

19

*Originally published on [https://hackernoon.com](https://hackernoon.com/es6-and-beyond-28aed8574e00)*

#javascript #es6

Troy  Marvin

Troy Marvin

1593008048

ES6 Slides

Slides presenting major ES6 features and probable ES7 features. Also highlights what features are supported in node 4.2.*, the current LTS release

#es6 #node.js #es6 slides #programming

Myriam  Rogahn

Myriam Rogahn

1594649520

ES6 Concepts - Part One

Constants

Constants are block-scoped variables/arrays/objects which cannot be reassigned or redeclared in the same scope (Scope is defined by the nearest curly braces). Const declaration creates a read-only reference to a value but it is not immutable.

Syntax - const nameN = valueN;

Variable scope

Constant scope can be global/local depending on the block in which it is declared. However, you cannot access constant as window object property.

e.g.

constPI = 3.14;

console.log(window.PI) //output: undefined

Cons

Slow performance if code executes in temporal dead zone (i.e. accessing block scoped variable before definition is evaluated. Block scoped variables are not hoisted therefore accessing it before definition evaluation results in ReferenceError.)

#constants #es6 #es6 concepts

Makenzie  Pagac

Makenzie Pagac

1605335622

JavaScript: ES6 & Beyond

ECMAScript 2015(also known as ES6) is a major update to Javascript since ES5 which was standardized in 2009. Since then, Javascript has come up with incremental updates every year. These significant updates from ES6 and beyond are commonly referred to as Modern Javascript.

let and const

let allows you to declare variables that are limited to the scope of a block statement or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.

function varTest() {
  var x = 1
  {
    var x = 2 // same variable
    console.log(x) // 2
  }
  console.log(x) // 2
}
function letTest() {
  let x = 1
  {
    let x = 2 // different variable
    console.log(x) // 2
  }
  console.log(x) // 1
}

const are block-scoped, much like variables declared using the let keyword. Once used, the variable can’t be reassigned. In other words, it’s an _immutable variable_except when it used with objects.

const pi = 3.14
pi = 4 // TypeError, Attempted to assign to readonly property

const name = {firstname: "piyush"}
name.firstname = "sherlock"
name.lastname = "holmes"
console.log(name) 
// Object{firstname: "sherlock", lastname: "holmes}

Template Literals

Template literals allow us to embed expressions in strings with a cleaner syntax.

Template literals are enclosed by the backtick ( ) character instead of double or single quotes.

// ES5
let name = "Piyush"
let msg = "Hello," + " " + name + "." // Hello, Piyush.

// ES6
let name = "Piyush"
let msg = `Hello, ${name}.` // Hello, Piyush.

Arrow Functions

Arrow functions are a syntactically compact alternative to a regular function expression. It makes your code more readable and structured.

// ES5
const isEven = function (num) {
 return num % 2 === 0;
}
// ES6
const isEven = num => num % 2 === 0;

Also, you can use Arrow functions with built-in functions like map, filter, and reduce.

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const odds = nums.filter(n => n % 2 === 1);

console.log(nums); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(odds); // [1, 3, 5, 7, 9]

The handling of this is also different in arrow functions compared to regular functions. In regular functions the this keyword represented the object that called the function, which could be the window, the document or whatever. With arrow functions the this keyword always represents the object that defined the arrow function.

Default Parameters

It allows named parameters to be initialized with default values if no value or undefined is passed.

// ES5
function multiply(a, b) {
  b = typeof b !== 'undefined' ? b : 1;
  return a * b;
}
console.log(multiply(5, 2)); // 10
console.log(multiply(5)); // 5
// ES6
function multiply(a, b = 1) {
  return a * b;
}
console.log(multiply(5, 2)); // 10
console.log(multiply(5)); // 5

Spread (…)

It allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Spread for function calls

Expands an iterable(array, string, etc) into a list of arguments.

const nums = [1, 3, 2, 7, 5];
Math.max(nums); // NaN

// Use spread!
Math.max(...nums); // 7

Spread for array literals

Create a new array using an existing array. Spreads the elements from one array into a new array.

const nums1 = [1, 2, 3];
const nums2 = [4, 5, 6];

[...nums1, ...nums2]
// [1, 2, 3, 4, 5, 6]

Spread for object literals

Copies properties from one object into another object literal.

const name = {firstname: "piyush", lastname: "sinha"};                       
const name = {firstname: "piyush", lastname: "sinha"};

const fullAddress = {...address, country: "india"};
// {city: "mumbai", state: "maharashtra", country: "india"}
const details = {...name, ...fullAddress};
// {firstname: "piyush", lastname: "sinha", city: "mumbai", state: "maharashtra", country: "india"}

Destructuring

A short, clean syntax to _unpack _values from arrays, or properties from objects into distinct variables.

Array Destructuring

const raceResults = ["Jazz", "Ibtesam", "Farhaz", "Kunal"];

const [gold, silver, bronze] = raceResults;
gold; // "Jazz"
silver; // "Ibtesam"
bronze; // "Farhaz"
const [fastest, ...everyoneElse] = raceResults;
fastest; // "Jazz"
everyoneElse; // ["Ibtesam", "Farhaz", "Kunal"]

Object Destructuring

const runner = {
  first: "Piyush",
  last: "Sinha", 
  country: "India"
}
const {first, last, country} = runner;
first; // "Piyush"
last; // "Sinha"
country; // "India"

Parameters Destructuring

const fullName = ({first, last}) => {
 return `${first} ${last}`
}

const runner = {
  first: "Piyush",
  last: "Sinha", 
  country: "India"
}
fullName(runner); // "Piyush Sinha"

#javascript #es6 #web-development #programming #developer