2023热门JS语法新特性
JS Syntax Feature from 《state of js 2023》
Nullish Coalescing
空值合并运算符(??),识别null和undefined值;MDN
const foo = null ?? 'default string';
console.log(foo);
// Expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// Expected output: 0
Dynamic Import
动态引入,import函数支持异步引入js模块;MDN
import(moduleName)
import(moduleName, options)
await import('/modules/my-module.js')
Private Field
类私有属性,以#
为前缀,无法在类的外部引用;MDN
class ClassWithPrivateField {
#privateField
}
Logical Assignment
逻辑与赋值&&=
,逻辑或赋值||=
;MDN
const a = { duration: 50, title: '' };
a.duration ||= 10;
console.log(a.duration);
// expected output: 50
a.title ||= 'title is empty.';
console.log(a.title);
// expected output: "title is empty"
let a = 1;
let b = 0;
a &&= 2;
console.log(a);
// Expected output: 2
b &&= 2;
console.log(b);
// Expected output: 0
Hashbang Comments
#!
HashBang注释,用于在shell中执行js时,指定js解释器
是单行注释,只能写在js代码的第一行;MDN
#!/usr/bin/env node
console.log("Hello world");
error.cause
error实例中cause属性,指示了引起错误的具体原因;MDN
try {
connectToDatabase();
} catch (err) {
throw new Error('Connecting to database failed.', { cause: err });
}
array.toSpliced(),toSorted(),toReversed()
不改变数组原始值,创建新数据作为返回值
array.with()
相对于直接用[索引]
更新数组,with方法不改变原始值、返回新数组
const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
上次更新: