Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery outerHeight() returns undefined instead of null

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?

like image 889
bart Avatar asked Dec 11 '22 13:12

bart


1 Answers

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.)

like image 84
nnnnnn Avatar answered Dec 24 '22 13:12

nnnnnn