Skip to content

Repository files navigation

Es2021

A comprehensive educational project demonstrating the new features introduced in ECMAScript 2021 (ES12) through practical, runnable JS examples.

Built in 2021, this repository explores modern language enhancements including numeric separators, logical assignment operators,private class methods and accessors, WeakRef, and FinalizationRegistry. Designed as a hands-on learning resource, the project explains each feature with clear examples, use cases, and executable code to help developers understand improvements in readability, asynchronous programming, encapsulation, and memory management.

Core Capabilities

  • Numeric Separators: Improved readability for large numbers
  • String.replaceAll(): Simple string replacement without regex
  • Logical Assignment Operators: Concise conditional assignments (&&=, ||=, ??=)
  • Promise.any(): First-fulfilled promise handling
  • Private Class Methods: True method encapsulation with # syntax
  • Private Getters/Setters: Private accessors for class properties
  • WeakRef: Weak object references for better memory management
  • FinalizationRegistry: Cleanup callbacks for garbage collection

Technical Excellence

  • Pure JavaScript: No external dependencies required
  • Node.js Compatible: Works with Node.js 16.13.1+
  • Educational Focus: Clear, well-commented examples
  • Practical Use Cases: Real-world applications for each feature

Developer Experience

  • Single Entry Point: All examples in one file for easy navigation
  • Self-Contained: No external dependencies
  • Well-Documented: Each feature explained with comments
  • Runnable Examples: Execute with npm start

Features

  • 🔢 Numeric Separators - Enhanced readability for large numbers
  • 🔄 String.replaceAll() - Simple string replacement without regex
  • Logical Assignment Operators - Concise conditional assignments (&&=, ||=, ??=)
  • ⏱️ Promise.any() - First-fulfilled promise handling
  • 🔒 Private Class Methods - True method encapsulation with # syntax
  • 🎯 Private Getters/Setters - Private accessors for class properties
  • 💾 WeakRef - Weak object references for better memory management
  • 🧹 FinalizationRegistry - Cleanup callbacks for garbage collection

Getting Started

Prerequisites

  • Node.js (v16.13.1 or higher)
  • npm (comes with Node.js)

Installation

  1. Clone the repository:
git clone https://github.com/orassayag/es2021.git
cd es2021
  1. Install dependencies:
npm install

Running the Examples

Execute all ES2021 feature demonstrations:

npm start

This will run through all examples in index.js and display their output in the console.

Usage

Running All Examples

To see all ES2021 features in action:

npm start

This executes the main index.js file which contains all feature demonstrations.

Exploring Individual Features

Open index.js and look for the section headers (e.g., // 1. Numeric Separators). You can comment out sections you don't want to see or modify the examples to experiment.

Configuration

This project doesn't require any external configuration. It's a self-contained educational project with no environment variables or configuration files needed beyond what's in package.json.

Available Scripts

npm start

Runs all ES2021 feature examples in sequence.

npm test

Currently a placeholder - can be extended with tests in the future.

Development

Code Style

The project uses Prettier for code formatting. Check .prettierrc for configuration.

Extending Examples

To add more examples or modify existing ones:

  1. Open index.js
  2. Add or edit code in the appropriate section
  3. Run npm start to see your changes

Architecture Principles

  1. Simplicity: Keep examples focused and easy to understand
  2. Clarity: Well-commented code with explanations
  3. Self-Contained: No external dependencies
  4. Educational: Each example demonstrates a single concept
  5. Practical: Examples show real-world use cases

Design Patterns

  • Single Responsibility: Each section focuses on one feature
  • Modular Structure: Clear separation between different feature demonstrations
  • Progressive Complexity: Examples start simple and build up to more complex use cases

Directory Structure

es2021/
├── .github/                # GitHub configuration
│   └── rulesets/           # Repository rules
├── .vscode/                # VS Code settings
├── index.js                # Main file with all ES2021 examples
├── package.json            # Project configuration
├── package-lock.json       # Dependency lock file
├── README.md               # This file
├── INSTRUCTIONS.md         # Detailed usage instructions
├── CONTRIBUTING.md         # Contribution guidelines
├── CODE_OF_CONDUCT.md      # Code of conduct
├── SECURITY.md             # Security policy
├── CHANGELOG.md            # Change history
└── LICENSE                 # MIT license

Best Practices

For Learning

  1. Read the Comments: Each example has detailed explanations
  2. Experiment: Modify the code to see what happens
  3. Practice: Try to implement the features in your own projects
  4. Reference: Use this as a quick reference when you need to remember syntax

For Contributing

  1. Follow Code Style: Use Prettier for consistent formatting
  2. Keep Examples Focused: Each example should demonstrate one concept
  3. Add Explanations: Include comments explaining what the code does
  4. Test Changes: Run npm start to verify your examples work

ES2021 Features Explained

1. Numeric Separators

Make large numbers more readable using underscores as visual separators:

let billion = 1_000_000_000;
let price = 1_475_938.38;
let hex = 0xff_ff_ff;

2. String.prototype.replaceAll()

Replace all occurrences without regex:

// Old way
let result = 'hello+world+test'.replace(/\+/g, ' ');

// New way
let result = 'hello+world+test'.replaceAll('+', ' ');

3. Logical Assignment Operators

Combine logical operations with assignment:

// AND assignment (&&=)
x &&= 5; // Assigns only if x is truthy

// OR assignment (||=)
y ||= 10; // Assigns only if y is falsy

// Nullish coalescing assignment (??=)
z ??= 20; // Assigns only if z is null or undefined

4. Promise.any()

Returns when the first promise fulfills:

const first = await Promise.any([
  fetchFromAPI1(),
  fetchFromAPI2(),
  fetchFromAPI3(),
]);
// Returns the first successful result

5. Private Class Methods

True method privacy using # prefix:

class Database {
  #connect() {
    // Private method - cannot be called outside class
  }

  query() {
    this.#connect(); // Can be called internally
  }
}

