DEV Community

Cover image for Modern JavaScript Features in ES13 ES2022
Leandro Nuñez for Digital Pollution

Posted on • Edited on

Modern JavaScript Features in ES13 ES2022

Introduction

JavaScript continues to evolve rapidly, and ES2022 introduces a set of exciting new features that cater to the evolving needs of modern web development.
In this post, we'll delve into the latest JavaScript features, exploring how each one enhances the language's capabilities.
We'll provide concise examples and real-life use cases for each feature, enabling you to leverage the power of modern JavaScript.

Table of Contents

  1. Class Field Declarations
  2. Private Methods and Fields
  3. await Operator at the Top Level
  4. Static Class Fields and Static Private Methods
  5. Class static Block
  6. Ergonomic Brand Checks for Private Fields
  7. at() Method for Indexing
  8. RegExp Match Indices
  9. Object.hasOwn() Method
  10. Error Cause
  11. Array Find from Last


1. Class Field Declarations
Class field declarations enable you to declare and initialize class properties directly within the class body.

class Person {
  name = '';
  age = 0;

  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: When defining classes with multiple properties, class field declarations enhance code readability by placing property declarations within the class definition.

References


2. Private Methods and Fields
Private methods and fields are declared using the # symbol, ensuring they are accessible only within the class.

class Book {
  #title = '';

  #getSummary() {
    return `This book is titled "${this.#title}".`;
  }

  constructor(title) {
    this.#title = title;
  }

  showSummary() {
    console.log(this.#getSummary());
  }
}
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: Private methods and fields protect sensitive data and internal implementation details, making classes more robust and secure.

References


3. The await Operator at the Top Level
ES2022 allows using the await operator at the top level of modules, enabling easy asynchronous module initialization.

// dataFetcher.js
const data = await fetchData();
export default data;
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: When initializing data asynchronously before exporting modules, using await at the top level simplifies the code structure.

References


4. Static Class Fields and Static Private Methods
Static class fields and static private methods are declared using the static keyword, accessible without class instantiation.

class MathUtils {
  static #multiplier = 2;

  static multiplyByTwo(number) {
    return number * MathUtils.#multiplier;
  }
}

console.log(MathUtils.multiplyByTwo(5)); // Output: 10
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: Static class fields and methods provide utility functions that don't require creating instances, promoting more efficient code organization.

References


5. Class static Block
Class static blocks allow you to execute code during class initialization, improving class setup.

class Configuration {
  static #config;

  static {
    // Some complex configuration setup
    Configuration.#config = { /* Configuration data */ };
  }
}
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: Class static blocks are handy when setting up complex configurations before using the class.

References


6. Ergonomic Brand Checks for Private Fields
ES2022 introduces ergonomic brand checks, allowing efficient and reliable private field type checks.

class Currency {
  #amount = 0;
}

function isCurrency(value) {
  return value instanceof Currency;
}
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: Ergonomic brand checks ensure secure and accurate type checking for private fields.

References


7. at() Method for Indexing
The at() method for indexing simplifies accessing elements in strings and arrays.

const message = 'Hello, JavaScript!';
console.log(message.at(7)); // Output: 'J'
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: The at() method provides a more concise way to access specific characters or elements within strings or arrays.

References


8. RegExp Match Indices
RegExp match indices allow you to access the start and end indices of matched substrings.

const text = 'Explore the latest JavaScript features!';
const regex = /\b\w+\b/g;
const matches = [...text.matchAll(regex)];
console.log(matches.map(match => match.indices));
// Output: [ [ [ 0, 7 ] ], [ [ 11, 21 ] ], [ [ 23, 32 ] ], [ [ 34, 44 ] ], [ [ 46, 54 ] ] ]
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: RegExp match indices are valuable when parsing text and capturing matched substrings' positions.

References


9. Object.hasOwn() Method
The Object.hasOwn() method checks if an object has a specified property, ignoring inherited properties.

const user = {
  name: 'John',
  age: 30
};

console.log(Object.hasOwn(user, 'name')); // Output: true
console.log(Object.hasOwn(user, 'isAdmin')); // Output: false
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: The Object.hasOwn() method helps avoid accidental access to inherited properties in complex object hierarchies.

References


10. Error Cause
ES2022 introduces the cause property for errors, facilitating better error chaining.

try {
  // Some operation that throws an error
} catch (error) {
  throw new Error('Error occurred', { cause: error });
}
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: Error causes help in providing a clearer understanding of the error context and its root cause.

References


11. Array Find from Last
The findFromLast() method allows you to search an array from the last element to the first.

const numbers = [10, 20, 30, 40, 50];
const lastMatch = numbers.findFromLast((element) => element > 20);
console.log(lastMatch); // Output: 50
Enter fullscreen mode Exit fullscreen mode

Real-Life Use Case: When searching for the last occurrence of a specific element, findFromLast() streamlines the process.

References

Conclusion

ES2022 brings a wealth of powerful features to JavaScript, enhancing code organization, security, and performance.
From class field declarations and private methods to ergonomic brand checks for private fields, each feature unlocks new possibilities in modern web development. Additionally, features like await at the top level and class static blocks further streamline asynchronous operations and class initialization.
Embrace the latest JavaScript advancements to create cleaner, more efficient, and sophisticated applications.

References

Top comments (0)