2567

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;
}
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
Alex
  • 29,612
  • 11
  • 60
  • 134
  • 6
    possible duplicate of [How do you check for an empty string in JavaScript?](http://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript) – Dour High Arch Jun 10 '13 at 19:40
  • I made a fiddle for testing: http://jsfiddle.net/J7m7m/886/ – Darren Griffith Oct 13 '16 at 22:42
  • 112
    Protip, never do `(truthy statement) ? true : false;`. Just do `(truthy statement);`. – David Baucum Aug 02 '17 at 17:55
  • 5
    @GeorgeJempty not a dup, since the other answer asks about _strings_ in particular, whereas this one asks about _variables_. – Madbreaks Feb 01 '18 at 00:55
  • 3
    Any correct answer to this question relies entirely on how you define "blank". – Madbreaks Feb 01 '18 at 01:03
  • falsy values in javascript with example : https://developer.mozilla.org/en-US/docs/Glossary/Falsy – Khurshid Ansari Feb 15 '18 at 08:51
  • @David out of curiosity, why not? I've used both with no apparent ill effects. – Jay Jan 30 '19 at 14:54
  • 4
    @Jay It doesn't hurt anything as far as execution of your code. It's just overly verbose. You wouldn't say, "Is are you hungry is true?" You just "Are you hungry" So in code just say `if (hungry) …` instead of `if (hungry === true) …`. Like all coding things in this manner, it's just a matter of taste. More specific to the example provided by the OP he's saying even more verbosely, "If it's true, then true, if not then false" But if it's true, then it's already true. And, if it's false, it's already false. This is akin to saying "If you're hungry then you are, and if not then you aren't." – David Baucum Jan 30 '19 at 22:58
  • 2
    If you want to force a value to be a real boolean, you can do `!!value`. It's just the "not" operator twice, so it reads like "not not value", which is its boolean value. – frodo2975 Jan 19 '20 at 04:29
  • @frodo2975, thanks. Didn’t know you can convert a value to a Boolean this way in JavaScript. That’s the same as C++. Interesting – Alex Jan 19 '20 at 10:18
  • The correct answer relies on how you define false as said. To deal with the false is: `function isEmpty(val) { return (val || val === false) }` – RaaaCode Apr 14 '20 at 21:11
  • This become fail when input is boolean. – Shahid Hussain Abbasi Apr 16 '20 at 06:40
  • wouldn't if(variable == null || variable.length <= 0) do the trick? undefined results in TRUE null results in TRUE [] results in TRUE – Rodrigo Borba May 26 '21 at 00:29

43 Answers43

4931

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.

jAndy
  • 212,463
  • 51
  • 293
  • 348
  • 142
    What if the value is a false boolean that was intended. Sometimes you want to give a default value if there is no value, which won't work if false boolean was passed in. – TruMan1 Dec 30 '12 at 22:38
  • 109
    @TruMan1: in such a case (where your logic dictates the validation) you have to go like `if( value || value === false )`. Same goes for all *falsy values*, we need to validate for those explicitly. – jAndy Dec 31 '12 at 04:58
  • 33
    Except if value is an array. The interpretation of `truthy` could be misleading. In that case we should be checking `value.length != 0` for a non-empty array. – user Apr 18 '14 at 21:06
  • 13
    Just want to add that if you feel the `if` construct is syntactically too heavy, you could use the ternary operator, like so: `var result = undefined ? "truthy" : "falsy"`. Or if you just want to coerce to a boolean value, use the `!!` operator, e.g. `!!1 // true`, `!!null // false`. – KFL Aug 26 '14 at 07:24
  • 8
    Also note that this will not check for strings which only contain whitespace characters. – Christophe Roussy Nov 21 '14 at 10:28
  • 1
    Wow. JavaScript is prettier than Ruby for once. What is the world coming to? – Aaron Gray Feb 12 '15 at 01:54
  • Another interesting fact: only NaN variable is not equal to itself. i.e. if you need to check specifically if a variable is NaN then use (var !== var). ```var x = NaN; x !== x (true)``` – Rohit Mar 05 '15 at 15:27
  • Another reason to check if length is greater than 0 (in addition to the array check mentioned by @buffer), is that " " (a space) is not considered 'truthy' but it is conceptually blank. – Gayle May 04 '15 at 19:11
  • 3
    Be aware that this will produce undesired results if `0` is actually an okay `value` (which it is in most cases where some integer or decimal value is to be stored in `value`). – connexo Jun 16 '15 at 15:05
  • any IE10 version of this? – Brad Jun 17 '15 at 21:10
  • 1
    `typeof` is no longer safe in ES6. You get a `ReferenceError` if you typdef a variable declared with `let` or `const` later in the scope. More details: http://stackoverflow.com/q/31219420/3242070 – Luboš Turek Jul 06 '15 at 16:58
  • 4
    This is a really simple answer that will lead to a lot of false positives. You need to be more specific when checking values. – BentOnCoding Jul 23 '15 at 17:20
  • apparently the latest fashion is to test for undefined against `(void 0)` as undefined may well be a legitimate variable in scope. – x0n Jan 19 '16 at 05:07
  • 1
    I wonder if this reference to "truthiness" predates Stephen Colbert's coinage of the term? – Jim Feb 10 '16 at 18:01
  • I find the syntax someone difficult to understand: I'm used to seeing something like `if(empty(value)){//value is empty}`. Good to know though – Kolob Canyon Mar 05 '16 at 22:03
  • There seems to be correction in this answer var a; if(a){console.log('I am undefined"');} Prints "I am undefined" in console, where as typeof(a) is still undefined – Avinash Agrawal Sep 07 '16 at 10:31
  • 1
    @jAndy: Thank you, only your solution helped me today to fix a problem :) – Jasmine Oct 09 '16 at 23:43
  • 2
    This is all well and good, unless you are checking for a numeric value, which can include 0. Just a heads up, as it may, at some point, bite you right on the ass, just like it did for me today. I was checking for the existence of a variable retrieved from an endpoint (json) and doing a price calculation. The price was 0. My code thus failed, as 0 in my case was a valid value. – Matthew Trow Jan 04 '17 at 17:02
  • Does the "0" mean it will check for array length? I'm working on some inherited JS and there are a lot of checks for NULL and variable.length > 0. I know truthy with get the NULL but does it also check an array variable having a length? – Caverman Mar 09 '17 at 14:48
  • No, not at all. Checking like `if( array_name )` will always be `true` if `array_name` references anything. That includes an empty array (object). Short: The condition will just check the reference, not the content, so you have to check for `array_name.length` explicitly if you need to know if there are any elements contained by that js-array. – jAndy Mar 10 '17 at 13:10
  • I ran across this answer and kept using this solution, until I had a _0_ value not triggering an if. The "0" exception should be in bold. – Buffalo May 02 '17 at 13:39
  • 1
    If the value is either empty object `{}` or empty array `[]` this will return `true`. – iaforek Oct 04 '17 at 14:23
  • undefined values resolve as undefined in this case, not false – Sam Alexander Oct 20 '17 at 20:25
  • The answer is partially wrong. If you have const value = '' and do if (!value) it will evaluate to true even without a value. Although you can do shorthand, shorthand becomes quite confusing in large scale projects where you need to know what the expected fail value should be when reading code. Shorthand is painful when working with projects you didn't write yourself. – Cazineer Jan 18 '18 at 04:53
  • This is definitely what you don't want to do, it will return true too often. Definite javascript mistake. – user378380 Mar 07 '19 at 00:14
  • See python. Even `[]` will test as `false`. This is a choice of course as you can still use `==` for values or `is` in some cases (not going to explain this last one here though) – Rafe Apr 24 '19 at 01:27
  • How to include test for an empty object? const emptyObject = {}, will return true if tested. – Ed of the Mountain Aug 05 '19 at 20:24
  • I cant believe this answer got 4000 votes and marked as correct. null, undefined and false(y) are not the same. – Nicholas Hamilton Oct 20 '19 at 02:32
  • Also remember that !!"0" === true, sometimes it sneaks in like when you get it from – Dulguun Otgon Nov 14 '19 at 01:47
  • what about "null"? – Leon Jun 20 '20 at 07:49
  • in es6 val?doSomthing():null; – Omar bakhsh Available to work Jan 17 '21 at 15:35
  • 0 is pretty much always considered defined and the most common source of bugs with this type of code. Seen it way too many times. – Jonathan Feb 04 '21 at 13:39
  • this method dont work if the variable is zero (0) – fcaserio Mar 05 '21 at 15:26
  • @fcaserio The value `0` is mentioned in the original post. – jAndy Mar 09 '21 at 22:37
