I was reading the Three.js code when a silly question arose: Is there any difference between the codes below?
frameHeight = frameHeight !== undefined ? frameHeight : 24;
and
frameHeight = frameHeight || 24;
(frameHeight is a parameter of the function)
Thanks
I was reading the Three.js code when a silly question arose: Is there any difference between the codes below?
frameHeight = frameHeight !== undefined ? frameHeight : 24;
and
frameHeight = frameHeight || 24;
(frameHeight is a parameter of the function)
Thanks
Share Improve this question asked Aug 15, 2012 at 17:29 mccraveiromccraveiro 553 bronze badges 2-
1
Not a javascript expert, but I believe the first will only return 24 if
frameHeight
isundefined
where as the second will return 24 ifframeHeight
has any "falsey" value, likenull
,''
, etc. – sellmeadog Commented Aug 15, 2012 at 17:32 -
They are different, but
if(frameHeight===undefined)frameHeight=24;
IS equivalent but it is more readable and performs better since its value will only change when needed – ajax333221 Commented Aug 15, 2012 at 17:48
4 Answers
Reset to default 9Yes, they are different.
frameHeight = frameHeight || 24;
This will coerce frameHeight
to a boolean value. If it is 0
, ''
, false
, null
, undefined
, or NaN
it will be false and frameHeight
will be defaulted to 24.
frameHeight = frameHeight !== undefined ? frameHeight : 24;
This will explicitly check if frameHeight
is not undefined
and ONLY for undefined
will it default it to 24
.
frameHeight = frameHeight || 24;
^ Will do a null check as well. Will also do a check for 0, false, empty string ('') NaN and undefined
frameHeight = frameHeight !== undefined ? frameHeight : 24;
^ Will just check for undefined.
Yes, there is a difference and that difference can be significant depending upon the circumstances.
frameHeight = frameHeight || 24
will assign 24
to frame if frameHeight is initially ANY falsey value such as ""
, 0
, null
, undefined
, NaN
or false
.
Whereas:
frameHeight = frameHeight !== undefined ? frameheight : 24
will only assign it 24
if the initial value is exactly undefined
.
So, of possible significance in this particular function, the second method will allow you to pass 0
for the frameHeight
to set a zero height, but the first method will not because it will override that 0
to 24
.
frameHeight = frameHeight || 24;
fails for frameHeight
= 0 works for frameHeight
= null
frameHeight = frameHeight !== undefined ? frameHeight : 24;
fails for frameHeight
= null works for frameHeight
= 0