JavaScript - ECMAScript 2020: A Beginner's Guide
Hello, aspiring programmers! I'm thrilled to be your guide on this exciting journey into the world of ECMAScript 2020. As a computer science teacher with years of experience, I've seen countless students light up when they grasp these concepts. So, let's dive in and explore the wonderful features that ES2020 brings to the JavaScript language!
Features Added in ECMAScript 2020
ECMAScript 2020, also known as ES2020, is like a shiny new toolbox for JavaScript developers. It introduces several exciting features that make our coding lives easier and more efficient. Let's unpack this toolbox together and see what goodies we find inside!
BigInt Primitive DataType
Imagine you're counting stars in the night sky. There are billions of them! In the past, JavaScript had a limit on how big a number could be. But now, with BigInt, the sky's the limit (pun intended)!
BigInt allows us to work with incredibly large integers. Here's how you can use it:
const bigNumber = 1234567890123456789012345678901234567890n;
console.log(bigNumber);
// Output: 1234567890123456789012345678901234567890n
const result = bigNumber + 1n;
console.log(result);
// Output: 1234567890123456789012345678901234567891n
In this example, we're creating a BigInt by adding 'n' at the end of the number. The 'n' tells JavaScript, "Hey, this is a BigInt!" We can perform operations on BigInts just like regular numbers, but remember to add 'n' to any number you're using with BigInt.
The Nullish Coalescing Operator (??)
Have you ever played "guess the present" game? You shake the box, and if you hear nothing, you guess it's empty. The nullish coalescing operator is kind of like that, but for code!
This operator helps us check if a value is null or undefined, and if it is, we can provide a default value. Here's how it works:
let username = null;
console.log(username ?? "Guest");
// Output: "Guest"
username = "Alice";
console.log(username ?? "Guest");
// Output: "Alice"
In the first case, username is null, so the operator returns "Guest". In the second case, username has a value, so it returns that value. It's like saying, "If the box is empty, let's assume it's a teddy bear!"
Promise allSettled() Method
Imagine you're a teacher (like me!) waiting for all your students to finish a test. Some might finish successfully, others might give up. Promise.allSettled() is like waiting for everyone to hand in their paper, regardless of how well they did.
Here's an example:
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];
Promise.allSettled(promises).then((results) => results.forEach((result) => console.log(result.status)));
// Output:
// "fulfilled"
// "rejected"
In this code, we have two promises. One resolves successfully, the other rejects. Promise.allSettled() waits for both to complete and then gives us the status of each.
The String matchAll() Method
Have you ever played "Where's Waldo?" Well, matchAll() is like playing "Where's Waldo?" with text! It helps us find all occurrences of a pattern in a string.
Let's see it in action:
const text = "The cat and the hat sat on the mat.";
const regex = /at/g;
const matches = [...text.matchAll(regex)];
console.log(matches);
// Output: [
// ['at', index: 7, input: 'The cat and the hat sat on the mat.', groups: undefined],
// ['at', index: 19, input: 'The cat and the hat sat on the mat.', groups: undefined],
// ['at', index: 31, input: 'The cat and the hat sat on the mat.', groups: undefined]
// ]
Here, we're searching for all occurrences of "at" in our text. matchAll() returns an iterator, which we convert to an array using the spread operator (...). Each match gives us information about where it was found in the string.
The Optional Chaining Operator (?.)
Last but not least, let's talk about the optional chaining operator. It's like a cautious explorer, carefully checking each step of the path before moving forward.
Here's how it works:
const user = {
name: "Alice",
address: {
street: "123 Main St"
}
};
console.log(user.address?.street);
// Output: "123 Main St"
console.log(user.phoneNumber?.home);
// Output: undefined
In this example, we're trying to access properties that might not exist. The ?. operator allows us to do this safely. If user.address exists, it will try to access street. If user.phoneNumber doesn't exist, it stops there and returns undefined instead of throwing an error.
Methods Table
Here's a handy table summarizing the new methods we've learned:
Method | Description |
---|---|
BigInt | Allows working with large integers |
?? (Nullish Coalescing) | Provides a default value for null or undefined |
Promise.allSettled() | Waits for all promises to settle |
String.matchAll() | Finds all occurrences of a pattern in a string |
?. (Optional Chaining) | Safely accesses nested object properties |
And there you have it, folks! We've explored the exciting new features of ECMAScript 2020. Remember, the best way to learn is by doing. So, fire up your code editor and start experimenting with these new tools. Happy coding, and may your JavaScript journey be filled with excitement and discovery!
Credits: Image by storyset