6. Private Getters and Setters

Private accessors for class properties:

class User {
  #password;

  get #hashedPassword() {
    return hash(this.#password);
  }

  set #hashedPassword(value) {
    this.#password = value;
  }
}

7. WeakRef

Create weak references that don't prevent garbage collection:

const cache = new WeakRef(largeObject);
const obj = cache.deref(); // Get object if still alive

8. FinalizationRegistry

Execute cleanup when objects are garbage collected:

const registry = new FinalizationRegistry((value) => {
  console.log(`Cleaning up: ${value}`);
});

registry.register(myObject, 'resource-id');

Architecture

graph TD
    A[index.js] --> B[Numeric Separators]
    A --> C[String.replaceAll]
    A --> D[Logical Assignment Operators]
    A --> E[Promise.any]
    A --> F[Private Class Methods]
    A --> G[Private Getters/Setters]
    A --> H[WeakRef]
    A --> I[FinalizationRegistry]

    D --> D1[&&= AND Assignment]
    D --> D2[||= OR Assignment]
    D --> D3[??= Nullish Assignment]

    F --> F1[Private Methods]
    F --> F2[Public Methods]

    style A fill:#4CAF50
    style B fill:#2196F3
    style C fill:#2196F3
    style D fill:#FF9800
    style E fill:#2196F3
    style F fill:#9C27B0
    style G fill:#9C27B0
    style H fill:#E91E63
    style I fill:#E91E63
Loading

Project Structure

es2021/
├── index.js           # Main file with all ES2021 examples
├── package.json       # Project configuration
├── package-lock.json  # Dependency lock file
├── README.md          # This file
├── INSTRUCTIONS.md    # Detailed usage instructions
├── CONTRIBUTING.md    # Contribution guidelines
└── LICENSE           # MIT license

Browser/Environment Compatibility

Environment Version Support
Node.js 16.13.1+ ✅ Full
Chrome 90+ ✅ Full
Firefox 88+ ✅ Full
Safari 14.1+ ✅ Full
Edge 90+ ✅ Full

Use Cases

  • Numeric Separators: Financial calculations, large datasets, binary/hex values
  • replaceAll(): Text processing, data sanitization, template engines
  • Logical Assignment: State management, default values, configuration
  • Promise.any(): Redundant API calls, fastest response selection
  • Private Methods: Encapsulation, hiding implementation details
  • WeakRef: Caching, memory-sensitive data structures
  • FinalizationRegistry: Resource cleanup, connection management

Contributing

Contributions to this project are released to the public under the project's open source license.

Everyone is welcome to contribute. Contributing doesn't just mean submitting pull requests—there are many different ways to get involved, including answering questions and reporting issues.

Please feel free to contact me with any question, comment, pull-request, issue, or any other thing you have in mind.

Author

License

This application has an MIT license - see the LICENSE file for details.

Credits

Original blog post inspiration: New JavaScript Features - ECMAScript 2021 with Examples by Brayan Arrieta

Acknowledgments

  • Built for educational and research purposes
  • Respects robots.txt and implements rate limiting
  • Uses user-agent rotation to avoid detection
  • Implements polite crawling practices

About

A comprehensive demo of features introduced in ECMAScript 2021 (ES12) with practical, runnable examples. Built in 2021–2026, this educational JavaScript project showcases ES2021 features including numeric separators, String.replaceAll(), logical assignment operators, Promise.any(), private class methods, WeakRef, and FinalizationRegistry usage.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages