javascript check null or empty string [duplicate] - javascript

This question already has answers here:
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
(47 answers)
Closed 4 years ago.
Why is this not possible?
var value = null;
if(value == (null || ""))
{
//do something
}
I would like to check a value if it is null or empty without using the variable over and over again.

Use !value. It works for undefined, null and even '' value:
var value = null;
if(!value)
{
console.log('null value');
}
value = undefined;
if(!value)
{
console.log('undefined value');
}
value = '';
if(!value)
{
console.log('blank value');
}

If we split the condition into its two relevant parts, you first have null || "". The result of that will be equal to the empty string "".
Then you have value == ""., which will be false if value is null.
The correct way to write your condition is value == null || value == "".

Related

Variable returning 'null' instead of null

I have a very basic javascript function where I am splitting the string into two parts. The problem is the second part is 'null' and not null. So if function is not working properly
Please find below code and console.logs.
Why such strange behavior. Thank you in advance
extractCredentials(request: Request): any {
const authHeaderValue = request.headers.authorization;
const parts = authHeaderValue.split(' ');
const encryptedCredentails = parts[1];
console.log(typeof encryptedCredentails) // prints string
console.log(encryptedCredentails) // null
console.log(encryptedCredentails.length) // prints 4
if (encryptedCredentails == 'null') {
console.log('null') // prints null
}
else {
console.log('not null') // not executed
}
if (encryptedCredentails) {
console.log('true') // true
}
else {
console.log('false') // not executed
}
return encryptedCredentails
}
Just parse it like this JSON.parse(encryptedCredentails ) it return you null without ''
var encryptedCredentails = 'null'
console.log(JSON.parse(encryptedCredentails )) //null
console.log(encryptedCredentails ) //"null"
You are splitting on the basis of whitespace " ", so it cannot be "not null" because it will split it also
This condition is checking for a string value of 'null', not the primitive type null.
if (encryptedCredentails == 'null') {
console.log('null') // prints null
}
If you are trying to do a null check on encryptedCredentails then your condition should be one of the following possible options:
If you are only trying to check for null values, and not other null-ish values, then do a 'strict' equality check:
if (encryptedCredentails === null)
If you want to treat undefined 0 etc etc as `null, then use:
if (encryptedCredentails == null)
or
if (!encryptedCredentails)
see similar question on checking for null values here

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

Checking if object not null before accessing property [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
var how = $('how');
var id = $('myId');
if ((how != null && !how.value.blank()) || myId != null) {
return true;
} else {
alert('Error');
}
Is there an easier way to check for not null and checking if the value of that element is blank without having to do both != null and then calling value?
Since null is falsy, a slightly shorter version would be
if((how && !how.value.blank()) || myId != null) {
...
}
Note that the above code and your own snippet both assume that if how exists, it will have a property called value, and will throw an exception if this is not the case.

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.

Why is isNaN("1") false? [duplicate]

This question already has answers here:
Why does isNaN(" ") (string with spaces) equal false?
(25 answers)
Closed 8 years ago.
I'm trying to write a simple test for the input of a function to determine if all of the inputs are numbers or not.
function numbers(){
for (var i = 0; i < arguments.length; i++) {
if (isNaN(arguments[i])) return false;
}
return true;
}
However, when I pass in a list of numbers as characters (eg. numbers("1", "2")) I get true instead of the expected false.
isNaN implicitly coerces the argument to Number, and then checks whether this coerced value is NaN.
See http://es5.github.io/#x15.1.2.4
That is, isNaN(foo) is equivalent to isNaN(Number(foo))
Code fix:
if (typeof arguments[i] !== 'number' || isNaN(arguments[i])) return false;
The second part of the condition is because typeof NaN === 'number'.
Your function might be a bit more readable in functional style, using ES5's Array#every method:
//returns whether all arguments are of type Number and not NaN
function numbers() {
return [].every.call(arguments, function(arg) {
return typeof arg === 'number' && !isNaN(arg);
});
}
isNan() will attempt to cast it to a number, and then check. I would use this instead
if(!isNaN(parseFloat(arguments[i])) && isFinite(arguments[i])){
return false;
}
Alternatively, if you're using jQuery, you could use its built-in $.isNumeric() function

Categories