260

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
Salman A
  • 229,425
  • 77
  • 398
  • 489
  • 35
    Checking for only `null` or `undefined` can be done like so: `if (value == null)`. Mind the `==` operator that coerces. If you check like this `if (value === null || value === undefined)`, you forgot/don't know how Javascript coerces. http://webreflection.blogspot.nl/2010/10/javascript-coercion-demystified.html – Christiaan Westerbeek Jul 03 '14 at 11:46
  • 36
    @ChristiaanWesterbeek: your point that `arg == null` produces same results as `arg === undefined || arg === null`. However, I consider the latter example more readable. – Salman A Jul 07 '14 at 04:02
  • 11
    `arg == null` is pretty common in my experience. – Bryan Downing Oct 10 '14 at 01:56
  • 9
    `return value === (void 0)` is safer than testing against `undefined` which may well be a legitimate variable in scope, sadly. – x0n Jan 19 '16 at 05:09
  • @ChristiaanWesterbeek then why this produces a reference error? https://jsfiddle.net/00rb295d/ – Sharky Oct 17 '16 at 07:31
  • @Sharky Because the variable is not declared. Use `typeof` if you don't even know if you declared the variable. See the accepted answer for more details. – Christiaan Westerbeek Oct 17 '16 at 08:51
  • @ChristiaanWesterbeek then your initial comment is wrong. – Sharky Oct 17 '16 at 09:57
  • 4
    @Sharky There's a difference between a variable that is undefined and an undeclared variable: http://lucybain.com/blog/2014/null-undefined-undeclared/ – Christiaan Westerbeek Oct 17 '16 at 10:22
99
function isEmpty(value){
  return (value == null || value.length === 0);
}

This will return true for

undefined  // Because undefined == null

null

[]

""

and zero argument functions since a function's length is the number of declared parameters it takes.

To disallow the latter category, you might want to just check for blank strings

function isEmpty(value){
  return (value == null || value === '');
}
Mike Samuel
  • 109,453
  • 27
  • 204
  • 234
  • 11
    `undefined == null` but `undefined !== null` – Ian Boyd Feb 22 '14 at 15:06
  • 3
    @IanBoyd that is because you are comparing == to ===. this means that undefined == null (true) undefined != null (false) undefined === null (false) undefined !== null(true) would be better to give a bit more information in order to be helpful and push people in the right direction. moz doc on the difference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness – Corey Young Jan 14 '16 at 18:03
57

This is the safest check and I haven't seen it posted here exactly like that:

if (typeof value !== 'undefined' && value) {
    //deal with value'
};

It will cover cases where value was never defined, and also any of these:

  • null
  • undefined (value of undefined is not the same as a parameter that was never defined)
  • 0
  • "" (empty string)
  • false
  • NaN

Edited: Changed to strict equality (!==) because it's the norm by now ;)

guya
  • 4,195
  • 33
  • 25
  • 10
    I didn't downvote, but with regards to strict equality comparison, the general rule is that unless you _need_ implicit type conversion than strict comparison should be used. – J.Steve Dec 04 '13 at 08:45
  • 2
    Thanx for your comment Steve. That general rule is just fine. I just expect for ppl to understand why they use one or the other. Every way you look ppl will be glad to preach you about "always always use strict" - like it's the most important thing in Javascript. I've seen too many cases like **if(val !== null)** which obviously lead to an unwanted result. It's fine to say that when in doubt - use strict, but it's better to not be in doubt. – guya Dec 07 '13 at 22:11
  • 6
    I think the point here is that we expect the `typeof` operator to return a string so using the strict equality check is technically more accurate, more specific, and faster. So really, there is no reason to use the loose comparison, not the other way around. Also `val !== null` is perfectly valid in many cases - I do it all the time. I agree with your non-conformity argument, but I think this is a poor example to make it with. Not trying to troll you. – Bryan Downing Oct 10 '14 at 02:10
  • Thanx for your comment Bryan, You use val !== null because you know what you’re doing. A beginner will want to have a fallback to when val is falsy. But, val will never be null it’ll be undefined. If only he didn’t listen to that advice to “always always use strict” he’ll have less bugs. I’ve seen this happens in production code. typeof always returns a string and speed diff will be redundant. So, the only argument for using strict in the above case is consistency. I’ve said “No need for strict equality”. It doesn’t mean that you can’t if you want to or if it makes your code more consistent. – guya Oct 11 '14 at 02:26
  • 1
    @guya This deserves a vote simply for the edit after 7 years! Especially given the above discussion back in the day ;) Kudos Sir! – rmcsharry Dec 01 '20 at 23:31
30

You may find the following function useful:

function typeOf(obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}

Or in ES7 (comment if further improvements)

function typeOf(obj) {
  const { toString } = Object.prototype;
  const stringified = obj::toString();
  const type = stringified.split(' ')[1].slice(0, -1);

  return type.toLowerCase();
}

Results:

typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map

"Note that the bind operator (::) is not part of ES2016 (ES7) nor any later edition of the ECMAScript standard at all. It's currently a stage 0 (strawman) proposal for being introduced to the language." – Simon Kjellberg. the author wishes to add his support for this beautiful proposal to receive royal ascension.

Vix
  • 818
  • 8
  • 16
  • +1 it is helpfull to know the object of type ['regexp'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp), 'array' and 'function' – Yash Oct 05 '15 at 06:58
  • @Vix, why is the ES7 version any better? – GollyJer Sep 03 '17 at 04:26
  • It isn't, was experimenting with more readable ways of expressing the same functionality making use of: destructuring assignment, bind operator. – Vix Sep 03 '17 at 13:37
  • 3
    Note that the bind operator (`::`) is not part of ES2016 (ES7) nor any later edition of the ECMAScript standard at all. It's currently a stage 0 (strawman) proposal for being introduced to the language. – Simon Kjellberg Feb 12 '18 at 18:54
27

The first answer with best rating is wrong. If value is undefined it will throw an exception in modern browsers. You have to use:

if (typeof(value) !== "undefined" && value)

or

if (typeof value  !== "undefined" && value)
krupar
  • 333
  • 3
  • 5
  • 3
    eee... I think this is wrong as if(value) is sufficient (except empty objects / arrays). if value is 'undefined' the 'if' confition won't pass. – Oskar Szura Oct 15 '14 at 14:09
  • 4
    This conflates variables which are not defined (which throw a ReferenceError on evaluation), which are different to variables with the `undefined` value. – Qantas 94 Heavy Jan 16 '15 at 14:04
  • 2
    I got the same error here. if(x), if(!x), if(!!x) will all throw error if x is undefined. – shaosh Jun 06 '15 at 00:51
  • `if(value === 0) gameOver();` ;) – Madbreaks Feb 01 '18 at 00:53
  • This answer is also wrong because it returns false when `value` is zero, which is _not_ what op is looking for. – Madbreaks Feb 01 '18 at 01:02
  • Read @Qantas94Heavy comment that will clarify the confusion here. We get an exception when referring a variable which is not defined. But here variable is defined and only value is not defined. – Ranjith Kumar Jul 27 '20 at 09:47
22

A solution I like a lot:

Let's define that a blank variable is null, or undefined, or if it has length, it is zero, or if it is an object, it has no keys:

function isEmpty (value) {
  return (
    // null or undefined
    (value == null) ||

    // has length and it's zero
    (value.hasOwnProperty('length') && value.length === 0) ||

    // is an Object and has no keys
    (value.constructor === Object && Object.keys(value).length === 0)
  )
}

Returns:

  • true: undefined, null, "", [], {}
  • false: true, false, 1, 0, -1, "foo", [1, 2, 3], { foo: 1 }
Alexandre Magro
  • 860
  • 2
  • 7
  • 20
21

This condition check

if (!!foo) {
    //foo is defined
}

is all you need.

Aryeh Beitz
  • 1,360
  • 16
  • 20
JerryP
  • 401
  • 4
  • 10
  • I assume that this is just a snippet. But `if` already does a falsy check, which this just converts to a Boolean. Does it catch any cases which a normal `if(foo)` does not catch? – Daan van Hulst Jun 28 '17 at 07:38
  • 1
    This is perfect for when you need something inline, for example I need a react attribute (called active) that's true when a string isn't empty - an if statement would be overkill so I can just use `active={!!foo}` – Ben Kolya Mansley Jan 23 '18 at 20:01
  • 6
    Unless foo is 0 – Gorky Jun 22 '20 at 05:36
19

! check for empty strings (""), null, undefined, false and the number 0 and NaN. Say, if a string is empty var name = "" then console.log(!name) returns true.

function isEmpty(val){
  return !val;
}

this function will return true if val is empty, null, undefined, false, the number 0 or NaN.

OR

According to your problem domain you can just use like !val or !!val.

Arif
  • 4,274
  • 3
  • 40
  • 64
  • This doesn't really say if the variable is empty, since false and 0 can be valid values and not constitute an empty value. The value of having an isEmpty function would be to make sure values you expect that are empty return true. in my opinion null,undefined, NaN, and an empty string are the values that make sense as empty. – Corey Young Jan 14 '16 at 18:09
  • 11
    Why use ``isEmpty(val)`` if you could just do ``!val``? – Allen Linatoc Apr 15 '16 at 00:44
  • It is up to you. You can use it to increase readability. Otherwise if you think the team you work they are more advance coder, then you can use just `!val` or `!!val` according to your problem domain. – Arif Apr 16 '16 at 09:09
17

You are a bit overdoing it. To check if a variable is not given a value, you would only need to check against undefined and null.

function isEmpty(value){
    return (typeof value === "undefined" || value === null);
}

This is assuming 0, "", and objects(even empty object and array) are valid "values".

tcooc
  • 18,644
  • 3
  • 34
  • 53
14

Take a look at the new ECMAScript Nullish coalescing operator

You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with null or undefined.

let x = foo ?? bar();

Again, the above code is equivalent to the following.

let x = (foo !== null && foo !== undefined) ? foo : bar();
Daniel Delgado
  • 3,056
  • 3
  • 26
  • 35
11

Here's mine - returns true if value is null, undefined, etc or blank (ie contains only blank spaces):

function stringIsEmpty(value) {

    return value ? value.trim().length == 0 : true;

}
DavidWainwright
  • 2,647
  • 1
  • 24
  • 29
  • 1
    I did a test on several methods here. With a check for undefined, your function works great. So I use if(typeof value !== 'undefined' && !IsEmpty(value)) OR, if you actually want to check for empty, you can use if(typeof value === 'undefined' || IsEmpty2(value)). This will work for null; Undefined; 0; ""; " "; false – RationalRabbit Jan 30 '20 at 10:43
10

If you prefer plain javascript try this:

  /**
   * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
   * length of `0` and objects with no own enumerable properties are considered
   * "empty".
   *
   * @static
   * @memberOf _
   * @category Objects
   * @param {Array|Object|string} value The value to inspect.
   * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
   * @example
   *
   * _.isEmpty([1, 2, 3]);
   * // => false
   *
   * _.isEmpty([]);
   * // => true
   *
   * _.isEmpty({});
   * // => true
   *
   * _.isEmpty('');
   * // => true
   */

function isEmpty(value) {
    if (!value) {
      return true;
    }
    if (isArray(value) || isString(value)) {
      return !value.length;
    }
    for (var key in value) {
      if (hasOwnProperty.call(value, key)) {
        return false;
      }
    }
    return true;
  }

Otherwise, if you are already using underscore or lodash, try:

_.isEmpty(value)
l3x
  • 27,652
  • 1
  • 45
  • 35
  • 3
    Have tried your code. I get an error message in the console that says: "Uncaught reference error: isArray() is not defined". Otherwise, would be great if it worked. – crmprogdev Oct 22 '15 at 18:58
  • 11
    In the case of lodash at least, `_.isNil` is the function you're looking for, not `_.isEmpty`. [isNil documentation](https://lodash.com/docs#isNil), [isEmpty documentation](https://lodash.com/docs#isEmpty) – Snixtor May 29 '16 at 02:07
  • 1
    This would fail if value is boolean and has the value true. – kalyanbk Apr 24 '17 at 19:28
  • 3
    Plain javascript doesn't have `isArray` or `isString` functions on the `window`. – GFoley83 Oct 15 '17 at 19:49
  • @GFoley83 - You caught me! I have my reasons for not using Windows. I actually cover the topic in the chapter that talks about the history and progression of software languages. More relevant info will likely be the discussion/code demonstrating Monadic Error Handling in my book, Learn Functional Programming in Go. Cheers! – l3x Nov 05 '17 at 21:45
  • 2
    @l3x: Is that a joke? – Ry- Apr 04 '19 at 15:01
7
return val || 'Handle empty variable'

is a really nice and clean way to handle it in a lot of places, can also be used to assign variables

const res = val || 'default value'
cubefox
  • 1,059
  • 9
  • 18
  • A lot of places but not when the default is `true` and you're trying to supply or return a `val` of `false`. – Molomby Mar 20 '19 at 00:42
  • @Molomby that's a very specific edge case but even that is easily handled `const res = falsyValue ? true : falsyValue` – cubefox Mar 21 '19 at 13:50
6

If the variable hasn't been declared, you wont be able to test for undefined using a function because you will get an error.

if (foo) {}
function (bar) {}(foo)

Both will generate an error if foo has not been declared.

If you want to test if a variable has been declared you can use

typeof foo != "undefined"

if you want to test if foo has been declared and it has a value you can use

if (typeof foo != "undefined" && foo) {
    //code here
}
herostwist
  • 3,362
  • 1
  • 22
  • 32
5

To check Default Value

function typeOfVar (obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
function isVariableHaveDefaltVal(variable) {
    if ( typeof(variable) === 'string' ) {  // number, boolean, string, object 
        console.log(' Any data Between single/double Quotes is treated as String ');        
        return (variable.trim().length === 0) ? true : false;
    }else if ( typeof(variable) === 'boolean' ) {
      console.log('boolean value with default value \'false\'');
        return (variable === false) ? true : false;
    }else if ( typeof(variable) === 'undefined' ) {
        console.log('EX: var a; variable is created, but has the default value of undefined.'); 
        return true;
    }else if ( typeof(variable) === 'number' ) { 
        console.log('number : '+variable);
        return (variable === 0 ) ? true : false;
    }else if ( typeof(variable) === 'object' ) {
   //   -----Object-----
        if (typeOfVar(variable) === 'array' && variable.length === 0) {
            console.log('\t Object Array with length = ' + [].length); // Object.keys(variable)
            return true;
        }else if (typeOfVar(variable) === 'string' && variable.length === 0 ) {
            console.log('\t Object String with length = ' + variable.length);
            return true;
        }else if (typeOfVar(variable) === 'boolean' ) {
            console.log('\t Object Boolean = ' + variable);
            return (variable === false) ? true : false;
        }else if (typeOfVar(variable) === 'number' ) {
            console.log('\t Object Number = ' + variable);
            return (variable === 0 ) ? true : false;
        }else if (typeOfVar(variable) === 'regexp' && variable.source.trim().length === 0 ) {
       console.log('\t Object Regular Expression : ');
        return true;
        }else if (variable === null) {
       console.log('\t Object null value');
        return true;
        }
    }
    return false;
}
var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");
//The "g" flag in the regex will cause all spaces to get replaced.

check Result:

isVariableHaveDefaltVal(' '); // string          
isVariableHaveDefaltVal(false); // boolean       
var a;           
isVariableHaveDefaltVal(a);               
isVariableHaveDefaltVal(0); // number             
isVariableHaveDefaltVal(parseInt('')); // NAN isNAN(' '); - true         
isVariableHaveDefaltVal(null);              
isVariableHaveDefaltVal([]);               
isVariableHaveDefaltVal(/ /);              
isVariableHaveDefaltVal(new Object(''));               
isVariableHaveDefaltVal(new Object(false));            
isVariableHaveDefaltVal(new Object(0)); 
typeOfVar( function() {} );

I used @Vix function() to check the object of which type.

using instansof «

var prototypes_or_Literals = function (obj) {
    switch (typeof(obj)) {
        // object prototypes
        case 'object':
            if (obj instanceof Array)
                return '[object Array]';
            else if (obj instanceof Date)
                return '[object Date]';
            else if (obj instanceof RegExp)
                return '[object regexp]';
            else if (obj instanceof String)
                return '[object String]';
            else if (obj instanceof Number)
                return '[object Number]';

            else
                return 'object';
        // object literals
        default:
            return typeof(obj);
    }   
};
output test «
prototypes_or_Literals( '' ) // "string"
prototypes_or_Literals( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]"        
Yash
  • 7,342
  • 2
  • 55
  • 63
  • [Comparison Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) checks **== [Data]. === [Data, Type Of Object]** JS numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. `// Number Type [int, float literals ] var int = 77; var float = 77.7; console.log( int.toFixed(10) + '\t' + float.toFixed(10) ); // Object Type var number = new Number( 77 ); if( int != float ) console.log('Data Not Equal'); if( int == number && int !== number ) console.log('Data is Equal & Types vary');` – Yash Jan 25 '16 at 10:20
5

It may be usefull.

All values in array represent what you want to be (null, undefined or another things) and you search what you want in it.

var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1
ddagsan
  • 1,573
  • 15
  • 20
5
function isEmpty(obj) {
    if (typeof obj == 'number') return false;
    else if (typeof obj == 'string') return obj.length == 0;
    else if (Array.isArray(obj)) return obj.length == 0;
    else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
    else if (typeof obj == 'boolean') return false;
    else return !obj;
}

In ES6 with trim to handle whitespace strings:

const isEmpty = value => {
    if (typeof value === 'number') return false
    else if (typeof value === 'string') return value.trim().length === 0
    else if (Array.isArray(value)) return value.length === 0
    else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
    else if (typeof value === 'boolean') return false
    else return !value
}
Fabian von Ellerts
  • 3,261
  • 28
  • 31
jales cardoso
  • 517
  • 7
  • 9
  • 1
    great function, thank you! handles every type of value - numbers are left out in all other solutions! – Fabian von Ellerts Oct 05 '18 at 12:44
  • 1
    @FabianvonEllerts Please do not try to edit additional code into someone else's answer. Post it as your own answer, as a comment under the answer, or request in a comment that they update the answer themselves. – TylerH Oct 05 '18 at 13:52
5

Vacuousness

I don't recommend trying to define or use a function which computes whether any value in the whole world is empty. What does it really mean to be "empty"? If I have `let human = { name: 'bob', stomach: 'empty' }`, should `isEmpty(human)` return `true`? If I have `let reg = new RegExp('');`, should `isEmpty(reg)` return `true`? What about `isEmpty([ null, null, null, null ])` - this list only contains emptiness, so is the list itself empty? I want to put forward here some notes on "vacuousness" (an intentionally obscure word, to avoid pre-existing associations) in javascript - and I want to argue that "vacuousness" in javascript values should never be dealt with generically.

Truthiness/Falsiness

For deciding how to determine the "vacuousness" of values, we need to accomodate javascript's inbuilt, inherent sense of whether values are "truthy" or "falsy". Naturally, `null` and `undefined` are both "falsy". Less naturally, the number `0` (and no other number except `NaN`) is also "falsy". Least naturally: `''` is falsy, but `[]` and `{}` (and `new Set()`, and `new Map()`) are truthy - although they all seem equally vacuous!

Null vs Undefined

There is also some discussion concerning `null` vs `undefined` - do we really need both in order to express vacuousness in our programs? I personally avoid ever having the letters u, n, d, e, f, i, n, e, d appear in my code in that order. I always use `null` to signify "vacuousness". Again, though, we need to accomodate javascript's inherent sense of how `null` and `undefined` differ:
  • Trying to access a non-existent property gives undefined
  • Omitting a parameter when calling a function results in that parameter receiving undefined:

let f = a => a;
console.log(f('hi'));
console.log(f());
  • Parameters with default values receive the default only when given undefined, not null:

let f = (v='hello') => v;
console.log(f(null));
console.log(f(undefined));

Non-generic Vacuousness

I believe that vacuousness should never be dealt with in a generic fashion. We should instead always have the rigour to get more information about our data before determining if it is vacuous - I mainly do this by checking what type of data I'm dealing with:

let isType = (value, Cls) => {
  // Intentional use of loose comparison operator detects `null`
  // and `undefined`, and nothing else!
  return value != null && Object.getPrototypeOf(value).constructor === Cls;
};

Note that this function ignores polymorphism - it expects value to be a direct instance of Cls, and not an instance of a subclass of Cls. I avoid instanceof for two main reasons:

  • ([] instanceof Object) === true ("An Array is an Object")
  • ('' instanceof String) === false ("A String is not a String")

Note that Object.getPrototypeOf is used to avoid a case like let v = { constructor: String }; The isType function still returns correctly for isType(v, String) (false), and isType(v, Object) (true).

Overall, I recommend using this isType function along with these tips:

  • Minimize the amount of code processing values of unknown type. E.g., for let v = JSON.parse(someRawValue);, our v variable is now of unknown type. As early as possible, we should limit our possibilities. The best way to do this can be by requiring a particular type: e.g. if (!isType(v, Array)) throw new Error('Expected Array'); - this is a really quick and expressive way to remove the generic nature of v, and ensure it's always an Array. Sometimes, though, we need to allow v to be of multiple types. In those cases, we should create blocks of code where v is no longer generic, as early as possible:

if (isType(v, String)) {
  /* v isn't generic in this block - It's a String! */
} else if (isType(v, Number)) {
  /* v isn't generic in this block - It's a Number! */
} else if (isType(v, Array)) {
  /* v isn't generic in this block - it's an Array! */
} else {
  throw new Error('Expected String, Number, or Array');
}
  • Always use "whitelists" for validation. If you require a value to be, e.g., a String, Number, or Array, check for those 3 "white" possibilities, and throw an Error if none of the 3 are satisfied. We should be able to see that checking for "black" possibilities isn't very useful: Say we write if (v === null) throw new Error('Null value rejected'); - this is great for ensuring that null values don't make it through, but if a value does make it through, we still know hardly anything about it. A value v which passes this null-check is still VERY generic - it's anything but null! Blacklists hardly dispell generic-ness.
  • Unless a value is null, never consider "a vacuous value". Instead, consider "an X which is vacuous". Essentially, never consider doing anything like if (isEmpty(val)) { /* ... */ } - no matter how that isEmpty function is implemented (I don't want to know...), it isn't meaningful! And it's way too generic! Vacuousness should only be calculated with knowledge of val's type. Vacuousness-checks should look like this:
    • "A string, with no chars": if (isType(val, String) && val.length === 0) ...

    • "An Object, with 0 props": if (isType(val, Object) && Object.entries(val).length === 0) ...

    • "A number, equal or less than zero": if (isType(val, Number) && val <= 0) ...

    • "An Array, with no items": if (isType(val, Array) && val.length === 0) ...

    • The only exception is when null is used to signify certain functionality. In this case it's meaningful to say: "A vacuous value": if (val === null) ...

Gershy
  • 5,378
  • 1
  • 27
  • 38
5

The probably shortest answer is

val==null || val==''

if you change rigth side to val==='' then empty array will give false. Proof

function isEmpty(val){
    return val==null || val==''
}

// ------------
// TEST
// ------------

var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);

log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");

// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE

More details about == (source here)

Enter image description here

BONUS: Reason why === is more clear than ==

Enter image description here

To write clear and easy understandable code, use explicite list of accepted values

val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)

