Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript default parameter

Tags:

javascript

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

like image 453
mccraveiro Avatar asked Dec 11 '22 23:12

mccraveiro


1 Answers

Yes, 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.

like image 139
jbabey Avatar answered Dec 24 '22 04:12

jbabey