Checking whether variable is empty in JavaScript? - javascript

There is two kind of JavaScript code for investigating empty/full variable:
if(variable == ''){}
if(!variable){}
I tested both of them, and I achieved identical result. Now I want to know, (first) are they equivalent? And (second) which one is more standard for checking empty/full variable?
var variable1 = 'string';
var variable2 = 12;
var variable3 = true;
if(variable1 == ''){alert('empty-one');}
if(variable2 == ''){alert('empty-one');}
if(variable3 == ''){alert('empty-one');}
if(!variable1){alert('empty-two');}
if(!variable2){alert('empty-two');}
if(!variable3){alert('empty-two');}
As you see, there is no alert.

First is not standard, it only works for defined empty string.
Other will work if value is not truthy ( means something meaningful)
e.g var a;
a == '' will give false result
! a will produce true
e.g. var a = null;
a == '', // false
! a // true
var a = false;
a == '' // fase
! a // true
var a = NaN
a == '' // false
! NaN // true
true == 'true' // false, Boolean true is first converted to number and then compared
0 == '' // true, string is first converted to integer and then compared
== uses The Abstract Equality Comparison Algorithm to compare two operands
For more detail visit http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

In javascript null,'',0,NaN,undefined consider falsey in javascript.
In one sense you can check empty both way
But your first code are checking is it ''
and your 2nd condition is checking is your value are one of them (null,'',0,NaN,undefined)
In my view your 2nd condition is better then first as i don't have to check null,'',0,NaN,undefined seperately

No they are not equivalent. In case first it checks whether the value of variable is equal to the empty string('') or not. So case first will be true iff variable's value is ''. But second case will be true for all the values which are falsey i.e. false, 0, '', null, undefined.

Related

Is 0 considered true in ES6?