function isEmpty(val){
    return val===undefined || val===null || val==='' || (Array.isArray(val) && val.length===0)
}

// ------------
// TEST
// ------------

var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);

log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");

// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
4

Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.

function myFunction() {
    var data;  //The Values can be like as null, blank, undefined, zero you can test

    if(!(!(data)))
    {
        alert("data "+data);
    } 
    else 
    {
        alert("data is "+data);
    }
}
Ravikant
  • 79
  • 5
4

If you are using TypeScript and don't want to account for "values those are false" then this is the solution for you:

First: import { isNullOrUndefined } from 'util';

Then: isNullOrUndefined(this.yourVariableName)

Please Note: As mentioned below this is now deprecated, use value === undefined || value === null instead. ref.

BlackBeard
  • 8,598
  • 7
  • 42
  • 55
  • 2
    I thought this was cool so I initially unvoted, but it's a Node.js thing that's been deprecated. Type definitions file says: `/** @deprecated since v4.0.0 - use "value === null || value === undefined" instead. */` – atomictom Oct 02 '18 at 22:16
  • @atomictom I thought its a `typescript` thing. Can you please provide the link of its documentation? – BlackBeard Oct 03 '18 at 03:09
  • Here: https://nodejs.org/api/util.html#util_util_isnullorundefined_object. Also: "I thought this was cool so I initially **upvoted**" that should read :) – atomictom Oct 04 '18 at 20:21
  • Why would the deprecate a useful simple thing like this? geeeeees. – ticktock Jan 21 '20 at 22:01
2
function isEmpty(val){
    return !val;
}

but this solution is over-engineered, if you dont'want to modify the function later for busines-model needings, then is cleaner to use it directly in code:

if(!val)...
Luca C.
  • 7,969
  • 67
  • 67
2
var myNewValue = myObject && myObject.child && myObject.child.myValue;

This will never throw an error. If myObject, child, or myValue is null then myNewValue will be null. No errors will be thrown

Sᴀᴍ Onᴇᴌᴀ
  • 7,491
  • 8
  • 27
  • 56
Keith Blanchard
  • 513
  • 4
  • 3
2

For everyone coming here for having similar question, the following works great and I have it in my library the last years:

(function(g3, $, window, document, undefined){
   g3.utils = g3.utils || {};
/********************************Function type()********************************
* Returns a lowercase string representation of an object's constructor.
* @module {g3.utils}
* @function {g3.utils.type}
* @public
* @param {Type} 'obj' is any type native, host or custom.
* @return {String} Returns a lowercase string representing the object's 
* constructor which is different from word 'object' if they are not custom.
* @reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
* http://javascript.info/tutorial/type-detection
*******************************************************************************/
g3.utils.type = function (obj){
   if(obj === null)
      return 'null';
   else if(typeof obj === 'undefined')
      return 'undefined';
   return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
};
}(window.g3 = window.g3 || {}, jQuery, window, document));
centurian
  • 1,062
  • 11
  • 23
