Checking for null in JavaScript works except for zero - javascript

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

Related

Javascript - How to convert string '0' to number 0

I'm trying to do error handling on 2 input values. I'm using regex to confirm that the input is always a number. The issue I'm having is that I don't want my error handling to kick in if the user literally inputs 0. Right now I'm using:
number = parseInt(incomingValue) || ""
to set my variable. The issue is that this turns '0' into ""
Its fine if an empty value becomes an empty string because I am disabling my error checking when the lengths are equal to 0, but I need to properly turn '0' into a number 0. Anyone have any ideas?
Additionally, I'd also like to turn '000' (and so forth) into a number 0
You can turn '0' or '000' into a number by just doing:
parseInt('0'); // 0
parseInt('000'); // 0
The reason your code is not working is that javascript treats 0 as a falsly value, so when you do this:
const number = parseInt('0') || ""
the expression parseInt('0') will return 0 which is falsy. As a result, the || "" will be executed which will set number to "". You'll need to separate your parseInt and your default assignment to achieve what you want.
Use "Number()":
console.log(Number('0'));
console.log(Number('000'));
console.log(typeof(Number('0')));
console.log(typeof(Number('000')));
Or put "+" before '0' and '000':
console.log(+'0');
console.log(+'000');
console.log(typeof(+'0'));
console.log(typeof(+'000'));
Or put "* 1" before or after '0' and '000':
console.log('0' * 1);
console.log('000' * 1);
console.log(typeof('0' * 1));
console.log(typeof('000' * 1));
You can use parseInt(incomingValue) to get the int value.
For comparing you can use === for equal value and equal type means (incomingValue === 0) will be true in case of incomingValue = 0.
You can try typeof to distinguish what type of variable you are receiving
typeof true === 'boolean'
typeof null === 'object'
typeof 62 === 'number'
typeof 'Hello World' === 'string'

Javascript, string concatenation without ternary operator

Usually I use this:
myVar = "myString is" + 1 === 1 ? " really true" : " false, I think";
Maybe I need just the true part, let's say:
myVar = "myString is" + 1 === 1 ? " really true" : "";
I don't like this part: : "" because is useless.
Is there a way to use something like the below?
myVar = "myString is" + 1 === 1 && " really true";
It works but there is a problem when is false because it writes "false"!
You could always go with a good old if statement
var myVar = 'myString is';
if (1===1){myVar+=' really true';}
I think that makes it more readable than a one line boolean test
To be pragmatic the best pattern and best way to write this is to rely on a helper:
myVar = "my string is"+myHelper(...myParams);
Then in the helper we'll have a case/switch that is made exactly with this purpose and is really readable.
You can just use ||
myVar = (1 === 1 && "myString is really true") || "";
Wrap the 1 === 1 && " really true" inside parentheses () and add || '' like below (also wrapped in parentheses), or could use template literals to save you some time from typing those +s
let myString = "myString is" + ((1 === 1 && " really true") || '');
let myFalseString = "myString is" + ((1 === 0 && " really true") || '');
let onlyFalse = "myString is" + 1 === 1 && " really true";
let myTL = `myString is ${(1 === 1 && "really true") || ''}`;
console.log('My String:', myString);
console.log('False String:', myFalseString);
console.log('Only false:', onlyFalse);
console.log('My Template Literal:', myTL);
Looks much worse than having the extra : "" though so I would still recommend doing it like that:
myVar = "myString is" + 1 === 1 ? " really true" : "";
another way to achieve something like this could be to use an Array, and concat the values if they are not false. Not that it is any shorter than adding the : '', but as far as i know there is no way to get rid of the : ''
console.log( ["my string is", 1 === 1 && "really true"].filter(Boolean).join(" ") );
console.log( ["my string is", 1 === 2 && "really true"].filter(Boolean).join(" ") );
i would prob stick with the : '' or write a helper function that could look something like this.
function concat(){
let str = "";
for(let s of arguments){
str += s ? s : '';
}
return str;
}
console.log( concat("my string is", 1 === 1 && "really true") );
console.log( concat("my string is", 1 === 2 && "really true") );
Analysing the ternary operator we conclude that it's something like this:
// Example: 1 === 1 ? ' is really true' : ''
if (1 === 1) {
return ' is really true';
} else {
return '';
}
So the solution would be simply to remove the 'else' from the ternary operator, generating a 'binary'. Use a lone IF:
if (1 === 1) {
myVar += 'is really true';
}
The best solution to use the logic operator inline is the ternary operator itself. It's not a problem to have the 'false' part of it as a empty string "". But if you're really annoyed by it you could create a function and use the template literals like this:
function myFunction(evaluation) {
if (evaluation) {
return ' really true';
}
return '';
}
let myVar = `My String is ${myFunction(1 === 1)}`;

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.

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 != ''
:)

If/Else Statement Returning false positives

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!

Categories

Resources