Create variables from the properties of objects
const bar = {foo = 'foo bar'}const test = ['hello', 'world']const { foo } = barconst [first, second] = testconsole.log(foo) // 'foo bar'console.log(first + ' ' + second) // 'hello world'
Get the contents of an object or array for creating new objects and arrays
const foo = ['hello']const bar = ['world']const helloWorld = [...foo, ...bar]console.log(helloWorld) // ['hello', 'world']
Can be used with Destructuring
const fruitsList = ['List Title', 'apple', 'orange', 'blueberries']const [listTitle, ...fruits] = fruitsListconsole.log(listTitle) // 'List Title'console.log(fruits) // ['apple', 'orange', 'blueberries']
These are anonymous functions without this
, or super
. Great for callback’s.
const foo = () => 'bar'console.log(foo()) // 'bar'
Is a logical operator ??
that returns its right-hand side value when its left-hand side is null
or undefined
, otherwise returns the left-hand side. Therefore, falsey values will be considered valid and returned like empty string, zero, etc.
const left1 = '' ?? 'test'const left2 = 0 ?? 'test'console.log(left1) // ''console.log(left2) // 0const right1 = null ?? 'test'const right2 = undefined ?? 'test'const right3 = thisDoesNotExist?.value ?? 'test'console.log(right1) // 'test'console.log(right2) // 'test'console.log(right3) // 'test'
You can use nullish coalescing to conditionally run an expression. If the left-hand side expression evaluates to null
or undefined
, the right-hand expression will run.
Therefore, you can short-circuit the right-hand expression by returning a value that isn’t null
or undefined
.
const willShortCircuit = () => { console.log('will'); return 42; }const wontShortCircuit = () => { console.log('wont'); return null; }const test = () => { return 'test' }console.log( wontShortCircuit() ?? test() ) // 'wont' then 'test'console.log( willShortCircuit() ?? test() ) // 'will' then 42 as test() is not evaluated
Assign a value to a variable, only when it’s nullish (undefined
or null
) by using the Nullish Assigment Operator ??=
.
let x = nulllet y = undefinedlet z = '!'x ??= 'hello 'y ??= 'world'z ??= '?' // z is NOT nullish, so '?' will NOT be assignedconsole.log(x + y + z) // hello world!
You can use the optional chaining operator ?.
to read properties deep in objects that may by nullish (null
or undefined
). When it’s nullish, it short-circuits the expression then returns undefined
.
const dog = {color: 'yellow',breed: {name: 'Lab'}}const dogWithOutBreed = {color: 'brown'}console.log(dog.breed?.name) // 'Lab'console.log(dogWithOutBreed.breed?.name) // undefined
await import('/modules/my-module.js')