JavaScript ES6
ES6, also known as ECMAScript 2015, is the sixth major revision of the JavaScript language. It introduced many new features and syntax improvements to the language, making it more powerful and easier to work with.
One of the most significant changes in ES6 was the introduction of block-scoped variables using the let and const keywords. These keywords allow developers to declare variables that are only accessible within a specific block of code, rather than at the function or global level. This makes it easier to write clean, maintainable code that avoids naming conflicts and reduces the risk of bugs.
ES6 also introduced arrow functions, which provide a more concise syntax for defining functions and template literals, which allow for easy string interpolation and multi-line strings. Additionally, it added new data types like Map and Set, which provide more flexible alternatives to traditional arrays and objects.
Other notable features of ES6 include classes, which provide a more familiar syntax for creating objects and working with inheritance, and the spread operator, which allows for easier manipulation of arrays and objects. It also introduced generators, which allow for easy iteration over data structures, and async/await syntax for working with asynchronous code.
String Template
Backtick (‘) characters are used to surround template literals instead of double or single quotes.
Template literals are composed of normal strings as well as placeholders, which are embedded expressions separated by a dollar sign and curly braces: ${expression}. The functions you give or the default function get the strings and placeholders as input. When you don’t provide your own, the default function just uses string interpolation to replace the placeholders before joining the individual strings together to produce a single string.
To provide your own function, place a function name before the template literal; the resulting object is referred to as a tagged template. The template literal will then be provided to your tag function so that you can do any operations you like on its various components.
Put a backslash (\) before the backtick in a template literal to escape it.
Example:
var age = 25
var name = 'Gauss'
console.log('My name is ' + name + ' and I\'m ' + age + ' years old.'); //ES5
console.log(`My name is ${name} and I\'m ${age} years old`); //ES6
console.log(name.padStart(10, '*')); // Fill 10 charecter with * before
console.log(name.padEnd(10, '*')); // Fill 10 charecter with * after
console.log('GA'.repeat(10)); // Repeat the given portion 10 times
Output:
My name is Gauss and I'm 25 years old.
My name is Gauss and I'm 25 years old
*****Gauss
Gauss*****
GAGAGAGAGAGAGAGAGAGA
Let vs Cons vs Var
Variables in JavaScript could only be declared using the var keyword prior to the release of ES2015 (ES6); however, let and const, two additional ways to declare variables, were introduced with ES6. This frequently raises issues, chiefly around the choice of keyword.
var | let | const | |
Scope | Variables declared with var are in the function scope. | Variables declared as let are in the block scope. | Variables declared as const are in the block scope. |
Hoisting | Allowed | Not allowed | Not allowed |
Reassign the value | allowed | allowed | Not allowed |
Redeclaration of the variable | allowed | Not allowed | Not allowed |
Arrow Function
A typical function expression can be more compactly expressed using an arrow function expression, however, it has limitations and isn’t applicable in all circumstances.
There are some restrictions and discrepancies between arrow functions and conventional functions:
- Arrow functions shouldn’t be used as methods because they lack their own bindings to this, arguments, or super.
- There is no access to the new.target keyword in arrow functions.
- For call, apply, and bind methods, which typically depend on setting a scope, arrow functions are not appropriate.
- It is not possible to utilize arrow functions as constructors.
- Within its body, arrow functions cannot utilize yield.
Example:
function add(a, b) { // A regular function expression
return a + b
}
console.log(add(112, 345));
let sum = (a,b) => a + b //An arrow function expression
console.log(sum(123,678));
Output:
457
801
Rest & Spread Operator
The spread and rest operators in JavaScript are represented by three dots (…). These two operators, however, are not equivalent.
The key distinction between the rest and spread operators is that a JavaScript array contains the remains of a particular set of user-supplied values when using the rest operator. Iterables are expanded into separate elements using the spread syntax, though.
The three-dot (…) operator is referred to as a rest operator when it is used as a function argument. It is known as the spread operator in all other circumstances.
Example:
function sum(...rest) { // (...) as rest operator
return rest.reduce((a,b) => a+b)
}
console.log(sum(1, 2, 3, 4, 5));
let a = [1, 2, 3, 4, 5]
console.log(...a); // (...) as spread operator
let obj = {
a: 10,
b: 50,
c: 89,
d: 56
}
let obj2 = {
...obj // (...) as spread operator
}
console.log(obj2);
Output:
15
1 2 3 4 5
{a: 10, b: 50, c: 89, d: 56}
Destructuring
With the use of the JavaScript language “destructuring,” we may take information from maps, objects, and arrays and set it into fresh, new variables. We can extract many properties or objects from an array at once by destructuring.
Example:
let person = {
name: 'Gattuso',
profession: 'Football Coach',
age: 45,
address: {
city: 'Milan',
country: 'Italy'
}
}
let { name, profession, address: { city, country }, age } = person
console.log(`Hi! I\'m ${name}. I'\m a professional ${profession} from ${city}, ${country}.`);
Output:
Hi! I'm Gattuso. I'm a professional Football Coach from Milan, Italy.
Getter and Setter
Getters and setters are used in Javascript to define object accessors (Computed Properties). An accessor utilizes a function to retrieve or modify an object’s value. When certain tasks need to be completed automatically before changing or obtaining an object’s value, such as reformatting strings, gaining access to private attributes, initiating events, etc., accessors come in handy. In JavaScript, getter methods are used to access the properties of an object, and setter methods are used to change the values of an object. Also, see Python getter and setter Methods.
Example:
var Rectangle = function () {
var position = {
x: 54,
y: -90
}
this.draw = function () {
console.log('I\'m a rectangle');
console.log(`Poition: X = ${position.x} and Y = ${position.y}`);
}
Object.defineProperty(this, 'position', {
get: function () {
return position
},
set: function (value) {
position = value
}
})
}
var rect = new Rectangle()
console.log(rect.position);
rect.position = {
x:93,
y:-37
}
console.log(rect.position);
Output:
{x: 54, y: -90}
{x: 93, y: -37}