If/Else Statement Returning false positives - javascript

In my code, I have this if/else statement to deal with a situation in which the numbers and letters both return cont = false. I have tried running just this code, with the same result. Obviously, it should execute the code in the else statement. Does anyone have any ideas?
var input = prompt()
if (input == null || " ") {
//Cont determines whether or not to continue
console.log("cont = false");
var cont = false;
}else{
console.log("cont = true");
var cont = true;
}

Because that code is not how you check one input against two values.
if ( input == null || " " )
should be
if (input==null || input == " ")

input == null || " "
evaluates to (result of your comparison) || " ". Now since " " (a non-empty string) is a truthy value this always evaluates to true.
For order of evaluation -
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Adding to the other replies which are all correct about the || operator and precedence.
Using == is not a good thing to do in most cases, not least because 0 == null etc - if you're checking if it's actually null or an empty string then something like this is safer:
if (input === null || input.trim() === "") {
...
This checks type as well as content, so won't be able to give false positives. though if input isn't a string it will complain.

Thank's so much! As a summary of all of the answers recieved so far:
The OR operator (||) is comparing input == null to " ", the latter of which always evaluates to true
=== is better than ==
Thanks again for all the help and support!

Related

Dynamically constructed if statement in one string variable

I am blacking out over issue and I am convinced I am thinking too complex about this, but summarized, my issue is about this:
// imagine this variable is dynamically filled by a loop with conditions inside
var condition = varA + " == " + varB + " && " + varC + " == " + varD;
if (condition) {
// something
}
So it doesn't check whether varA equals varB and varC equals varD as what I intended, but instead it just sees it as a string and that appears to be always true anyway. I don't want, I want to see it actually checking whether varA equals varB etc.
Is there a way to parse this statement into something that actually can be a 'legit' if condition?
Thanks!
I think I understand what your trying to do. You are trying to look at a number of comparisons and determine, in the end, if all comparisons were truly true.
In this case you can actually just keep building your condition out as in the following:
var a = 1, b = 1, c = 3, d = 3, e = 5, f = 6;
var condition = a === b; // condition is true
condition = condition && c === d; // condition is still true
condition = condition && e === f; // condition is now and forever false
why not just do
if(varA == varB && varC ==varD){
//do something
}
edit
maybe try using safe-eval. its a third party package but APPEARS to be an improvement on eval.
The issue with your condition variable is that it's not checking for equality between your variables. The whole condition variable is being read as a string because it sees the == and && as strings and ends up concatenating them together.
I suggest writing your if statement like so:
if (varA === varB && varB === varC && varC === varD) {
// do something
}
That way, you're checking if varA is equal to varB and varB is equal to varC, etc. Using the triple equals also ensures that the variables are of the type value type (i.e. string, boolean, number). Hope this helps.

Checking for null in JavaScript works except for zero

I'm using the following syntax to ensure that my input parameters aren't null.
function hazaa(shazoo){
shazoo = shazoo || " ";
}
It works for everything I tested for except the zero.
null -> " "
"beep" -> "beep"
4 -> 4
but...
0 -> " "
I'm guessing that the zero is regarded as null or false, hence creating the gotcha. What's the syntax to get it right, so that zero is zero?
If it makes the issue considerably simpler to suggest a syntax, we can assume that the input is going to be a char, string, number or null.
I'm using the following syntax to ensure that my input parameters aren't null.
If all you are trying to do is to use " " only if the input is null, then use ternary operator, like this
shazoo = shazoo === null ? " " : shazoo;
This answer lists the values which are considered as Falsy in JavaScript. The table shows that zeroes are considered as Falsy. That is why shazoo || " " is evaluated to be " ", when shazoo is zero.
In my opinion, this is one of the few places where you don't want to do a typesafe comparison.
In such places you want to threat undefined the same way as null; and you don't want to write it every time.
//so better use this
shazoo = shazoo == null ? " " : shazoo;
//than this
shazoo = shazoo === null || shazoo === undefined ? " " : shazoo;
I'm guessing that the zero is regarded as null or false
Yes 0 is treated as false.
What's the syntax to get it right, so that zero is zero?
You can try to use
shazoo = shazoo === null ? " " : shazoo;
You can us === operator and the best way would be
if (shazoo === null)
shazoo = " ";
No need to use else
shazoo = shazoo //no sense
Use the following:
if (shazoo === null){
...
}else{
...
}
New notation
You can also in ES6 use the default argument notation that will default if undefined is passed for that argument.
function foo(shazoo = "default"){
console.log(shazoo);
}
foo(); // "default"
foo(undefined); // "default"
var bar; //
foo(bar); // "default"
foo("my string"); // "my string"
foo(null); // null
It does not handle null
Boolean(0) outputs false, so it took second option ""
you can try (check this fiddle)
function hazaa(shazoo){
return shazoo == null ? " " : shazoo;
}
hazaa(0); //output 0

null escaped in nodejs

I console.log("var = " + JSON.stringify(result.something));
I got var = null
but when I do
if(result.something !=null || result.something != ''){
console.log('enter')
}
it print enter also. I wonder why is that happening, I also tried result.something != 'null', it still go into the if statement.
Your variable is null, here's why:
1. (result.something !=null) : returns false
2. (result.something != '') : returns true
Since you've used an OR operator, program control is going to go inside the if block if either of the condition is true.
As your 2nd condition is evaluating to be true, it's going inside of the if block.
From javascript MDN:
null : "an empty value" i.e no object value present
null value is different from an empty string. So something like if(null ==== " ") will return false
your if statement always true because
the result.something is null AND it is not an empty string null != ''
:)

