Comparion True If Null Or Empty String - javascript

I have a value in my app's state that is used to set the value of a form input field. At any given point, this value can be null, undefined, an empty string, or a string.
I then have a function, that tests to see if the prev value of the variable is not equal to the current value:
checkValues(prevValue, curValue) {
if(prevValue != curValue && !curValue) { // do something }
}
The problem is, if prevValue was an empty string, and curValue is null, it always does the thing. This happens sometimes in instances where data was fetched from an API. The value that was initially set to empty string becomes null:
if('' != null) { // it does the thing because they are not the same }
However, I DON'T want to do the thing in this situation. How can I allow '' != null to return false instead of true?

You can use a double pipe operator (||) to force null or undefined values to empty strings:
if ((prevValue || '') != (curValue || '')) {
}
You could make it cleaner by separating those double pipe operations from the if such as:
var left = prevValue || '';
var right = curValue || '';
if (left != right) {
}

Related

Javascript short circuit if statement: How to return true

I am trying to make a function which check the value if null or ""
Here is what I got so far (that is working)
function notnull(values,success,failed){
var count = 0
$.each(values,function(index,val){
console.log(val)
val != "" && val != null ? count++ : count
})
if(count == values.length){
return true;
}else{
console.log('false')
}
}
However If I tried short circuiting the 2nd if statement it returns an error
function notnull(values,success,failed){
var count = 0
$.each(values,function(index,val){
val != "" && val != null ? count++ : count
})(count == values.length) ? return true:console.log('false')
}
the error says
Uncaught SyntaxError: Unexpected token return
Question 1: How can I return true or false in a short circuit version
Question 2: at the code
val != "" && val != null ? count++ : count
How can I omit the else part?
Your second example is a bit messy, but if I understand your function, you want to go through each value and make sure none of them are null, right?
Here is your original, cleaned up a bit:
function notNull(values){
let count = 0;
$.each(values, function (index,val) {
(val != "" && val != null) ? count++ : count
});
return count == values.length; // returns true or false
}
You are basically going through each of the values, counting them up if they aren't null, and returning true if none were null (your count is the same as your array) or false otherwise.
You are using the jQuery equivalent of the vanilla each() function. They function the same way: they'll go through every single entry in an array.
You can't short-circuit each(). Instead, you need to use some() or every(). Those functions are similar, but opposite:
some() - Continues to loop through as long as its callback returns false.
every() - Continues to loop through as long as its callback returns true.
In your case, you want to use every() because you want to go through every element and make sure it is something (in your case, not null):
function notNull(values) {
return values.every((value) => value != "" && value != null);
}
console.log(notNull([1,2,3]));
console.log(notNull([1,null,3]));
Much nicer. This will check each value. As long as they match the condition, it'll keep going and ultimately return true. If if finds one that does match, it'll short circuit there and return false.
As for your second question, how can you leave out the "else" part of this:
val != "" && val != null ? count++ : count
With the ternary operator (?:), you can't. But, you can with the normal boolean operators:
val != "" && val != null && count++;
JavaScript will short-circuit that condition at the first false, so it'll only get to count++ if the other two bits are true.
On your second example, I think you were attempting something like:
condition ? return value : console.log('a')
This would be an invalid syntax. You can only have values inside of a ternary. You could do something like this:
return condition ? value : otherValue;
If you want a return mixed in, you have to do it as two separate things:
!condition && console.log(''); // log if false;
if (condition) return value;
return and throw are both stubborn in this way and always have to be broken out and can't be mixed with other selective operators.

Difference between exclamation equals sign and exlamation 2x equals sign when checking with null

What is the difference between next if statements in javascript when checking with null?
var a = "";
if( a != null ) // one equality sign
....
if( a !== null ) // two equality sign
....
When comparing to null I can't find any difference.
According to http://www.w3schools.com/js/js_comparisons.asp
!= - not equal
!== - not equal value or not equal type
In JavaScript, null has type: object (try yourself executing the following sentence typeof null).
That is, !== will check that a is also object before checking if the reference equals.
Actually you know that === and !== are meant to check that both left and right side of the equality have the same type without implicit conversions involved. For example:
"0" == 0 // true
"0" === 0 // false
Same reasoning works on null checking.
!= checks
negative equality
while !== checks for
negative identity
For example,
var a = "";
a != false; //returns false since "" is equal false
a !== false; //returns true since "" is not same as false
but if you are comparing it with null, then value will be true in both ocassion since "" is neither equal nor identical to null
There is no difference between them when comparing to null.
When we use strict equality (!==) it is obvious because they have different types, but when we use loose equality (!=) it is an important thing to remember about JavaScript language design.
Because of language design there are also some common questions:
How do you check for an empty string in JavaScript?
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
var a = "";
(1) if( a != null ) // one equality sign
Above condition(1) checks value only and not data-type, this will return true.
....
(2) if( a !== null ) // two equality sign
This checks value and data-type both, this will true as well.
To understand it more precisely,
var a = "1";
if( a == 1) {
alert("works and doesn't check data type string");
}
if( a === 1) {
alert('doesn't works because "1" is string');
}
if( a === "1") {
alert('works because "1" is string');
}
There is a difference if variable has value undefined:
var a = undefined;
if( a != null ) // doesn't pass
console.log("ok");
if( a !== null ) // passes
console.log("ok");
Got idea from reading this great post Why ==null, Not ===null. Also != is faster.

Check null database value

Below is the object returned from backend:
[Object]0: Object Option_Name_0: null Option_Name_1: "me" Option_Name_2: "you" Option_Name_3: "get" Option_Name_4: "no"__proto__: Objectlength: 1__proto__: Array[0]
I am just trying to populate the values into dropdown menu, by removing "null" value.
$.each(e, function(i) {
$.each(e[i], function(key, val) {
if (val != 'null') {
$(".flash_bet_win").append("<option value=" + val + ">" + val + "</option>");
}
});
});
But still I see "null" value in dropdown menu. How to fix this?
Check for null not "null",
if(val !== null)
{
$(".flash_bet_win").append("<option value="+val+">"+val+"</option>");
}
go for a deep comparison (!==) not (!=) as undefined == null would result in truthy value whereas undefined === null would be false
In case you want to check if the value is not null, not undefined or not empty use,
if(val){
...... //your code
}
In your if statement, you're checking that that it's not equal to string 'null', when you want to check if it's equal to the value null
if(val != null)
Or, even shorter:
if(val)
Does this do the trick?

How do i compare against an empty variable?

If I set a variable to 0, I get the weird behavior that a comparison to "" (empty) is true. How do I check that the variable is really empty?
tmp = 0;
if ( tmp != "")
{
//do something - This is where the code goes.
}
else
{
//isEmpty - I would expect to be here
}
Use strict comparison operators
=== and !==
With == and != (called abstract comparison operators),
If the two operands are not of the same type, JavaScript attempts to
convert the operands to an appropriate type for the comparison.
If by empty, you want to check if the variable hasn't been defined, use:
if (typeof tmp !== "undefined") {
// it exists!
}
What do you mean by empty variable? If you mean an empty string, then you should use !== to check it.
if (tmp !== "")
JavaScript implicitly converts values to other types. To check type also, use the !== operator:
if ( tmp !== "")
In JavaScript everything except 0, NaN, undefined, false and null are considered to be false. "" is considered as true.
if (tmp) {
}
Above if will be executed if variable contains any value other than 0, NaN, undefined, false and null.
If tmp is a string then you can use the following code:
if (tmp !== "") {
}
=== and !== operators compare without doing type-conversion.

getAttribute('value') when value=""

I am using Y.one(selector).getAttribute('value'); to return the value on a page and I am having trouble dealing with cases where value="".
var check_value = Y.one(selector).getAttribute('value');
if (check_value != undefined || check_value != null || check_value != "") {
alert(check_value);
}
With all of these checks I am getting an empty alert box when the value of the element I am looking at is "". In this case since I know the value I am looking for is a number I can change the check to just look for a number > 0 and have it work but I was wondering if anyone knew of a method to check for no value for cases where I was not dealing with numeric data.
if (check_value >0) {
alert(check_value);
}
This method does work in my case.
Why don't you just check for 'truthiness' instead?
if (check_value) {
alert(check_value);
}
It's basically the same as your (intended) check, I suppose. And if you need to check for 0 (a Number), just use this:
if (check_value || check_value === 0) {
...
}
If it is an empty string, then it isn't undefined and it isn't null. Since you check if it is not undefined or not null or not an empty string, then it will pass.
Use && not ||
You might look at Y.Lang.isValue()
http://yuilibrary.com/yui/docs/api/classes/Lang.html#method_isValue
Look at the logic in plain english check_value != undefined || check_value != null || check_value != "" if it's undefined or null or "", if it's null it's not undefined, if it's blank it's not null, so everything gets through; you're looking for a logical AND instead of OR
try this:
var check_value = Y.one(selector).getAttribute('value');
if (check_value != undefined && check_value != null && check_value != "") {
alert(check_value);
}
You're seeing the alert because your if statement has OR (||) clauses. In the case that the value attribute is an empty string, the last condition (check_value != "") should fail. However, since "" is not equal to undefined the first condition has already returned true, the if statements test passes (it won't evaluate the other conditions because it doesn't need to) and the if block is executed.
I suspect you actually wanted to use AND (&&) instead.

Categories