Hey! Absolutely you are blessed with some fantastic ES6 features which have added a new dimension to JS making it more powerful and enjoyable to work with. So, overall some important JS features you have to know altime.
Here are the top 10 ES6 features explained with simple examples:
- let and const with Scope
let
: Allows you to create variables যেটা একবার declare করার পর আপনি যতবার ইচ্ছে change করতে পারবেন, তবে অবশ্যই block scope এর মধ্যে।const
: Creates variables যেটা একবার dcelare করার পর এর value আর কখনো chang করতে পারবেন না।
Previously, কোনও variable কে JS এ var দিয়ে declare করা হতো। var দিয়ে কোনো variable কে declare করা মানে সেটা Global scope বা Function scope. মানে, var দিয়ে declare করা কোনো variable কে সম্পূর্ণ code এর যেকোনো জায়গা থেকে access করা যাবে। এমনকি function scope এবং block scope এর ভেতরেও access করা যাবে।
let বা const দিয়ে কোনো variable declare করা মানে সেটা Block scope. মানে, কোনো variable কে let বা const দিয়ে কোনো block এর মধ্যে declare করলে সেটা block এর বাইরে অন্য কোথাও access করা যাবে না।
let count = 5;
count = 10;
const pi = 3.14;
// pi = 3.14159; // Error!
To know details about “What is scope”, you should better search it in google… right? 😆😀
2. Arrow function
Regular Function কে আরো short করে এবং clean ভাবে লিখার জন্য arrow function খুবই জনপ্রিয়।
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
আমরা ৩ ভাবে arrow function লিখতে পারি:
- যখন কোন parameter থাকবে না তখন তোমাকে empty first bracket অবশ্যই দিতে হবে
// Arrow function
const greet = () => console.log('hello');
- যখন একটা parameter থাকবে তুমি কোনো bracket না দিলেও হবে
// Arrow function
const add = a => a + 1;
- যখন একাধিক parameters থাকবে তখন তোমাকে first bracket অবশ্যই দিতে হবে
// Arrow function
const add = (a, b) => a + b;
3. Template literal
In ES6, you can use ${PARAMETER}
(a new syntax) inside of the back-ticked string.
let name = `My name is ${firstName} ${lastName}`
While using ES5, you had to break string like below. তুমি চাইলে এখনও এটা use করতে পারবে ES6 এর মধ্যে। কোনো error দিবেনা। কিন্তু, এটা বড় কোনো লাইন লিখতে গেলে যথেষ্ট time-consuming. তাই না?
let name = 'My name is ' + firstName + ' ' + lastName
4. for…of for…in
for...of
: A more readable loop for arrays.
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
console.log(num);
}
for...in
: Is used to iterate through the properties of an object.
const person = {
name: 'Alice',
age: 25,
occupation: 'Engineer'
};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
5. Destructuring
Two types of destructuring you will found.
- Array destructuring
- Object destructuring
//Array Destructuring
let colors = ["Red", "Pink", "Blue", "Black"];
let [color1, color2] = colors; // destructuring
console.log(color1, color2);
//Object Destructuring
let person = {name: "Monalisa", age: 28};
let {name, age} = person; // destructuring
console.log(name, age);
Array এর কোনো element destructure করতে হলে অবশ্যই sequence maintain করতে হবে। যেমন তুমি একটা উপরের example এ একটা array নিয়েছো এবং সেখানে কিছু color এর নাম আছেঃ red, pink, blue, black. এখন সেখান থেকে red color এবং pink color টা নিতে চাইলে তোমাকে sequence অনুযায়ী destructure করতে হবে। তোমার array তে red আগে এসেছে তাহলে তুমি red এর জন্য যে variable টা নিচ্ছো সেটা আগে লিখতে হবে। এরপর pink second index এ আছে, তাই pink এর variable টা second এ থাকতে হবে।
তবে, একটা Object এর কোনো property destructure করার সময় তোমাকে কোনো sequence maintain করতে হবেনা। তুমি let {name, age} = person;
এর পরিবর্তে let {age, name} = person;
দিলেও কোনো সমস্যা নেই।
In ES5, you had to use below approach for array destructuring:
var colors = ["Red", "Pink", "Blue", "Black"];
var color1 = colors[0]; // destructuring 1st element
var color2 = colors[1]; // destructuring 2nd element
console.log(color1, color2);
In ES5, you had to use below approach for object destructuring:
var person = {name: "Monalisa", age: 28};
var name = person.name;
var age = person.age;
console.log(name); // Monalisa
console.log(age); // 28
6. Spread & Rest operator
Spread operator unpacks elements from array, while the rest operator gathers/ packs elements back into an array.
// spread operator
const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
console.log(newArr); //[1,2,3,4,5]
// rest operator
function sum(...numbers) {
let total = 0;
for (const number of numbers) {
total += number;
}
return total;
}
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
উপরের example এ, sum
function টা যেকোনো number of arguments নিতে পারে parameter হিসেবে and gathers them into the numbers
array using the rest operator ...numbers
. তাহলে, Function এর ভেতর আমরা numbers
এই array টার উপর loop চালাচ্ছি এবং সবগুলো value যোগ করে sum বের করছি ।When you call sum(1, 2, 3, 4, 5)
, the function treats all the provided values as elements of the numbers
array and returns the sum, which is 15
in this case.
7. Default parameter
এখানে, default parameter use করার মানে হল, function টা call করার সময় parameter pass না করলেও code কোনো error generate করবে না। আর parameter pass করা হলে তখন সেই default parameter টা replace হয়ে যাবে parameter হিসেবে pass করা value দিয়ে। অনেকটা Logicall OR operator এর মতো।
function greet(name = 'Sakib Al Hasan') {
console.log(`Hello, ${name}!`); // Output-> Hello, Sakib Al Hasan!
}
greet() // function calling
Logic behind the above code => name = name || ‘Sakib Al Hasan’
8. Multi-line string
In ES6, it is very simple. Just use back-ticks, neither extra addition operators nor \n
are needed.
let poemData = `Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.`
In ES5, you had to use below approach:
var poemData = 'Twinkle, twinkle, little star,\n'
+ 'How I wonder what you are.\n'
+ 'Up above the world so high,\n'
+ 'Like a diamond in the sky.'
9. Map, filter, find
map()
: It creates a new array from calling a function for every array element. It does not change the original array.filter()
: It creates a new array filled with elements that pass a test provided by a function. It does not change the original array.find()
: It returns the value of the first element that passes a test. It does not change the original array. It returns undefined
if no elements are found.
// map()
const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt) // output-> 2,3,4,5
//filter()
const ages = [32, 33, 16, 40];
const result = ages.filter(age -> age>=18); // output-> 32,33,40
//find()
const ages = [32, 33, 16, 40];
const result = ages.find(age -> age>=18); // output-> 32
10. Logical and / or
Logical and (&&)
: Returns true if both expressions are true, otherwise it returns false.
Logical or(||)
:Returns true if one or both expressions are true, otherwise it returns false.
//Logical and
let x = 6;
let y = 3;
(x < 10 && y > 1); // output-> true
(x < 10 && y < 1); //output-> false
//Logical or
(x == 5 || y == 5); //output-> false
11. Ternary operator
JS contains a conditional operator that assigns a value to a variable based on condition.
let age = 16;
let voteable = (age < 18) ? "Too young":"Old enough"; // output-> Too young
12. Promises
In ES6, Promises are used for asynchronous execution. You can use promise like below.
let data = new Promise((resolve, reject) => {
// do something
resolve();
}).then(()=> {
console.log('Badsha!');
})
An easy example of promise:
let myPromise = new Promise((resolve, reject) => {
const randomNumber = Math.random();
if (randomNumber > 0.5) {
resolve('Success!'); // Resolve the promise
} else {
reject('Error!'); // Reject the promise
}
});
myPromise
.then(result => console.log(result))
.catch(error => console.error(error));
Here, we created a promise called myPromise
that randomly resolves or rejects depending on given condition. We used the then
method to handle the resolved promise and the catch
method to handle the rejected promise.
13. Modules
In ES6, using import
and export
you can manage your code more easily. export
is used to make the function of one JS file available for other functions in other JS file. import
is used to call the exported function.
//Math.js file
export let number = 10;
export const subtract = (a, b) => a - b;
We can import userID variable and getName method using import statement .
//App.js file
import {number , subtract} from './Math';
console.log(number); // 10
These amazing features have made JS more modern and developer-friendly. These will definitely enhance your programming experience! এই article টা simpleএবং easy রাখতে এখানে সবগুলোতে ES5 এর syntax দেখানো হয়নি, কয়েকটা তে দেখানো হয়েছে। If you want to know their ES6 syntax, then Google will help you. Besides Logical oerator & ternary operator এই দুইটা কিন্তু JS এর feature, not ES6.
Start dealing with ES6 today!!!