2

If you want to avoid getting true if the value is any of the following, according to jAndy's answer:

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

One possible solution that might avoid getting truthy values is the following:

function isUsable(valueToCheck) {
    if (valueToCheck === 0     || // Avoid returning false if the value is 0.
        valueToCheck === ''    || // Avoid returning false if the value is an empty string.
        valueToCheck === false || // Avoid returning false if the value is false.
        valueToCheck)             // Returns true if it isn't null, undefined, or NaN.
    {
        return true;
    } else {
        return false;
    }
}

It would be used as follows:

if (isUsable(x)) {
    // It is usable!
}
// Make sure to avoid placing the logical NOT operator before the parameter (isUsable(!x)) and instead, use it before the function, to check the returned value.
if (!isUsable(x)) {
    // It is NOT usable!
}

In addition to those scenarios, you may want to return false if the object or array is empty:

You would go about it this way:

function isEmptyObject(valueToCheck) {
    if(typeof valueToCheck === 'object' && !Object.keys(valueToCheck).length){
        // Object is empty!
        return true;
    } else {
        // Object is not empty!
        return false;
    }
}

function isEmptyArray(valueToCheck) {
    if(Array.isArray(valueToCheck) && !valueToCheck.length) {
        // Array is empty!
        return true;
    } else {
        // Array is not empty!
        return false;
    }
}

If you wish to check for all whitespace strings (" "), you may do the following:

function isAllWhitespace(){
    if (valueToCheck.match(/^ *$/) !== null) {
        // Is all whitespaces!
        return true;
    } else {
        // Is not all whitespaces!
        return false;
    }
}

Note: hasOwnProperty returns true for empty strings, 0, false, NaN, null, and undefined, if the variable was declared as any of them, so it might not be the best to use. The function may be modified to use it to show that it was declared, but is not usable.

yaharga
  • 1,743
  • 2
  • 25
  • 56
2

Code on GitHub

const isEmpty = value => (
  (!value && value !== 0 && value !== false)
  || (Array.isArray(value) && value.length === 0)
  || (isObject(value) && Object.keys(value).length === 0)
  || (typeof value.size === 'number' && value.size === 0)

  // `WeekMap.length` is supposed to exist!?
  || (typeof value.length === 'number'
      && typeof value !== 'function' && value.length === 0)
);

// Source: https://levelup.gitconnected.com/javascript-check-if-a-variable-is-an-object-and-nothing-else-not-an-array-a-set-etc-a3987ea08fd7
const isObject = value =>
  Object.prototype.toString.call(value) === '[object Object]';

Poor man's tests

const test = () => {
  const run = (label, values, expected) => {
    const length = values.length;
    console.group(`${label} (${length} tests)`);
    values.map((v, i) => {
      console.assert(isEmpty(v) === expected, `${i}: ${v}`);
    });
    console.groupEnd();
  };

  const empty = [
    null, undefined, NaN, '', {}, [],
    new Set(), new Set([]), new Map(), new Map([]),
  ];
  const notEmpty = [
    ' ', 'a', 0, 1, -1, false, true, {a: 1}, [0],
    new Set([0]), new Map([['a', 1]]),
    new WeakMap().set({}, 1),
    new Date(), /a/, new RegExp(), () => {},
  ];
  const shouldBeEmpty = [
    {undefined: undefined}, new Map([[]]),
  ];

  run('EMPTY', empty, true);
  run('NOT EMPTY', notEmpty, false);
  run('SHOULD BE EMPTY', shouldBeEmpty, true);
};

Test results:

EMPTY (10 tests)
NOT EMPTY (16 tests)
SHOULD BE EMPTY (2 tests)
  Assertion failed: 0: [object Object]
  Assertion failed: 1: [object Map]
Pascal Polleunus
  • 2,166
  • 2
  • 24
  • 27
  • great function, all of the other answers here had multiple issues which yours appears to address, I just wish I'd found it before I'd written my own :p thought you might like to take a look at my work https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in/61350550#61350550 both of our functions appear to have exactly the same output but I've cut down on code a little. Please let me know if I've missed anything. – Sean Bannister Apr 21 '20 at 18:30
  • Did you try my "Poor man's tests"? I think I ended up adding more tests in the function for special cases like Map, WeakMap, and maybe also Date, RegExp. Are you sure about your `value.constructor === Object`? Check [this](https://stackoverflow.com/a/8511350/101831). – Pascal Polleunus Apr 23 '20 at 02:43
  • Yes, I did run your tests, thanks for those, both of our functions return the same results with both of our tests. I keep wondering if I'm missing something outside of these test cases. I believe `value.constructor === Object` is okay, in javascript IF OR statements have execution order so that OR statement will only execute if the previous didn't return TRUE and we've already checked for `Null`. In fact the only purpose of that last OR statement is to detect `{}` and ensure it doesn't return TRUE for things it shouldn't. – Sean Bannister Apr 23 '20 at 09:01
2

The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // detailed address is unknown
  }
};
let customerCity = customer.details?.address?.city;

The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:

