In Ruby you have something called a conditional assignment (||=
). You can use it to assign values to variables if they have not already been defined or set. It is similar to saying this in Javascript:
if (typeof x == undefined) { x = 'value' }
In Ruby, to assign 'value
to x
if it has not already been assigned, you would use x ||= 'value
Example of how it works:
x = 1
x ||= 2
return x // Will return 1
Or:
x ||= 2
return x // Will return 2
Is there any way to do this in Javascript without the significantly longer if
statement?
Solved: @tede24 suggested the following
var x = x || newValue
The only way it is different to Ruby is that if x
has been defined to 0
, i.e. var x = 0
, the will set x
to newValue