The let
keyword was added to JavaScript to fix some of the limitations of the var
keyword. When using var
to define variables, their scope was limited to the entire function (or globally to the whole script). This could create a lot of issues, like if a variable inside a block of code was accidentally overwritten, it could cause unexpected errors.
With let
, variables are only valid within the block they were defined in (like within {}
), and they aren't accessible outside of that block. This makes it easier to manage variables and prevents problems caused by variable conflicts.
var x = 10;
{
let x = 2;
console.log(x); // 2 - Inside this block, x is 2
}
console.log(x); // 10 - Outside the block, x is back to 10
In this example, you can see that let
allows us to have two variables with the same name in different parts of the code without them interfering with each other. This is especially useful in large and complex projects where there might be many variables with different scopes.
The const
keyword is used to define variables that shouldn't change their value. These variables remain constant after being initialized, and you can't assign a new value to them. However, if const
is used for an object or an array, you can still change the contents of the object or array, but you can't assign the variable to a different object or array.
This feature prevents unintended changes to variables that are meant to stay constant. const
is especially useful for defining constants like fixed parameters, settings, and other things that shouldn't change.
const x = 10;
{
const x = 2;
console.log(x); // 2 - Inside this block, x is 2
}
console.log(x); // 10 - Outside the block, x is still 10
This example shows that with const
, you can define variables that remain constant within their block scope, which makes your code more stable and helps prevent potential errors.
Arrow Functions are a new, simpler way to write functions in JavaScript. Because of their concise syntax, they make the code shorter and more readable. Unlike traditional functions, Arrow Functions don't require the function
keyword and the return
keyword, allowing you to write simpler code without these keywords.
One of the main features of Arrow Functions is that they inherit this
from the enclosing scope, meaning you don't need to keep track of this
in temporary variables anymore. However, because of this feature, Arrow Functions are not suitable for use as methods of objects.
// Regular function in ES5
var x = function(x, y) {
return x * y;
}
// Arrow function in ES6
const x = (x, y) => x * y;
This example shows how Arrow Functions can replace traditional functions and simplify coding. Arrow Functions are ideal for things like callbacks, short and simple functions, and situations where quick and readable coding is needed.
Object Destructuring is a handy way to extract values from an object and assign them to separate variables. Instead of having to assign each object property to variables manually, you can use destructuring to do this quickly and easily.
This feature is especially useful when working with complex objects that have multiple properties, making the code shorter and more readable.
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
let { firstName, age } = person;
console.log(firstName); // 'John'
console.log(age); // 50
In this example, the firstName
and age
properties are extracted from the person
object and assigned to separate variables. This method is particularly useful when you want to extract only some of the properties from an object and don't need the others.
Array Destructuring is a convenient way to extract values from arrays and assign them to variables. Instead of manually accessing each array element and assigning them to variables, you can do this with a single statement.
This feature is especially useful when working with large or complex arrays where you only want to access a few elements, making the code more concise and readable.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let [fruit1, fruit2] = fruits;
console.log(fruit1); // 'Banana'
console.log(fruit2); // 'Orange'
In this example, the first two elements of the fruits
array are assigned to the variables fruit1
and fruit2
. Array Destructuring is useful when you need quick and simple access to a few elements of an array.
The ...
operator, known as the Spread
operator, is a powerful feature in ES6 that allows you to spread out elements of an iterable (like an array or object) into a new array or function. This operator helps you concatenate arrays, copy them, or even pass elements of an array as arguments to a function.
This feature simplifies and cleans up code, making operations like merging, copying, or passing arguments easier to implement.
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "Dec"];
const year = [...q1, ...q2, ...q3, ...q4];
console.log(year); // ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
In this example, the Spread
operator is used to combine four arrays into a new array called year
. This operator is particularly useful for coding scenarios that require merging data or passing arguments.
The for/of
loop is a new way to iterate over iterable objects (like arrays, strings, maps, and sets) in JavaScript, allowing you to loop through their values easily. Unlike for/in
, which iterates over keys or indexes, for/of
iterates directly over values, making your code more readable and concise.
This loop is particularly useful for working with data that is iterable, like arrays and strings.
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + " ";
}
console.log(text); // 'BMW Volvo Mini '
In this example, the for/of
loop iterates over the elements of the cars
array and adds each value to the text
variable. This loop lets you work directly with values without dealing with indexes, simplifying your code.
A Map
object is a new data type in JavaScript that allows you to use any object as a key and access its associated values. Unlike regular objects that only use strings as keys, Map
can accept any data type as a key.
This feature is particularly useful when you need to store data using unconventional keys (like objects or arrays) and gives you more precise control over your data.
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
console.log(fruits.get("apples")); // 500
In this example, Map
allows you to store data as key-value pairs and access them using the get
method. This data type is ideal for managing collections of data that require non-simple keys.
A Set
object is a new data type in JavaScript that lets you store a collection of unique values (no duplicates). Unlike arrays, which can have duplicate values, a Set
only keeps unique values. This feature is particularly useful when you need to store a collection of values without duplicates.
const letters = new Set();
letters.add("a");
letters.add("b");
letters.add("c");
letters.add("a"); // This value won't be added again because it already exists
console.log(letters.size); // 3
In this example, Set
allows you to add values sequentially and prevent duplicate values from being stored. Set
is particularly useful when you need to manage unique values and want to avoid the complexity of checking for duplicates.
do you use them? Classes in JavaScript act as templates for creating similar objects. This feature allows you to define more complex structures like objects with specific methods and properties. Classes have a simpler and more readable syntax than constructor functions, making your code better organized.
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
In this example, a class named Car
is defined with two properties, name
and year
. Using this class, you can easily create multiple objects of type Car
and assign different values to them. Classes are particularly useful in applications that require defining multiple instances of a type, making your code more organized and readable.
Promises in JavaScript help you work with asynchronous code, like server requests, more simply and predictably. A Promise
represents an asynchronous operation and its eventual outcome. When you define a Promise
, you can specify what happens when the operation completes (whether successful or not).
This feature allows you to write asynchronous code in a way that's easier to read and manage.
const myPromise = new Promise(function(resolve, reject) {
setTimeout(function() { resolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
console.log(value); // After 3 seconds, the message "I love You !!" is displayed
});
In this example, a Promise
is defined that returns a message after 3 seconds. Using then
, you can specify what to do when the Promise
resolves. This feature is especially useful for managing asynchronous operations that might take time.
The Symbol
data type is a new type in JavaScript used to create unique and non-repeatable identifiers. Symbols
are particularly useful when you need to prevent variable or property name conflicts in your code, as each Symbol
is always unique. Even if you create two Symbols
with the same description, they will still be different.
This feature is very useful for preventing issues like name conflicts in large projects or when multiple people are working on a project.
let id = Symbol('id');
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
person[id] = 140353;
console.log(person[id]); // 140353
In this example, a Symbol
named id
is created and used as a key in the person
object. This ensures that the id
key does not conflict with any other property in the object and always remains unique.
Default parameters allow you to specify default values for function parameters. This means if a parameter is not specified when calling the function, the function will use the default value. This feature simplifies writing code and prevents errors caused by forgetting to provide parameter values.
function myFunction(x, y = 10) {
return x + y;
}
console.log(myFunction(5)); // 15
In this example, the myFunction
function has a y
parameter with a default value of 10. If no value is specified for y
when calling the function, the function automatically uses 10. This feature is especially useful in situations where a function requires many parameters, making coding more flexible.
The Rest
parameter (...
) is a simple way to define functions that take an unspecified number of arguments. With this parameter, you can take all the additional arguments as an array and work with them. This feature is particularly useful when you don't know exactly how many arguments a function will receive.
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
console.log(sum(4, 9, 16, 25, 29, 100, 66, 77)); // 326
In this example, the sum
function can take any number of arguments and processes them all as an array. This feature is particularly useful for functions that need to work with a variable number of arguments.
The includes
method was added to strings to easily check if a specific substring exists in a larger string. This method returns a Boolean (true
or false
) and is very useful for quick searches within strings.
This method is especially helpful when you need to check if a specific word or phrase exists in a larger text.
let text = "Hello world, welcome to the universe.";
console.log(text.includes("world")); // true
In this example, includes
checks if the word world
exists in the text
string and returns true
or false
based on the result. This method helps you easily check the content of strings with simple and readable code.
The startsWith
method is a simple way to check if a string starts with a specific substring. If the string starts with that substring, it returns true
; otherwise, it returns false
. This method is useful when you need to check the content of a string.
let text = "Hello world, welcome to the universe.";
console.log(text.startsWith("Hello")); // true
In this example, startsWith
checks if the text
string starts with Hello
. This feature is handy when you need to verify that a string begins with a specific word or phrase.
The endsWith
method is a simple way to check if a string ends with a specific substring. If the string ends with that substring, it returns true
; otherwise, it returns false
. This method is useful for quickly checking the end of strings.
let text = "John Doe";
console.log(text.endsWith("Doe")); // true
In this example, endsWith
checks if the text
string ends with Doe
. This method is especially useful when you need to ensure a string ends in a specific way.
The entries
method is a new way to iterate over arrays in JavaScript that allows you to loop through key-value pairs (i.e., index and value). This method returns an iterable object that you can use in a for/of
loop to access each array element and its corresponding index.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const f = fruits.entries();
for (let x of f) {
console.log(x);
}
/* Output:
[0, "Banana"]
[1, "Orange"]
[2, "Apple"]
[3, "Mango"]
*/
In this example, entries
returns an iterable object of the fruits
array that contains index-value pairs. This feature lets you access both the values and the indices in a loop simultaneously.
The Array.from
method is a powerful feature in ES6 that lets you convert any array-like object (like NodeList
or strings) or any iterable object into a real array. This feature is handy when working with objects that aren't arrays but want to use array functionalities on them.
const arr = Array.from("ABCDEFG");
console.log(arr); // ['A', 'B', 'C', 'D', 'E', 'F', 'G']
In this example, Array.from
converts the string ABCDEFG
into an array of letters. This feature is particularly useful for scenarios where you need to convert objects into arrays to use array methods.
The keys
method is a new way to get the indexes of an array in JavaScript. This method returns an iterable object containing the array's keys (indexes). With this method, you can easily loop through the indexes of an array and access them.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();
for (let key of keys) {
console.log(key);
}
/* Output:
0
1
2
3
*/
In this example, keys
returns the indexes of the fruits
array, and the for/of
loop iterates over these indexes. This method helps you easily access the array's indexes without needing to use more complex loops.
The find
method is a powerful feature in ES6 that allows you to find and return the first element of
an array that meets a specific condition. This method takes a function as an argument, which is executed for each array element, and returns the first element that satisfies the condition.
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(function(value) {
return value > 18;
});
console.log(first); // 25
In this example, find
locates and returns the first number in the numbers
array that is greater than 18. This method is especially useful for quick searches in arrays and finding the first element that meets a specific condition.
22. How can you use findIndex
to locate the index of the first element that matches a specific condition?
The findIndex
method works similarly to find
, but instead of returning the value, it returns the index of the first element that meets a specific condition. This method is useful when you need to know the index of the first element that matches a specific condition.
const numbers = [4, 9, 16, 25, 29];
let firstIndex = numbers.findIndex(function(value) {
return value > 18;
});
console.log(firstIndex); // 3
In this example, findIndex
locates and returns the index of the first number in the numbers
array that is greater than 18. This method is particularly useful for situations where you need to know the position of a specific element.
Several new methods have been added to the Math object in ES6 for specific calculations. These methods include Math.trunc
, Math.sign
, Math.cbrt
, Math.log2
, and Math.log10
. Each of these methods is designed for specific mathematical operations and helps you perform more complex calculations more easily.
Math.trunc(x)
returns the integer part of the numberx
, removing the fractional part.Math.sign(x)
indicates whetherx
is negative, positive, or zero.Math.cbrt(x)
calculates the cube root of the numberx
.Math.log2(x)
returns the logarithm ofx
to the base 2.Math.log10(x)
calculates the logarithm ofx
to the base 10.
console.log(Math.trunc(4.9)); // 4
console.log(Math.sign(-4)); // -1
console.log(Math.cbrt(8)); // 2
console.log(Math.log2(8)); // 3
console.log(Math.log10(100)); // 2
These examples use various Math
methods for mathematical calculations. These methods are particularly useful when you need to perform specific calculations in JavaScript, making the code simpler.
In ES6, new features have been added to the Number object to help you work with numbers more precisely. These features include Number.EPSILON
, Number.MIN_SAFE_INTEGER
, Number.MAX_SAFE_INTEGER
, Number.isInteger
, and Number.isSafeInteger
.
Number.EPSILON
returns the smallest difference between two floating-point numbers in JavaScript.Number.MIN_SAFE_INTEGER
specifies the smallest safe integer that can be accurately represented.Number.MAX_SAFE_INTEGER
specifies the largest safe integer that can be accurately represented.Number.isInteger(x)
checks ifx
is an integer.Number.isSafeInteger(x)
checks ifx
is a safe integer.
console.log(Number.EPSILON); // 2.220446049250313e-16
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.isInteger(10)); // true
console.log(Number.isSafeInteger(12345678901234567890)); // false
These features are particularly useful for working with numbers and preventing computational errors in JavaScript.
In ES6, two new global methods have been added: isFinite
and isNaN
. These methods help you easily check if a value is a valid number.
isFinite(x)
checks ifx
is a finite number (i.e., notInfinity
orNaN
).isNaN(x)
checks ifx
is aNaN
(Not a Number).
console.log(isFinite(10/0)); // false
console.log(isFinite(10/1)); // true
console.log(isNaN("Hello")); // true
These methods help you easily work with numbers and special values in JavaScript and prevent computational errors.
Modules are an important feature in ES6 that allow you to divide code into smaller, separate parts and manage these parts as independent modules. This feature helps you eliminate code repetition and manage your projects more efficiently.
In JavaScript, modules can be imported in two ways:
Importing from named exports: This type of import allows you to import specific values from a module.
import { name, age } from "./person.js";
Importing from default exports: This type of import allows you to import a default value from a module.
import message from "./message.js";
Modules help you write cleaner, more organized code and prevent code duplication. This feature is particularly useful for large projects and makes maintaining and developing your code easier.