ES6~Basic - rohit120582sharma/Documentation GitHub Wiki

let, const and Block Scoping



Arrow Functions

The arrow functions, also known as fat arrow functions, are a concise way to write function expressions.

  • this is bound lexically, meaning that fat arrow functions don’t have their own this and that this refers to the parent scope. The complete list of variables whose values are determined lexically is: arguments, super, this, new.target
  • It can’t be used as constructors or generators. Normal functions support new via the internal method [[Construct]] and the property prototype. Arrow functions have neither, which is why new (() => {}) throws an error.
  • There’s no arguments variable available with arrow functions.

Apart from that, there are no observable differences between an arrow function and a normal function. For example, typeof and instanceof produce the same results:

> typeof (() => {})
'function'
> () => {} instanceof Function
true

> typeof function () {}
'function'
> function () {} instanceof Function
true


Default Function Parameters

In order to help us create more flexible functions, ES6 introduces default parameters for functions.

function greeting(name = "Anonymous") {
	return "Hello " + name;
}
console.log(greeting("John")); // Hello John
console.log(greeting(null)); // Hello John
console.log(greeting(undefined)); // Hello Anonymous
console.log(greeting()); // Hello Anonymous

The default parameter kicks in when the argument is not specified (it is undefined)



Rest and Spread

Rest

ES6 introduces the rest operator for function parameters. With the rest operator, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.

function sum(...args) {
	return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6

Spread

ES6 introduces the spread operator, which allows us to expand arrays and other expressions in places where multiple parameters or elements are expected.

const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // returns 89

...arr returns an unpacked array. In other words, it spreads the array.

However, the spread operator only works in-place, like in an argument to a function or in an array literal. The following code will not work:

const spreaded = ...arr; // will throw a syntax error


for...of loop

var categories = ['hardware', 'software', 'vaporware'];
for(let item of categories){
	console.log(item);
}


Template Literals



Tag literal

function processInvoice(segments, ...values){
	console.log(segments);
	console.log(values);
}
let invoiceNum = '1350';
let amount = '2000';
processInvoice `Invoice: ${invoiceNum} for ${amount}`;
// ['Invoice: ', ' for ', '']
// [1350, 2000]


Destructuring

let count = 0;
for(let [a, b] of [[5, 10]]){
	console.log(a, b); // 5, 10
	count++;
}
console.log(count); // 1


⚠️ **GitHub.com Fallback** ⚠️