Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:

function isEmpty(val){     return (val === undefined || val == null || val.length <= 0) ? true : false; } 
like image 822
Alex Avatar asked Apr 01 '11 15:04

Alex


People also ask

How do you check a value is empty null or undefined in JavaScript?

Say, if a string is empty var name = "" then console. log(! name) returns true . this function will return true if val is empty, null, undefined, false, the number 0 or NaN.

How check data is null or not in JavaScript?

Javascript null is a primitive type that has one value null. JavaScript uses the null value to represent a missing object. Use the strict equality operator ( === ) to check if a value is null . The typeof null returns 'object' , which is historical bug in JavaScript that may never be fixed.

How do you check if a variable is undefined in JS?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

IS null === undefined JavaScript?

In JavaScript, undefined is a type, whereas null an object. It means a variable declared, but no value has been assigned a value. Whereas, null in JavaScript is an assignment value.


2 Answers

You can just check if the variable has a truthy value or not. That means

if( value ) { } 

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if( typeof foo !== 'undefined' ) {     // foo could get resolved and it's defined } 

If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.

like image 195
jAndy Avatar answered Oct 02 '22 23:10

jAndy


The verbose method to check if value is undefined or null is:

return value === undefined || value === null; 

You can also use the == operator but this expects one to know all the rules:

return value == null; // also returns true if value is undefined 
like image 26
Salman A Avatar answered Oct 03 '22 00:10

Salman A