ECMAScript 2018: A Friendly Guide for Beginners

Hello there, future JavaScript wizards! I'm thrilled to be your guide on this exciting journey through ECMAScript 2018. As someone who's been teaching programming for years, I can't wait to share these new features with you. Don't worry if you're new to coding – we'll take it step by step, and before you know it, you'll be writing JavaScript like a pro!

ECMAScript 2018

New Added Features in ECMAScript 2018

ECMAScript 2018, also known as ES9, brought some fantastic additions to the JavaScript language. It's like getting a shiny new toolbox for your coding adventures! Let's dive into these features one by one.

JavaScript Asynchronous Iteration

Imagine you're at a buffet, and instead of piling everything on your plate at once, you can magically summon each dish as you're ready to eat it. That's kind of what asynchronous iteration does for your code!

The for-await-of Loop

This new loop allows us to work with asynchronous data sources more easily. Here's an example:

async function* numberGenerator() {
  yield Promise.resolve(1);
  yield Promise.resolve(2);
  yield Promise.resolve(3);
}

async function printNumbers() {
  for await (const num of numberGenerator()) {
    console.log(num);
  }
}

printNumbers();
// Output:
// 1
// 2
// 3

In this example, numberGenerator is an async generator function that yields promises. The for-await-of loop waits for each promise to resolve before moving to the next iteration. It's like having a patient friend who waits for you to finish each bite before offering the next dish!

New features of the RegExp() object

RegExp, or Regular Expressions, are like the Swiss Army knife of text processing. ECMAScript 2018 added some cool new tricks to this tool.

Unicode Property Escapes

This feature lets us match characters based on their Unicode properties. It's super helpful when working with international text!

const greekSymbol = "π";
console.log(/\p{Script=Greek}/u.test(greekSymbol)); // true

Here, \p{Script=Greek} matches any character in the Greek script. The u flag enables Unicode mode.

Lookbehind Assertions

Now we can check what comes before our match, not just after. It's like being able to peek over your shoulder in the coding world!

const price = "$123.45";
console.log(price.match(/(?<=\$)\d+(\.\d*)?/)[0]); // "123.45"

In this example, (?<=\$) is a positive lookbehind that ensures our match is preceded by a dollar sign, without including the dollar sign in the match.

Named Capture Groups

We can now give names to our capture groups, making our regular expressions more readable and maintainable.

const dateRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = dateRegex.exec("2023-05-15");
console.log(match.groups.year);  // "2023"
console.log(match.groups.month); // "05"
console.log(match.groups.day);   // "15"

It's like labeling the compartments in your toolbox – everything is easier to find!

JavaScript Promise finally()

Promises in JavaScript are like making a plan with a friend. Sometimes it works out, sometimes it doesn't, but either way, you might want to do something afterwards. That's where finally() comes in!

function fetchData() {
  return new Promise((resolve, reject) => {
    // Simulating an API call
    setTimeout(() => {
      const success = Math.random() > 0.5;
      if (success) {
        resolve("Data fetched successfully!");
      } else {
        reject("Error fetching data");
      }
    }, 1000);
  });
}

fetchData()
  .then(data => console.log(data))
  .catch(error => console.error(error))
  .finally(() => console.log("Operation completed"));

In this example, no matter if the promise resolves or rejects, the finally block will always run. It's like saying "Whether we succeed or fail, let's clean up and go home."

JavaScript Rest Object Properties

The rest operator (...) in object literals is like having a magic bag that can hold all the leftovers. It's super handy when you want to separate some properties from the rest.

const person = {
  name: "Alice",
  age: 30,
  city: "Wonderland",
  occupation: "Explorer"
};

const { name, age, ...rest } = person;

console.log(name);  // "Alice"
console.log(age);   // 30
console.log(rest);  // { city: "Wonderland", occupation: "Explorer" }

In this example, we're pulling out name and age, and everything else gets tucked into rest. It's like sorting your laundry – socks in one pile, everything else in another!

Conclusion

And there you have it, folks! We've journeyed through the exciting new features of ECMAScript 2018. Remember, the best way to learn is by doing, so don't be afraid to experiment with these new tools. coding is like cooking – the more you practice, the better you get!

Here's a quick reference table of the methods we've covered:

Feature Description
for-await-of Allows asynchronous iteration over promises
Unicode Property Escapes Matches characters based on Unicode properties in RegExp
Lookbehind Assertions Checks for matches based on what comes before in RegExp
Named Capture Groups Allows naming of capture groups in RegExp
Promise.prototype.finally() Specifies a callback to run when a promise is settled
Rest Object Properties Collects remaining properties into a new object

Happy coding, and may your JavaScript adventures be ever exciting!

Credits: Image by storyset