Since jQuery 3 .outerHeight()
returns undefined
instead of null
if called on a non-existing element. This causes problems when adding up heights of elements that don't exist, because number
+ undefined
now results in NaN
. While prior to jQuery 3 number
+ null
would return number
.
var lorem = $('#div1').outerHeight() + $('#div2').outerHeight();
Returns NaN
if for example #div2
does not exist.
Potential solution:
undef2null = function(myvar) {
if (myvar === undefined) {return null;}
else {return myvar;}
}
Would turn above code into:
var lorem = undef2null($('#div1').outerHeight()) + undef2null($('#div2').outerHeight());
Is there a more elegant solution than this?
You can guard against an undefined or null value using the ||
operator:
($('#div1').outerHeight() || 0)
...which is less typing than calling a function on each of the potentially problem values (although obviously you could make a one-line function out of that if you wanted to).
Or instead of a function that checks a single value to see if it is undefined
you could write a function that adds up all supplied arguments, checking each:
function addNumbers() {
var result = 0;
for (var i = 0; i < arguments.length; i++)
result += arguments[i] || 0;
return result;
}
console.log( addNumbers(1,2,3) );
console.log( addNumbers(1,undefined,3) );
console.log( addNumbers(1,undefined,null) );
(Note that the code I've shown doesn't actually test the type of the supplied values, so if you called it with strings or whatever it would happily concatenate those into the result. You could add an extra test for non-numeric/undefined/null values if desired.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With