Thursday, February 18, 2021

JavaScript Features That Are Introduced In ES2021

  1. String.prototype.replaceAll
    A new string method to replace all occurrences items.
    const catPhrase = 'A cat sat on the cat mat';
    const dogPhrase = catPhrase.replaceAll('cat', 'dog');
    console.log(dogPhrase); // A dog sat on the dog mat
    

  2. Logical Assignment Operators

    - Or Or Equals

    Or Or Equals provides a nice shorthand for us to provide an alternative value if the initial value is empty. 

    In the first example below, as a is truthy, a remains equal to “hello”.
    let a = “hello”;
    a ||= 10;
    console.log(a); // hello
    
    In the second example, found below, as b is falsey the value is then set to “world”.
    let b = “”;
    b ||= “world”;
    console.log(b); // world
    - And And Equals
    And And Equals provides a nice shorthand for us to override a value if a previous value was defined.

    In the first example below, as a is truthy, a is then set to “hello”.
    let a = true;
    a &&= “hello”;
    console.log(a); // hello
    In the second example below, as b is falsey, b remained equal fo false.
    let b = false;
    b &&= “world”;
    console.log(b); false

  3. Numeric Separators
    Numeric Separators introduces the separators for numeric literals with the intent to make them easier to read. Before ES2021 we would write our million value as follows:
    const billion = 1000000000
    With Numeric Separators we can make the number much easier to read by introducing underscores.
    const billion = 1_000_000_000

  4. Private Methods and Fields
    ES2021 finally fixes this omission by introducing private methods and private fields. To indicate a method or field is private you simply need to use a hash (#) before the name.
    class ClassWithPrivateField {
     #privateField
    }
    
    class ClassWithPrivateMethod {
     #privateMethod() {
     return 'hello world'
     }
    }
    
    class ClassWithPrivateStaticField {
     static #PRIVATE_STATIC_FIELD
    }
    Class was introduced on ES6, you may refer to below article:
    https://scalaoncloud.blogspot.com/2016/12/javascript-evolution-esmascript-6.html

No comments:

Post a Comment