CoffeeScript ?= and ||=
Posted by ark, ,
This all makes perfect sense and shouldn't be a surprise to me, but I spent time confirming it and figured I should keep my test somewhere.

a = 2
undef = undefined; zero = 0; nuul = null; arr = []; zs = ''; o = {}; fal = false
console.log('input:', undef, zero, nuul, arr, JSON.stringify(zs), 0, fal)

undef ?= a; zero ?= a; nuul ?= a; arr ?= a; o ?= a; fal ?= a
console.log('?= ', undef, zero, nuul, arr, JSON.stringify(zs), o, fal)

undef = undefined; zero = 0; nuul = null; arr = []; zs = ''; o = {}; fal = false
undef ||= a; zero ||= a; nuul ||= a; arr ||= a; zs ||= a; o ||= a; fal ||= a
console.log('||=', undef, zero, nuul, arr, JSON.stringify(zs), o, fal)

yields this:

input: undefined 0 null [] "" {} false
?= 2 2 0 2 [] "" {} false
||= 2 2 2 2 [] 2 {} 2

So that's interesting. It's important to know the difference between the two. especially if your original value might be falsy.

and maybe someone is searching for this and would use keywords like questionmark, question-mark, query, equals, or, double pipe.

Comments

Posted Thursday 31 July 2014 Share