Does Vbscript's Isempty Have An Equivalent In Javascript?
Solution 1:
JavaScript has a number of different values which could be considered "empty" and a number of different ways to test for empty.
First things that are empty:
undefined
: values that have been not been assigned. if you create a variable but don't assign anything to it, this is what it will contain.null
: this is an object value that can be assigned to anyvar
.
Next how to test for them. JavaScript is loosely typed with a lot of implicit type conversion. This means that when two values are of different types, the standard equals operator ==
performs type coersion. The triple-equals operator does not perform type coersion which makes it the best operator for testing against very specific values.
you can test the type of a value which returns a string that can be tested (note the triple-equals operator):
if ("undefined" === typeof myFoo) { /* this would be considered empty */ }
you can test against the keyword
undefined
(note the triple-equals operator):if (undefined === myFoo) { /* this would be considered empty */ }
you can test against the keyword
null
(note the triple-equals operator):if (null === myFoo) { /* this would be considered empty */ }
you can test against the empty string
""
(note the triple-equals operator):if ("" === myFoo) { /* this would be the empty string */ }
if you are expecting a value which would not normally be coerced to the boolean value
false
, then you can test for its existence by just testing it directly within the if statement:if (!myFoo) { /* this would be any falsy value, including false, null, 0, undefined */ } else { /* this would be any truthy value, including objects, numbers other than zero, Dates, etc. */ }
Most of the time, if you're expecting something "truthy", you can just test it directly and it will be coerced to a boolean value. So in short, you could probably get away with defining it as this:
functionisEmpty(value) {
return !value;
}
But it often makes more sense just to put a !
or !!
before the object to get its value. Just be careful if you are expecting false
or 0
(zero) as valid values. In those cases it is better to test the typeof
the object and make choices accordingly.
Solution 2:
Not sure, if this is what it should be
typeof variable == "undefined"
Solution 3:
functionIsEmpty( theValue )
{
if ( theValue === undefined )
{
returntrue;
}
returnfalse;
}
Solution 4:
function isEmpty(value){ return value == null || value === ""; }
Solution 5:
Not there isnt.
You will have always to test your variables against "null", undefined and "". (that is boring)
Post a Comment for "Does Vbscript's Isempty Have An Equivalent In Javascript?"