Does VBScript's IsEmpty have an equivalent in JavaScript? - javascript

Using Javascript, is there an equivalent function or functionality so VBScript's IsEmpty function? The VBScript function returns whether the given variable is "empty", e.g. since all the variables are actually VARIANTs, whether or not the VARIANT has a vt of VT_EMPTY, whereas most of what I've found for Javascript is string-specific or not generalizable.

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 any var.
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:
function isEmpty(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.

Not sure, if this is what it should be
typeof variable == "undefined"

function IsEmpty( theValue )
{
if ( theValue === undefined )
{
return true;
}
return false;
}

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

Not there isnt.
You will have always to test your variables against "null", undefined and "". (that is boring)

Related

Is there a difference between typeof x === 'undefined' vs if (x)

I've always maintained the practice of checking if a value is undefined using
if (typeof x === 'undefined')
However, a colleague is suggesting that using if (x) { is better.
Is there any difference between these two methods from a computational point of view?
There are at least two differences off the top of my mind:
Checking the type as undefined only checks for undefined, unlike if(x), which checks for any truthy values (e.g. true, a non-empty string, a non-zero number, etc)
You can perform typeof on non-existent variables, even in strict mode. You'll get a reference error if you never declared x and did if(x)
"use strict";
const a = undefined;
const b = "truthy value";
if(a) {
console.log("a in if"); // never executes
}
if(typeof a !== "undefined") {
console.log("a with typeof"); // never executes
}
if(b) {
console.log("b in if"); // executes
}
if(typeof b === "undefined") {
console.log("b with typeof"); // never executes
}
try {
if(c) console.log("this should error");
} catch(e) {
console.log("Can't access non-existent variable");
}
console.log("No error:", typeof c);
When should I use which one?
Generally:
Use if(x) when...
You're checking for a boolean
You're checking for (not) 0
You're checking for a non-empty empty string (probably use if(string.length) instead)
Checking the return value of a function (e.g. a function returns null when there's no result for a query or an object when there is (DOM functions like document.getElementById return null when no element with that ID exists))
Use if(typeof x !== "undefined") when...
You're checking whether an object key exists (if(typeof obj.key !== "undefined")) (the proper way as a commentator pointed out is with Object.hasOwn(obj, "key"))
You're checking whether a variable exists (not sure when or why you would do that though)
Checking whether an argument has been passed
Other uses like when you're writing an Express server and checking user-provided content
Something else I probably forgot...
Something that's useful to keep in mind is that Javascript is dynamically typed, even if it looks like it's just variables. There are a handful of types in JS, and Undefined (with caps) is one, and the only value it can hold is undefined. Think of it like saying you have the Number type and it only accepts 42. This is important to know because JS engines have to observe spec.
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.
There is a lot of variation in application code, but you can know that variables that have not been assigned are of type Undefined with value undefined and not something else. Next to Undefined is Null, which has a single value, null. Null, unlike Undefined, needs to be assigned.
In the spec you'll also the find the table for the result you get for each variable type.
You'll notice that Undefined has its own return value, as well as Boolean, but Null returns "object", which is reported to be a mistake in the original spec that we can't get rid of.
With types out of the way, we get to Boolean coercion, which is how if statements work out the condition. The spec has a table of cases that define when a value should be coerced into true or false.
You'll see that an if clause receives the Undefined type, it returns false. The same happens with Null. There are a few other cases that can also return false even if they are not Undefined or Null.
The Number type with values 0, -0, NaN
The String type with length 0 ("")
The BigInt type with value 0
As others have already answered, applications of the spec come in a few different places. The reasons as for why typeof exists and there is an overlap with the falsey evaluation arise from how the JS engines handle values and perform coercion into Boolean.

In typescript/javascript, what does passing an object into an if statement check do? [duplicate]

My question is as title says;
What does this mean:
if( variable ){ /* do something */ }
I mean if variable exist do something or what?
It means if variable is truthy, then execute the block. In JavaScript, the following are falsey
false
0
NaN
undefined
null
"" (Empty String)
Other than the above, everything else is truthy, that is, they evaluate to true.
If the variable didn't exist at all (that is, it had never been declared), that could would throw a ReferenceError because it's trying to read the value of a variable that doesn't exist.
So this would throw an error:
if (variableThatDoesntExist) {
console.log("truthy");
}
This would log the word "truthy":
var variable = "Hi there";
if (variable) {
console.log("truthy");
}
And this wouldn't log anything:
var variable = "";
if (variable) {
console.log("truthy");
}
It's Javacript syntax to check if the variable is truthy or falsy.
It's similar to saying if (variable is true) { /* Do something */}
In Javascript, these are falsy values.
false
0 (zero)
"" (empty string)
null
undefined
NaN (Not-a-Number)
All other values are truthy, including "0" (zero as string), "false" (false as a string), empty functions, empty arrays, and empty objects.

Is it safe to use comparison "if(foo)" instead of "if(foo == null)" on non-primitive types in JavaScript?

Assuming the foo is declared as a non-primitive type variable, but might be uninitialized, is there any possibility to use on non-primitive object comparison as this:
if (foo) {
...
}
or is it better to do it the longer way like this?
// not using "===" here on purpose, because the variable is non-primitive, so the value can't be 0 or empty string
if (foo != null) {
...
}
If it is not equal, then why.
By "non-primitive type" you mean object? Yes, all objects are truthy, so it is enough to distinguish them via if (foo) from any falsy values that the foo variable might contain, such as the primitive values undefined and null.
However, notice that you cannot "declare a variable as a non-primitive type" in JavaScript, so you must ensure by other means that it never has a truthy primitive value. If you could ensure that it always contains an object, you wouldn't need the condition at all.
In my experience, I have found it to be safest to specify exactly what you want in boolean expressions and never rely on type coercion.
If you don't want it to be equal to 0 or null or empty string, then:
if (foo !== 0 && foo !== '' && foo !== null) {
/* note that if foo = undefined, this will still get executed. */
}
Some libraries like Underscore or a framework like Angular have convenience functions for things like that, so you can do:
if (_.isObject(foo) === true) {
/* execute this */
}

Is empty string treated as falsy in javascript?

I've noticed that if you have a statement as the following:
var test = "" || null
test will evaluate to null but if we do something like the following:
var test = "test" || null
test will evaluate to "test", the same holds true for any object in place of the string, so does javascript treat empty string as either a falsy or null value, and if so why? Isn't an empty string still an object, so shouldn't it be handled the same?
I've tested this out in FireFox, Chrome, IE7/8/9, and Node.
Does javascript treat empty string as either a falsy or null value, and if so why?
Yes it does, and because the spec says so (ยง9.2).
Isn't an empty string still an object
No. An primitive string value is no object, only a new String("") would be (and would be truthy)
String is not an object, it's a primitive like number or boolean.
The empty string, NaN, +0, -0, false, undefined and null are the only values which evaluate to false in direct boolean conversion.
A string isn't an object in JS. Other "falsy" values are: 0, NaN, null, undefined.
One dangerous issue of falsey values you have to be aware of is when checking the presence of a certain property.
Suppose you want to test for the availability of a new property; when this property can actually have a value of 0 or "", you can't simply check for its availability using
if (!someObject.someProperty)
/* incorrectly assume that someProperty is unavailable */
In this case, you must check for it being really present or not:
if (typeof someObject.someProperty == "undefined")
/* now it's really not available */
SEE HERE
Yes an empty string is falsy, however new String("") is not.
Note also that it's well possible that
if (x) { ... }
is verified, but that
if (x == false) { ... }
is verified too (this happens for example with an empty array [] or with new String("")).

Reference and datatype checking, are these the same?

I have a simple function in my library that checks the validity of an object reference (object here meaning, a reference to a created HTML element, mostly DIV's). It looks like this:
function varIsValidRef(aRef) {
return ( !(aRef == null || aRef == undefined) && typeof(aRef) == "object");
}
While experimenting i found that this has the same effect:
function varIsValidRef(aRef) {
return (aRef) && typeof(aRef) == "object";
}
I understand there are some controversies regarding the short hand () test? While testing against various datatypes (null, undefined, integer, float, string, array) i could find no difference in the final outcome. The function seem to work as expected.
Is it safe to say that these two versions does the exact same thing?
No, in my opinion these functions don't work the same:
First option
If aRef is not undefined or null and the type of the var is object it returns true.
Second option
First we convert aRef to a boolean. Values like null, undefined and 0 become false, everything else become true. If it is true (so not one of those values) it checks if the type is object.
So the second option return false if aRef is 0, something you don't want. And it isn't option a elegant way to check it, because you check if an object or string or something is equal to a boolean.
And at least they don't return the same thing. The first option returns a boolean, but the second option returns the value you put in the function if (aRef) is false:
varIsValidRef(0);
>>> 0
varIsValidRef('');
>>> ""
varIsValidRef(undefined);
>>> undefined
varIsValidref(null);
>>> null
Because JavaScript use these values as falsy values you don't see the difference between these return values if you use if statements or something like that.
So I suggest you to use the first option.
they are strongly different:
!(aRef == null || aRef == undefined)
this part is evaluated to false with any of these "null", null, "undefined", undefined
(aRef)
while this other with any of these 0, "", false, null, undefined, NaN
Interesting case, but it seems logical for both to behave the same way despite being totally different. Lets see the first staement.
return ( !(aRef == null || aRef == undefined) && typeof(aRef) == "object");
Here,
null and undefined both denote a false state combined with the ! infront, makes it equal to the expression aRef which will return true in case both are either not null or not undefined.
They don't do the same, though they end up with the same results.
The first function is more strict in what it will count as false together, or if it's not, if its an object.
The second function will check if aRef is !false or not any of the falsy values (ie [], null, undefined) and check if the type is an object if it isn't.
I would prefer the first function, since its stricter in what it accepts, but if its all the same the function which performs the best should be used.
As for the controversy, its true that you have to be careful about how/when you use falsy values in equations but if it does what you want it to do (and for that you'll need to know what falsy values are) and you implement it correctly it should be no problem. The two are hard to put together though. So with that, if this does what you want it to do, and nothing more or less, by all means use it.

Categories

Resources