Check null database value - javascript

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?

Related

JavaScript check for value including 0

In javascript I need to check for a value in an if statement if it exists. The thing is 0 can be one of the accepted values. so when I do
if(!val) {
return true
}
return false
The thing is Javascript evaluates !0 = false
here are test cases what I want:
val = 0 // true
val = 91 // true
val = null // false
val = undefined = false
Basically check check for null but include 0. Not sure how to do this :/
For type check you have:
typeOf:
// note: typeof [] = object and typeof {} = object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
Array.isArray():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
isNaN()/Number.isNaN():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
Is one of those what you're looking for?
!0 = true // in js. just tried it on MDN
Check for undefined and null:
function isValNumber(val) {
if (val === undefined || val === null) {
return false
}
return true
}
console.log(isValNumber(0))
console.log(isValNumber(91))
console.log(isValNumber(null))
console.log(isValNumber(undefined))
I think you need to be checking for null & undefined in your conditional statement. That way, anything that is 0 or greater will return true. You also need to check the typeOf() for undefined because you undefined is not the value of the variable.
if (typeof(val) != 'undefined' && val != null && !(val < 0)){
return true;
}else{
return false;
}
0 is falsy so !0 is true in JavaScript, but to meet your test cases I think you want truthy values to return true, and you need to handle the special case for 0. One way to do it:
function test(val) {
if (val || val === 0) {
return true
}
return false
}
console.log(test(0));
console.log(test(91));
console.log(test(null));
console.log(test(undefined));
You could also leverage Javascript's weak equivalence operator and use != null which covers null and undefined as below:
function test(val) {
if (val != null) {
return true
}
return false
}
console.log(test(0));
console.log(test(91));
console.log(test(null));
console.log(test(undefined));

Comparion True If Null Or Empty String

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) {
}

how to check falsy with undefined or null?

undefined and null are falsy in javascript but,
var n = null;
if(n===false){
console.log('null');
} else{
console.log('has value');
}
but it returns 'has value' when tried in console, why not 'null' ?
To solve your problem:
You can use not operator(!):
var n = null;
if(!n){ //if n is undefined, null or false
console.log('null');
} else{
console.log('has value');
}
// logs null
To answer your question:
It is considered falsy or truthy for Boolean. So if you use like this:
var n = Boolean(null);
if(n===false){
console.log('null');
} else{
console.log('has value');
}
//you'll be logged null
You can check for falsy values using
var n = null;
if (!n) {
console.log('null');
} else {
console.log('has value');
}
Demo: Fiddle
Or check for truthiness like
var n = null;
if (n) { //true if n is truthy
console.log('has value');
} else {
console.log('null');
}
Demo: Fiddle
A value being "falsy" means that the result of converting it to a Boolean is false:
Boolean(null) // false
Boolean(undefined) // false
// but
Boolean("0") // true
This is very different from comparing it against a Boolean:
null == false // not equal, null == true is not equal either
undefined == false // not equal, undefined == true is not equal either
// but
"0" == true // not equal, however, `"0" == false` is equal
Since you are using strict comparison, the case is even simpler: the strict equality comparison operator returns false if operands are not of the same data type. null is of type Null and false is of type Boolean.
But even if you used loose comparison, the abstract equality algorithm defines that only null and undefined are equal to each other.
Depending on what exactly you want to test for, you have a couple of options:
if (!value) // true for all falsy values
if (value == null) // true for null and undefined
if (value === null) // true for null
In general you should always prefer strict comparison because JS' type conversion rules can be surprising. One of the exceptions is comparing a value against null, since loose comparison also catches undefined.
=== checks for identity - the exact same type and value. So null !== false firstly because they are not the same type, thus will not match when using ===.
If you just want to check for any falsey value, then check with:
if (!n)
If you want to specifically check for null, then check for null like this:
if (n === null)

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.

javascript typeof item === "undefined" never returns true

In the following code sample, typeof item === "undefined" never returns true. i am trying to get an attribute from XML, if the attribute is not there in the XML it returns "undefined", but i am not able to capture whether it has returned undefined or not, firebug shows "typeof item" as an "object"
var item;
var itemIDs = {};
if (items.status == 200)
{
var rows = items.responseXML.getElementsByTagName('z:row');
for(i=0;i<rows.length;i++)
{
//rows[i].attr(attribute);
item = rows[i].getAttribute(attribute);
if(typeof item === "undefined")
{
continue;
}
else
{
item = item.match(/[^\d+;#][\w\W]+/);
itemIDs[item] = 1 ;
}
}
}
else
{
alert('There was an error: ' + items.statusText);
}
return itemIDs;
Edit: I changed the condition to if(item == undefined), The code now works as expected now
Edit2: Double checked it, item variable was never null , it was "undefined"
getAttribute returns an object (valid object or a null object). So the check (typeof item === "undefined") is not correct. It should be (item === null).
Some browser's implementation of getAttribute may return an empty string if the attribute doesn't exist. You could test for both null and "", or alternatively use hasAttribute.
if(rows[i].hasAttribute(attribute))
{
// do stuff...
}
https://developer.mozilla.org/en/DOM/element.getAttribute
It's because typeof null === 'object' (contrary to the common sense). You should check if getAttrbiute's return value equals null.
item = rows[i].getAttribute(attribute);
if (item == null) { /* ... */ }
typeof null is "object"... this is what getAttribute seems to return when the attribute is missing. See documentation of element.getAttribute, specifically the notes section. It is suggested that you can use hasAttribute.
try this:
if (!item)
{
continue;
}
else
{
item = item.match(/[^\d+;#][\w\W]+/);
itemIDs[item] = 1 ;
}
this proofs if the item is null or undefined. is this true, it continues the loop.
getAttribute : return type object
you should compare return value to null

Categories