C# String.IsNullOrEmpty Javascript equivalent

I want to try to do string call equivalent to the C# String.IsNullOrEmpty(string) in javascript. I looked online assuming that there was a simple call to make, but I could not find one.
For now I am using a if(string === "" || string === null) statement to cover it, but I would rather use a predefined method (I keep getting some instances that slip by for some reason)
What is the closest javascript (or jquery if then have one) call that would be equal?
You're overthinking. Null and empty string are both falsey values in JavaScript.
if(!theString) {
alert("the string is null or empty");
}
Falsey:
false
null
undefined
The empty string ''
The number 0
The number NaN
If, for whatever reason, you wanted to test only null and empty, you could do:
function isNullOrEmpty( s )
{
return ( s == null || s === "" );
}
Note: This will also catch undefined as #Raynos mentioned in the comments.
if (!string) {
// is emtpy
}
What is the best way to test for an empty string with jquery-out-of-the-box?
If you know that string is not numeric, this will work:
if (!string) {
.
.
.
You can create one Utility method which can be reused in many places such as:
function isNullOrEmpty(str){
var returnValue = false;
if ( !str
|| str == null
|| str === 'null'
|| str === ''
|| str === '{}'
|| str === 'undefined'
|| str.length === 0 ) {
returnValue = true;
}
return returnValue;
}
you can just do
if(!string)
{
//...
}
This will check string for undefined, null, and empty string.
To be clear, if(!theString){//...} where theString is an undeclared variable will throw an undefined error, not find it true. On the other hand if you have: if(!window.theString){//...} or var theString; if(!theString){//...} it will work as expected. In the case where a variable may not be declared (as opposed to being a property or simply not set), you need to use: if(typeof theString === 'undefined'){//...}
My preference is to create a prototype function that wraps it up for you.
Since the answer that is marked as correct contains a small error, here is my best try at coming up with a solution. I have two options, one that takes a string, the other takes a string or a number, since I assume many people are mixing strings and numbers in javascript.
Steps:
-If the object is null it is a null or empty string.
-If the type is not string (or number) it's string value is null or empty. NOTE: we might throw an exception here as well, depending on preferences.
-If the trimmed string value has a length that is small than 1 it is null or empty.
var stringIsNullOrEmpty = function(theString)
{
return theString == null || typeof theString != "string" || theString.trim().length < 1;
}
var stringableIsNullOrEmpty = function(theString)
{
if(theString == null) return true;
var type = typeof theString;
if(type != "string" && type != "number") return true;
return theString.toString().trim().length < 1;
}
you can say it by logic
Let say you have a variable name a strVal, to check if is null or empty
if (typeof (strVal) == 'string' && strVal.length > 0)
{
// is has a value and it is not null :)
}
else
{
//it is null or empty :(
}

'' equals false in Javascript? What would be the safest way to distinguish between '' and boolean false?

We use an external API whcih returns '' or boolean false while Javascript seems to find the both equal.
for example:
var x = '';
if (!x) {
alert(x); // the alert box is shown - empty
}
if (x=='') {
alert(x); // the alert box is shown here too - empty
}
var z = false;
if (!z) {
alert(z); // the alert box is shown - displays 'false'
}
if (z=='') {
alert(z); // the alert box is shown here too - displays 'false'
}
How can we distinguish between the two?
Use the triple equal
if (x===false) //false as expected
if (z==='') //false as expected
A double equal will do type casting, while triple equal will not. So:
0 == "0" //true
0 === "0" //false, since the first is an int, and the second is a string
var typeX = typeof(x);
var typeZ = typeof(z);
if (typeX == 'string' && x == '')
else if (typeX == 'boolean' && !typeX)
I like Peirix's answer too, but here is an alternative.
as mentioned by peirix: tripple equal signs check both the value and the type
1 == '1' // true
1 === '1' // false
For avoid this questions use jslint validator. It helps for find unsafe operations.

Categories

Resources