Is empty string treated as falsy in javascript? - 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("")).

Related

What is the difference between truthy and falsy with true and false in JavaScript?

I have a question concerning some concepts in JavaScript such as (truthy, true) and (falsy, false).
I know the type of 1 is not true but the question is: why 1 == true?
What was the main reason of ECMAScript to consider 1 or "ghsagh" as true?
I also cannot understand the meaning of truthy and falsy.
What was the benefit of this consideration?!
JavaScript likes to convert values to other types implicitly whenever possible. Because of that, when comparing booleans to other types of variables, JavaScript uses the same logic as older programming languages. A value that represents empty, null, or zero (such as 0, or "") evaluates to false, and any other value (such as 1, 5, -19, "ghsfsah", or other meaningful content) evaluates to true.
Why does it do this? Well for one it allows developers a small shortcut when checking to see if a variable has content. For example, if a user doesn't give input in a text field, we can easily check to see if a field is empty and prompt the user.
if ( !textfield.value ) {
alert( "Please enter something in the text box" );
}
If you need to see if something is actually true or false, you can use ===.
JavaScript is very flexible about the types of values it requires. If JavaScript wants a boolean, it will convert whatever value you give it to a boolean.
Some values (“truthy” values) convert to true and others (“falsy” values) convert to false.
The following values convert to, and therefore work like, false:
undefined
null
0
-0
NaN
"" // the empty string
All other values, including all objects (and arrays) convert to, and work like, true.
As an example, suppose that the variable o either holds an object or the value null. You can test explicitly to see if o is non-null with an if statement like this:
if (o !== null){
....
}
The strict not-equal operator !== compares o to null and evaluates to either true or false. But you can omit the comparison and instead rely on the fact that null is falsy and objects are truthy:
if (o){
....
}
In the first case, the body of the if will be executed only if o is not null. So the code block will execute even if o is set to undefined.
The second case is less strict: it will execute the body of the if only if o is not false or any falsy value (such as null or undefined). Which if statement is appropriate for your program really depends on what values you expect to be assigned to o. If you need to distinguish null from 0 and "", then you should use an explicit comparison.

Why is "" == [null] true in JavaScript?

I know JavaScript has lots of insane results with comparisons between types, though I don't fully understand why. Came across this one today.
Why does
"" == [null]
evaluate to true in JavaScript?
Some more Javascript equality amusement, thanks to #Qantas:
Why does 2 == [2] in JavaScript?
Why is 0 == "" true in JavaScript
Why if([]) is validated while [] == false in javascript?
Why does !{}[true] evaluate to true in JavaScript?
The "Abstract Equality Comparison Algorithm" has many parts, but the important one here is this:
If Type(x) is either String or Number and Type(y) is Object,
return the result of the comparison x == ToPrimitive(y).
(There's a mirror-image of that too.) So, because "" is a string and [null] is an object, we've got to first convert [null] to a string by calling ToPrimitive([null]). That's an internal operation described as follows, when it's asked to convert an Object instance to a primitive value:
Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.
Now, the [[DefaultValue]] internal operation will call .toString() on the object and return that value. Try [null].toString() in your browser console:
> [null].toString()
""
And there you have it.
Edit: And why is [null].toString() an empty string? Because the .toString() operation on Array instances always just calls .join(), and that always yields an empty string for null and undefined values. Thus an array of one null ends up as just a single empty string.
It's according to the arcane type-conversion rules of Javascript. Rule #8:
If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
So the comparison is between x = "" and y = [null] converted to a string using ToPrimitive. Converting an array with one null element results in an empty string (because Array.toString() returns a comma-separated list of values), hence they evaluate to equal.
Why does "" == [null] evaluate to true?
Because you're comparing an array with a string, using the non-strict equality operator == - so it will try to cast values to the same type before comparing them.
What happens in detail is:
you compare a string to an object, so the object is cast to a string:
When an array is cast to a primitive value, it's .toString() method is invoked (as explained in detail by the other answers), which is equivalent to calling .join():
which in case of a one-element array that only contains an undefined or null value returns the empty string
which finally is equivalent to the empty string
This third step is the unexpected one ([null]+"" != null+""), if it actually did cast that to a string the result would have been "null" and your equality be false.
Let's look at the spec and follow through each step
Going via the Abstract Equality Comparison Algorithm (§11.9.3):
typeof ""; // string and typeof [null]; // object so not applicable
neither is null or undefined so not applicable
same as 2
neither is a number, not applicable
same as 4
neither is a bool, not applicable
again not applicable
finally, something applicable, now we need to know ToPrimitive([null])
§9.1 ToPrimitive for Objects says we need to work out [[DefaultValue]] (§8.12.8), points 1 and 2 of which say if you can do .toString and it gives a string, return that, so
[null].toString(); // ""
So we are now performing the comparison "" == "" which is true by the Abstract Equality Comparison Algorithm's point 1. d.
If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
JavaScript is weakly typed; you can use the following to get a false result:
"" === [null]
The value null is a JavaScript literal representing null or an "empty" value, i.e. no object value is present. It is one of JavaScript's primitive values.
The value null is a literal (not a property of the global object like undefined can be). In APIs, null is often retrieved in place where an object can be expected but no object is relevant. When checking for null or undefined beware of the differences between equality (==) and identity (===) operators (type-conversion is performed with the former).
typeof null // object (bug in ECMAScript, should be null)
typeof undefined // undefined
null === undefined // false
null == undefined // true

What does this javascript code snippet mean?

Here is the code snippet:
var prjId = navObj.itemId || navObj
Does this mean that prjId is either equal to navObj.itemId or navObj? What does it then mean that a variable is equal to navigation object?
Thank you in advance for answers!
This is equivalent to the following:
var prjId;
if(navObj.itemId)
prjId = navObj.itemId;
else
prjId = navObj;
If navObj.itemId is set to false or has not been defined at all,
prjId = navObj;
otherwise:
prjId = navObj.itemId;.
No. The || operator first tries to convert navObj.itemId to a Boolean value.
It will be converted to true if it is already the Boolean value, true, a number other than 0 or NaN, a non-empty string, or an object that is not null or undefined. These are known as "truthy" values.
It will be converted to false if it is already the Boolean value false, 0, NaN, an empty string, null or undefined. These are known as "falsey" values.
If navObj.itemId is "truthy", navObj.itemId is assigned to prjId, otherwise navObj is assigned to prjId.
Further Reading
Logical Operators
It simply means that if the left operand of the logical or operator (||) is a truthy value then return it otherwise return the right operand.
The following values are always falsy:
false
0
empty string
null
undefined
NAN (not a number)
So if navObj.itemId doesn't evaluate to anything of the above, then it will be assigned to the prjId variable.
This is widely used when we have optional parameters in a function, for example. It is a way of specifying the default value for an optional parameter. But of course that's not the only use of it.
It sets prjId to the property of itemId on navObj, if it exists (evaluates to 'truthy'), if it doesn't exist (or it evaluates to 'falsy'), prjId gets set to navObj.

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.

Does VBScript's IsEmpty have an equivalent in 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)

Categories

Resources