Syntax operator for "default assignment if value doesn't exits"

# Sultan (5 years ago)

An operator syntax for the the "typeof" pattern used to detect if a environment/object has a value:

if (typeof variable === 'undefined') {...} if (typeof object.key === 'undefined') {...}

This could manifest in destructuring as the following

var fn = ({ key ||= 1 }) => { }

And with variables as:

var global ||= {}

Equivalent code:

(arg) => { if (typeof arg.key === 'undefined') { arg.key = 1 } }

if (typeof global === 'undefined') { var global = {} }

# Rob Ede (5 years ago)

pretty succinct with existing de-structuring syntax:

const [variable = defaultValue] =  [maybeUndefinedValue]

const fn = ({ key = defaultValue }) => {  console.log(key); }
# Sultan (5 years ago)

const [variable = defaultValue] = [maybeUndefinedValue]

This would fail throw for variables you don't know exist i.e in the following example polyfill will throw if Symbol doesn't exist.

const [Symbol = SymbolPolyfill] = [Symbol]

This is specifically why convention is to use:

typeof maybeUndefinedValue === 'undefined'

const fn = ({ key = defaultValue }) => { console.log(key); }

The second example doesn't assign the key prop to the passed object.

# Isiah Meadows (5 years ago)

I'd just prefer a way to detect the value undefined vs no such binding.

# Rob Ede (5 years ago)

Yeah I guess there exists a use case for that method still. But I don’t feel that use case merits special syntax.