Is 0 considered true in ES6? Or all strings considered true?
this is returning true:
var value = "0";
var isTrue = value ? true : false; // true
I thought === was for strict equality.
If it has changed is there a way to get the old way for compatibility sake?
UPDATE:
Thanks. The value I'm receiving will always be a string so I'll check for "0" and "false":
var booleanValue = value && value!=="0" && value!=="false" ? true : false;
"0" is true because it's just a string and has a value, but the 0 as a number is considered false
This is a list of all falsy values in javascript:
false
0
'' or ""
null
undefined
NaN
Only the String '' is a falsy value, meaning that it is an empty string.
'0' is a string with content so it isn't a falsy value, but 0 is one.
All strings that have characters in them are truthy.¹ Only the empty string, "", is falsy.¹
0 (the number) is falsy. "0" is not.
I thought === was for strict equality.
It is. There is no === check in your code. The conditional operator (? :) doesn't do an === check on the condition operand. It does a boolean check, just like if does.
If you used ===, it you'd get false:
var isTrue = value === true ? true : false; // false
Of course, in that case, there's no point to the conditional operator:
var isTrue = value === true; // false
The value I'm receiving will always be a string so I'll check for "0" and "false":
var booleanValue = value && value!=="0" && value!=="false" ? true : false;
It depends on what you want to do and what possible values you might get. For instance, if what you're getting will be a string containing a valid number or a valid boolean (as seems the case from your example there), you could use JSON.parse to parse it to a number or boolean:
var isTrue = !!JSON.parse(str);
(The !! is so that 0 and NaN convert to false and a number that isn't 0 or NaN converts to true.) But again, it depends on what you're receiving, a switch with the values you're expecting may be better, etc.
¹ "falsy" and "truthy":
"falsy" - coerces to false when used as a boolean, such as in a conditional operator as in your question. The falsy values are 0, NaN, null, undefined, "", and of course, false.
"truthy" - coerces to true when used as a boolean. All non-falsy values are truthy, including "0" and "false".
You're inspecting a string containing 0 instead of an actual number 0.
"0" // string
0 // number
A string is considered false if it is equal to '', all other strings are considered true
A number is considered false if it is either 0 or NaN, all other numbers are considered true.
=== indeed means strict equal, meaning a comparison is made on both type and value. So:
true == 1 // true
true === 1 // false
Actually its other way around, for any string, it will return True, for 0 as an integer, it will return False, and for 1 as an integer, it will return True
var value0 = 0;
var value1 = 1;
var str = "23123";
var isTrue0 = value0 ? true : false;
var isTrue1 = value1 ? true : false;
var isTrueStr = str ? true : false;
console.log('0: ' + isTrue0);
console.log('1: ' + isTrue1);
console.log('string: ' + isTrueStr);
isTrue = value - classic error using assignment rather than comparison.

Javascript Optimal way of checking false statement except zero

In javascript we use shortand notation if(input){} to check for empty or null input. We will get false for Null, Undefined, false, 0, NAN, "". My requirements is that I want to get true for any number including zero so I have created a method as follows
function checkFalseExceptZero(value){
if( value !== undefined && value !== null && value !== false && value !== "" && value.length !== 0 ) return true;
else return false;
}
I have added all possible checks in the above method to get the desired result. I am curious if there is any quick, sweet, short or more robust approach to achieve the same?
A simple to understand answer. The three equal signs in JS will not convert type to check if the values equal unlike the two equal signs.
0 == false //true
0 === false //false, because 0 is a number and false is a boolean
Therefore, the answer, if you want to put it inside a function:
JS:
function isNumber(v) {
return typeof v === "number"
}
The function will check the type of the variable. So it is not actually comparing the value to determine the result. The function will only return true if the type of the variable is called number.
Test runs:
isNumber(0) //true
isNumber(false) //false
isNumber("0") //false
isNumber(undefined) //false
In case you want to know, typeof variable will return a string.
My requirements is that I want to get true for any number including
zero so I have created a method as follows
function checkFalseExceptZero(value){
if ( variable.constructor === Array) return !!value.length;
return value === 0 || !!value;
}
This a shorter version of your function. This returns true only when value is 0 or a trully value.
So :
checkFalseExceptZero(null) ==> false;
checkFalseExceptZero(undefined) ==> false;
checkFalseExceptZero(false) ==> false;
checkFalseExceptZero("") ==> false;
checkFalseExceptZero(0) ==> true;
checkFalseExceptZero([]) ==> false;
checkFalseExcpetZero([1]) ==> true;
For any valid number, including 0, JavaScript already exposes the isFinite function. This returns false for all non-numbers, as well as for infinite and NaN
Examples (excerpt from the linked mdn page):
isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false
isFinite(0); // true
isFinite(2e64); // true
isFinite("0"); // true, would've been false with the
// more robust Number.isFinite("0")

How do I negate the parameter for AngularJS ng-if directive?

Quick Example:
There is a routed parameter (/Home/:isLoggedIn) that equates to true or false. (/Demo/#/Home/false) and a controller property
this.loggedIn = this.routeParams.loggedIn;
I have a view (Home.html) that has two elements, each with an ng-if attribute.
<div ng-if="home.loggedIn">
Logged In!
</div>
<div ng-if="!home.loggedIn">
Not Logged In...
</div>
If I navigate to /Demo/#/Home/true then the first element displays and the second does not.
If I navigate to /Demo/#/Home/false then the first element does not display NOR does the second one.
I would expect the !home.loggedIn parameter evaluate to true when the value of loggedIn is, in fact, false.
Any advice here?
It is quite obvious that he problem has its root to the fact that routeParams.loggedIn is a string.
So the solution is quite obvious:
// Change that:
this.loggedIn = this.routeParams.loggedIn;
// To this:
this.loggedIn = this.routeParams.loggedIn === 'true';
But why the weird behaviour ?
Why work not showing anything when loggedIn is 'false' ?
Well, here is why:
The ngIf directive uses the following toBoolean() function to convert its value to boolean:
function toBoolean(value) {
if (typeof value === 'function') {
value = true;
} else if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
If a string is passed to toBoolean() it converts it to lowercase and checks (among other things) if it equals 'false' (in which case it returns false). This is different than the default JavaScript implementation which interprets any non-empty string as true when casting to boolean.
So, let's examine the two cases for both ngIfs:
loggedIn === 'true'
ngIf1 evaluates home.loggedIn --> 'true' (string)
ngIf1 passes this value through toBoolean()
toBoolean('true') returns true (because it sees a string that can't match with any string considered falsy)
ngIf1 renders its content
ngIf2 evaluates !home.loggedIn <=> !'true' --> false (boolean)
(this happens because any non-empty string happens to evaluate to true)
ngIf2 passes this value through toBoolean()
toBoolean(false) returns false
ngIf2 does not render its content
loggedIn === 'false'
ngIf1 evaluates home.loggedIn --> 'false' (string)
ngIf1 passes this value through toBoolean()
toBoolean('false') returns false (because it sees a string that is considered falsy
ngIf1 does not render its content
ngIf2 evaluates !home.loggedIn <=> !'false' --> false (boolean)
(this happens because any non-empty string happens to evaluate to true)
ngIf2 passes this value through toBoolean()
toBoolean(false) returns false
ngIf2 does not render its content
So, this explains the "weird" behaviour (hopefully in an understandable way).
Problem is likely home.loggedIn is a string, when passed to ng-if it is probably evaluating and doing the conversion from string to bool to get the value "false" into false. In the expression evaluation before the value is passed through if you have !"false" that is actually false since any string is true, negating it becomes false.

Javascript if condition on boolean

Can you explain why the if condition doesn't work without the eval function:
var myBoolean= document.getElementById("someBoolean").value; //This is a 'false'
if(myBoolean)
{
alert(Your boolean is True); //This condition always getting executed even though myBoolean is false;
}
if(eval(myBoolean))
{
alert("You will never see this alert bcoz boolean is false");
}
In Javascript the following values are treated as false for conditionals:
false
null
undefined
The empty string ''
The number 0
The number NaN
Everything else is treated as true.
'false' is none of the above, so it's true.
The string 'false' evaluates to the boolean true
This is because it's not actually a boolean, it's a the string 'false'. When you convert a string to a boolean, '' is false and anything else is true.
You check if it's equal to the string 'false' (or 'true') or not.
var myBoolean = 'false'; // (string)
myBoolean = myBoolean !== 'false'; //false (boolean)
'false' == true, crazily enough because of JavaScript's implicit type coercion. Check out these other examples from Crockford's The Elements of JavaScript Style.
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined
// true
' \t\r\n ' == 0 // true
You could solve this particular problem by changing your code to something like
var myBoolean = document.getElementById("someBoolean").value === "true"
Also, it is almost always better to use !! and === rather than ! and ==
document.getElementById("someBoolean") does not return a boolean true/false it returns an element or undefined / null
you could reverse your logic and get the expected result:
if(!myBoolean)
{
alert('This element does not exist');
}
if(!eval(myBoolean))
{
alert("Do not know why you would ever want to do this");
// you could do typeof()
}
Try:
var myBoolean= document.getElementById("someBoolean").value; //This is a 'false'
if(myBoolean != "false")
{
alert(Your boolean is True); //This condition always getting executed even though myBoolean is false;
}
Like others have said, a string isn't a boolean value, so using it as though it was will give you a logical error.
A string IS a boolean truth value according to ECMA
var a = ""<br/>
a&&false //-> false<br/>
a||false //-> "" (truthy)<br/>

Convert string to Boolean in javascript [duplicate]

This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 5 years ago.
How to convert a string to Boolean ?
I tried using the constructor Boolean("false"), but it's always true.
I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval... which you don't).
var myBool = myString == "true";
I would like to answer this to improve upon the accepted answer.
To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.
function stringToBool(val) {
return (val + '').toLowerCase() === 'true';
}
JSPerf
you can also use JSON.parse() function
JSON.parse("true") returns true (Boolean)
JSON.parse("false") return false (Boolean)
Actually you don't get the meaning of Boolean method.It always return true if the variable is not null or empty.
var variable = some value;
Boolean(variable);
If my variable have some value then it will
return true
else
return false
You can't use Boolean as you think.
trick string to boolean conversion in javascript. e.g.
var bool= "true";
console.log(bool==true) //false
var bool_con = JSON.parse(bool);
console.log(bool_con==true) //true
I am still amazed how people vote blindly for solutions that won't work, like:
var myBool = myString == "true";
The above is so BUGGY!!!
Not convinced? Just try myString = true (I mean the boolean true). What is the evaluation now? Opps: false!
Alternative
var myString=X; // X={true|false|"true"|"false"|"whatever"}
myString=String(myString)=='true';
console.log(myString); // plug any value into X and check me!
will always evaluate right!
Depends on what you see as false in a string.
Empty string, the word false, 0, should all those be false or is only empty false or only the word false.
You probably need to buid your own method to test the string and return true or false to be 100 % sure that it does what you need.
I believe the following code will do the work.
function isBoolean(foo) {
if((foo + "") == 'true' || (foo + "") == 'false') {
foo = (foo + "") == 'true';
} else {
console.log("The variable does not have a boolean value.");
return;
}
return foo;
}
Explaining the code:
foo + ""
converts the variable 'foo' to a string so if it is already boolean the function will not return an invalid result.
(foo + "") == 'true'
This comparison will return true only if 'foo' is equal to 'true' or true (string or boolean). Note that it is case-sensitive so 'True' or any other variation will result in false.
(foo + "") == 'true' || (foo + "") == 'false'
Similarly, the sentence above will result in true only if the variable 'foo' is equal to 'true', true, 'false' or false. So any other value like 'test' will return false and then it will not run the code inside the 'if' statement. This makes sure that only boolean values (string or not) will be considered.
In the 3rd line, the value of 'foo' is finally "converted" to boolean.
These lines give the following output:
Boolean(1).toString(); // true
Boolean(0).toString(); // false
Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#.
So workaround is
var setActive = 'true';
setActive = setActive == "true";
if(setActive)
// statements
else
// statements.
javascript:var string="false";alert(Boolean(string)?'FAIL':'WIN')
will not work because any non-empty string is true
javascript:var string="false";alert(string!=false.toString()?'FAIL':'WIN')
works because compared with string represenation
See this question for reference:
How can I convert a string to boolean in JavaScript?
There are a few ways:
// Watch case sensitivity!
var boolVal = (string == "true");
or
var boolVal = Boolean("false");
or
String.prototype.bool = function() {
return (/^true$/i).test(this);
};
alert("true".bool());
You can try this:
var myBoolean = Boolean.parse(boolString);

Categories

Resources