let customer = {
  name: "Carl",
  details: { age: 82 }
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city
Sunny Sultan
  • 583
  • 7
  • 17
2
function notEmpty(value){
  return (typeof value !== 'undefined' && value.trim().length);
}

it will also check white spaces (' ') along with following:

  • null ,undefined ,NaN ,empty ,string ("") ,0 ,false
Hassan Ali Shahzad
  • 1,875
  • 18
  • 26
1

This will check if variable of indeterminate nesting is undefined

function Undef(str) 
{
  var ary = str.split('.');
  var w = window;
  for (i in ary) {
    try      { if (typeof(w = w[ary[i]]) === "undefined") return true; }
    catch(e) { return true; }
  }
  return false;
}

if (!Undef("google.translate.TranslateElement")) {

The above checks if the Google translate function TranslateElement exists. This is equivalent to:

if (!(typeof google === "undefined" 
 || typeof google.translate === "undefined" 
 || typeof google.translate.TranslateElement === "undefined")) {
rickdog
  • 690
  • 8
  • 10
1

Try Boolean() and isNaN() (for number type) to check a variable has a value or not.

function isEmpty(val) {
  return typeof val === 'number' ? isNaN(val) : !Boolean(val);
}

var emptyVals = [undefined, null, false, NaN, ''];
emptyVals.forEach(v => console.log(isEmpty(v)));
ParthoShuvo
  • 382
  • 2
  • 10
0

I think using the ? operator is slightly cleaner.

var ? function_if_exists() : function_if_doesnt_exist();
Pedro Pereira
  • 460
  • 5
  • 12
0

Although an oldie, what forget is that they should wrap their code block and then catch the error and then test...

function checkup( t ){
  try{
    for(p in t){
      if( p.hasOwnProperty( t ) ){
        return true;
      }
    }
    return false;
  }catch(e){
    console.log("ERROR : "+e);
    return e;
  }
}

So you really don't have to check for a potential problem before hand, you simply catch it and then deal with it how you want.

Mark Giblin
  • 928
  • 2
  • 12
  • 19
0

You can directly use the equality operator

<script>
    var firstName;
    var lastName = null;
    /* Since null == undefined is true, the following statements will catch both null and undefined */
        if(firstName == null){
            alert('Variable "firstName" is undefined.');
        }    
        if(lastName == null){
           alert('Variable "lastName" is null.');
        }
</script>

demo @ How to determine if variable is undefined or null using JavaScript

jonathan klevin
  • 149
  • 1
  • 2
0
try{

     let vari = obj.propTest; // obj may be don't have propTest property

        ...
} catch(NullException){
    // do something here
}

I think using try catch will avoid any error of null check, also in Angular or JavaScript Just catching null exception and process in it.

nobjta_9x_tq
  • 988
  • 11
  • 16
0

This covers empty Array and empty Object also

null, undefined, ' ', 0, [ ], { }

isEmpty = (value) => (!value  || (typeof v === 'object' &&
   Object.keys(value).length < 1));
Narasimha Reddy - Geeker
  • 2,587
  • 1
  • 12
  • 21
0

Below worked for me. Please do a slight change to make this fast

function isEmpty(obj) {
    if (!obj) return true;
    if (typeof obj == 'number') return false;
    else if (typeof obj == 'string') return obj.length == 0;
    else if (Array.isArray(obj)) return obj.length == 0;
    else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
    else if (typeof obj == 'boolean') return false;
}
Junayed
  • 61
  • 6
0

Most of the existing answers failed for my use case, most returned empty if a function was assigned to the variable or if NaN was returned. Pascal's answer was good.

Here's my implementation, please test and let me know if you find anything. You can see how I tested this function here.

function isEmpty(value) {
  return (
    // Null or undefined.
    (value == null) ||
    // Check if a Set() or Map() is empty
    (value.size === 0) ||
    // NaN - The only JavaScript value that is unequal to itself.
    (value !== value) ||
    // Length is zero && it's not a function.
    (value.length === 0 && typeof value !== "function") ||
    // Is an Object && has no keys.
    (value.constructor === Object && Object.keys(value).length === 0)
  )
}

Returns:

  • true: undefined, null, "", [], {}, NaN, new Set(), //
  • false: true, false, 1, 0, -1, "foo", [1, 2, 3], { foo: 1 }, function () {}
Sean Bannister
  • 2,625
  • 4
  • 28
  • 41
0
  1. you can use the arguments
  2. become arguments to array
  3. filter

function validateAttrs(arg1, arg2, arg3,arg4){
    var args = Object.values(arguments);
    return (args.filter(x=> x===null || !x)).length<=0
}
console.log(validateAttrs('1',2, 3, 4));
console.log(validateAttrs('1',2, 3, null));
console.log(validateAttrs('1',undefined, 3, 4));
console.log(validateAttrs('1',2, '', 4));
console.log(validateAttrs('1',2, 3, null));
x-rw
  • 1,253
  • 10
  • 24
0

Will return false only for undefined and null:

return value ?? false

-1

This function check for empty object {},empty array [], null, undefined and blank string ""

function isEmpty(val) {
  //check for empty object {}, array []
  if (val !== null && typeof val === 'object') {
    if (Object.keys(obj).length === 0) {
      return true;
    }
  }
  //check for undefined, null and "" 
  else if (val == null || val === "") {
    return true;
  }
  return false;
}

var val={};
isEmpty(val) -> true
val=[];
isEmpty(val) -> true
isEmpty(undefined) -> true
isEmpty(null) -> true
isEmpty("") -> true
isEmpty(false) -> false
isEmpty(0) -> false

GorvGoyl
  • 27,835
  • 20
  • 141
  • 143
-3

For my case I tried with if null,'', !variable, But it did not work.

See my code below to get the text from an html field

var status=$(this).text(); //for example (for my case)

if there was no value(no text) in the status variable ,I was trying to set the value 'novalue' to status variable.

the following code worked.

if(status == false)
{
   status='novalue';
} 

when there was no text found for satus variable the above code assigned 'novalue' to the status variable

Hriju
  • 560
  • 1
  • 11
  • 23
  • would really like to know why this is getting downvotes? it would be really helpful. If you are downvoting please explain why you think this answer is wrong. – Hriju Mar 14 '18 at 04:33
  • I think its not reallly answering the question. You explain a problem that you had, but there was already a good solution to the question by somebody else years before you answered it. – John Smith Feb 11 '19 at 10:27
-4

you can always use loadash functions ,like _.nil or _.undefined .They are pretty good to use.