All Products
Search
Document Center

esnext

Last Updated: Feb 04, 2021

SJS supports part of ES6 grammar.

let & const

 
  1. function test(){
  2. let a = 5;
  3. if (true) {
  4. let b = 6;
  5. }
  6. console.log(a); // 5
  7. console.log(b); // Reference error: b is not defined
  8. }

Arrow function

 
  1. const a = [1,2,3];
  2. const double = x => x * 2; // Arrow function
  3. console.log(a.map(double));
  4. var bob = {
  5. _name: "Bob",
  6. _friends: [],
  7. printFriends() {
  8. this._friends.forEach(f =>
  9. console.log(this._name + " knows " + f));
  10. }
  11. };
  12. console.log(bob.printFriends());

Enhanced object literal

 
  1. var handler = 1;
  2. var obj = {
  3. handler, // Object attribute
  4. toString() { // Object method
  5. return "string";
  6. },
  7. };
Note: The super keyword is not supported and cannot be used in the object method.

Template string

 
  1. const h = 'hello';
  2. const msg = `${h} alipay`;

Destructuring

 
  1. // Array destructuring assignment
  2. var [a, ,b] = [1,2,3];
  3. a === 1;
  4. b === 3;
  5. // Object destructuring assignment
  6. var { op: a, lhs: { op: b }, rhs: c }
  7. = getASTNode();
  8. // Shorthand for object destructuring assignment
  9. var {op, lhs, rhs} = getASTNode();
  10. // Destructured parameters
  11. function g({name: x}) {
  12. console.log(x);
  13. }
  14. g({name: 5});
  15. // Default values in destructuring assignment
  16. var [a = 1] = [];
  17. a === 1;
  18. // Function parameters: destructured parameters + default values
  19. function r({x, y, w = 10, h = 10}) {
  20. return x + y + w + h;
  21. }
  22. r({x:1, y:2}) === 23;

Default + Rest + Spread

 
  1. // Default parameters
  2. function f(x, y=12) {
  3. // If no value is passed to y, or if the passed value is undefined, then the value of y is 12.
  4. return x + y;
  5. }
  6. f(3) == 15;
  7. function f(x, ...y) {
  8. // y is an array
  9. return x * y.length;
  10. }
  11. f(3, "hello", true) == 6;
  12. function f(x, y, z) {
  13. return x + y + z;
  14. }
  15. f(...[ 1,2,3]) == 6; // Array destructuring
  16. const [a, ...b] = [1,2,3]; // Array destructuring assignment, b = [2, 3]
  17. const {c, ...other} = {c: 1, d: 2, e: 3}; // Object destructuring assignment, other = {d: 2, e: 3}
  18. const d = {...other}; // Object destructuring