Why does var combined = null + "" has a value? - javascript

Probably a very basic question from a confused javascript noob...
Why do
var hasthisvalue = null;
if (hasthisvalue)
print("hasthisvalue hs value");
and
var hasthatvalue = "";
if (hasthatvalue)
print("hasthatvalue has value");
don't print anything, but if I combine these two
var combined = "hasthisvalue" + "hasthatvalue";
if (combined)
print ("combined has value");
it does?
Or more directly:
var combined = null + "";
if (combined)
print ("combined has value");
Why does "combined" has a value if I only add two variables that don't have values? What am I missing?

When you compare them separately, each converts to false in the if check. When you combine them, the null becomes the string "null", so their concatenation is the string "null", which does not convert to false

The first 2 examples are situations where the values are "falsy". These values are equal to false during a loose comparison:
null
undefined
blank string
boolean false
the number 0
NaN
Other values not in this list are "truthy" and are equal to true on a loose comparison.
The third case, you can try in the console. null+'' becomes a string: "null" and is therefore truthy.

Related

Unary + operator in JavaScript applied to ' ' (string with space) [duplicate]

Today when I was doing some experiments with ==, I accidentally found out that "\n\t\r" == 0. How on earth does "\n\t\r" equal to 0, or false?
What I did is:
var txt = "\n"; //new line
txt == 0; //it gives me true
And that really annoy me. So I did more:
var txt = "\r"; //"return"
txt == 0; //true
var txt = "\t"; //"tab"
txt == 0; //true
It does not make sense, at all. How's that happen? And more crazy is this:
//Checking for variable declared or not
var txt ="\n\t\r";
if(txt!=false){
console.log("Variable is declared.");
}else{
console.log("Variable is not declared.");
}
What it gives me is Variable is not declared.
How is it equal to 0, or false???
This behaviour might be surprising but can be explained by having a look at the specification.
We have to look at the what happens when a comparison with the equals operator is performed. The exact algorithm is defined in section 11.9.3.
I built a simple tool to demonstrate which algorithm steps are executed: https://felix-kling.de/js-loose-comparison/
string == integer
The step we have to look at is #5:
5. If Type(x) is String and Type(y) is Number,
return the result of the comparison ToNumber(x) == y.
That means the string "\n" ("\r", "\t") is converted to a number first and then compared against 0.
How is a string converted to a number? This is explained in section 9.3.1. In short, we have:
The MV (mathematical value) of StringNumericLiteral ::: StrWhiteSpace is 0.
where StrWhiteSpace is defined as
StrWhiteSpace :::
StrWhiteSpaceChar StrWhiteSpace_opt
StrWhiteSpaceChar :::
WhiteSpace
LineTerminator
This just means that the numerical value of strings containing white space characters and/or a line terminator is 0.
Which characters are considered as white space characters is defined in section 7.3.
string == boolean
The step we have to look at is #7:
7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
How booleans are converted to numbers is pretty simple: true becomes 1 and false becomes 0.
Afterwards we are comparing a string against a number, which is explained above.
As others have mentioned, strict comparison (===) can be used to avoid this "problem". Actually you should only be using the normal comparison if you know what you are doing and want this behaviour.
Because JavaScript is a loosely typed language, it attempts to type cast your 1st side of the comparison to the other so that they would match each other.
Any string which does not contain a number, becomes 0 when compared to an integer, and becomes true (Except in certain situations), when compared to a Boolean.
Light reading material.
txt is not a Boolean, so it will never be false. It can be undefined though.
var txt ="\n\t\r";
if(txt !== undefined) { //or just: if (txt)
console.log("Variable is declared.");
} else {
console.log("Variable is not declared.");
}
//=> will log: 'Variable is declared.'
By the way, a declared variable may be undefined (e.g. var txt;).
If you do a stricter comparison (without type coercion, using ===), you'll see that
var txt = '\n'; txt === 0; //=> false
var txt = '\r'; txt === 0; //=> false
var txt = '\t'; txt === 0; //=> false
See also
The reason is that "\n\t\r" just as " " are treated as empty strings.
If you use == it will return true but if you use === it will return false.
If you want to test for existence you should use something like
if(typeof strName !== 'undefined') {
/*do something with strName*/
} else {
/*do something without it*/
}
Whenever you use the == operator and try to compare a string to a number, the string will first be converted to a number. Thus: alert("\n\r"==0) becomes: alert(Number("\n\r")==0)
The Number constructure is kind of interesting. It will first strip whitespace then decide if the number is a not a number or not. If NaN, then the result is "NaN". If the string is empty, then the result is 0.
alert(Number()) alerts 0
alert(Number("")) alerts 0
alert(Number(" \n \r \n \t")) alerts 0
alert(Number("blah")) alerts NaN
alert(Number("0xFF")) alerts 255
alert(Number("1E6")) alerts 1000000
To check if the result is NaN use isNaN()
Thus: alert(isNaN("blah")) alerts true
Thus: alert(isNaN("")) alerts false
Thus: alert(isNaN("\n")) alerts false
Thus: alert(isNaN(" ")) alerts false
however do note that NaN will never equal NaN:
var nan=Number("geh");alert(nan==nan); alerts false
Update:
if you want to check if both sides are NaN, then you'd convert both to boolean values first like so:
var nan=Number("geh");alert(!!nan==!!nan); alerts true
or better yet
var nan=Number("geh");
alert(isNaN(nan)&& isNaN(nan));

How to check 2 different types of things using ===?

I want to check whether the value in an input box is equal to a variable. When I use ===, it returns false but when I use ==, it returns true, provided both are equal.
<input id="g1"></input> <button id="b" onclick="myFunction()">Try</button>
function myFunction() {
var d1;
d1 = Math.floor(Math.random()*100)
if( document.getElementById("g1").value == d1) {
document.getElementById("d").innerHTML = "Correct";
}
This happens because JavaScript == can compare numeric strings to numbers whereas === does not.
Similarly the "value" property your using returns a string that you're comparing to an integer. You'll need to use parseInt to convert the value first.
parseInt(document.getElementById("g1").value) === d1
A few things to consider with parseInt:
parseInt returns NaN when you try to convert non-number strings (i.e. converting 'bogus' returns NaN.
It will convert decimals into integers by dropping the decimals. So parseInt('2.1') == 2 // => true.
Honestly, given your use case, it's appropriate to use ==, but I'd add a comment explaining why it's being used.
=== means both value has to be equals but have same type of data in it aswell where == means they only needs to be equal. so for example if d1 is a string holding value 2 and g1 is an integer also holding value 2 using === would not work and will return false as both data is different even though they have same syntax.
<input id="g1"></input> <button id="b" onclick="myFunction()">Try</button>
function myFunction() {
var d1 = 0;
d1 = Math.floor(Math.random()*100)
if( paseint(document.getElementById("g1").value) === d1) {
document.getElementById("d").innerHTML = "Correct";
}
== is the equality operator
=== is an identity operator
For example true==1 is true because true is converted to 1 and then it's compared. However, true===1 is false. This is because it does not do type coercion.
That aside, in your case I think you want to try casting your value to an integer and then compare.
var string5 = '5'
var numb5 = 5
if (string5 == numb5) will return true
if (string5 === numb5) will return false
second variant also compares type, because string is not same type as number it is false.

Checking whether variable is empty in JavaScript?

There is two kind of JavaScript code for investigating empty/full variable:
if(variable == ''){}
if(!variable){}
I tested both of them, and I achieved identical result. Now I want to know, (first) are they equivalent? And (second) which one is more standard for checking empty/full variable?
var variable1 = 'string';
var variable2 = 12;
var variable3 = true;
if(variable1 == ''){alert('empty-one');}
if(variable2 == ''){alert('empty-one');}
if(variable3 == ''){alert('empty-one');}
if(!variable1){alert('empty-two');}
if(!variable2){alert('empty-two');}
if(!variable3){alert('empty-two');}
As you see, there is no alert.
First is not standard, it only works for defined empty string.
Other will work if value is not truthy ( means something meaningful)
e.g var a;
a == '' will give false result
! a will produce true
e.g. var a = null;
a == '', // false
! a // true
var a = false;
a == '' // fase
! a // true
var a = NaN
a == '' // false
! NaN // true
true == 'true' // false, Boolean true is first converted to number and then compared
0 == '' // true, string is first converted to integer and then compared
== uses The Abstract Equality Comparison Algorithm to compare two operands
For more detail visit http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
In javascript null,'',0,NaN,undefined consider falsey in javascript.
In one sense you can check empty both way
But your first code are checking is it ''
and your 2nd condition is checking is your value are one of them (null,'',0,NaN,undefined)
In my view your 2nd condition is better then first as i don't have to check null,'',0,NaN,undefined seperately
No they are not equivalent. In case first it checks whether the value of variable is equal to the empty string('') or not. So case first will be true iff variable's value is ''. But second case will be true for all the values which are falsey i.e. false, 0, '', null, undefined.

What causes isNaN to malfunction? [duplicate]

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 9 years ago.
I'm simply trying to evaluate if an input is a number, and figured isNaN would be the best way to go. However, this causes unreliable results. For instance, using the following method:
function isNumerical(value) {
var isNum = !isNaN(value);
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
on these values:
isNumerical(123)); // => numerical
isNumerical("123")); // => numerical
isNumerical(null)); // => numerical
isNumerical(false)); // => numerical
isNumerical(true)); // => numerical
isNumerical()); // => not numerical
shown in this fiddle: http://jsfiddle.net/4nm7r/1
Why doesn't isNaN always work for me?
isNaN returns true if the value passed is not a number(NaN)(or if it cannot be converted to a number, so, null, true and false will be converted to 0), otherwise it returns false. In your case, you have to remove the ! before the function call!
It is very easy to understand the behaviour of your script. isNaN simply checks if a value can be converted to an int. To do this, you have just to multiply or divide it by 1, or subtract or add 0. In your case, if you do, inside your function, alert(value * 1); you will see that all those passed values will be replaced by a number(0, 1, 123) except for undefined, whose numerical value is NaN.
You can't compare any value to NaN because it will never return false(even NaN === NaN), I think that's because NaN is dynamically generated... But I'm not sure.
Anyway you can fix your code by simply doing this:
function isNumerical(value) {
var isNum = !isNaN(value / 1); //this will force the conversion to NaN or a number
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
Your ternary statement is backward, if !isNaN() returns true you want to say "numerical"
return isNum ? "not numerical" : "<mark>numerical</mark>";
should be:
return isNum ? "<mark>numerical</mark>" : "not numerical";
See updated fiddle:
http://jsfiddle.net/4nm7r/1/
Now that you already fixed the reversed logic pointed out on other answers, use parseFloat to get rid of the false positives for true, false and null:
var isNum = !isNaN(parseFloat(value));
Just keep in mind the following kinds of outputs from parseFloat:
parseFloat("200$"); // 200
parseFloat("200,100"); // 200
parseFloat("200 foo"); // 200
parseFloat("$200"); // NaN
(i.e, if the string starts with a number, parseFloat will extract the first numeric part it can find)
I suggest you use additional checks:
function isNumerical(value) {
var isNum = !isNaN(value) && value !== null && value !== undefined;
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
If you would like treat strings like 123 like not numerical than you should add one more check:
var isNum = !isNaN(value) && value !== null && value !== undefined && (typeof value === 'number');

Understanding underscore's implementation of isNaN

Taken from the underscore.js source:
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
Why did they do it this way? Is the above implementation equivalent to:
_.isNaN = function(obj) {
return obj !== obj;
};
If it is, why the "more complicated" version? If it is not, what are the behavioural differences?
_.isNaN(new Number(NaN)) returns true.
And that's by design.
var n = new Number(NaN);
console.log(_.isNaN(n), n!==n); // logs true, false
The host environment (e.g. web-browser environment) may introduce other values that aren't equal to themselves. The _.isNumber(obj) part makes sure that the input is a Number value, so that _.isNaN only returns true if the NaN value is passed.
If + is given before of any value with no preceding value to + , JavaScript engine will try to convert that variable to Number.If it is valid it will give you the Number else it will return NaN. For example
+ "1" // is equal to integer value 1
+ "a1" // will be NaN because "a1" is not a valid number
In above case
+"a1" != "a1" // true, so this is not a number, one case is satisfied
+"1" == "1" // true, so it is number
Another simple case would be, why the below expression give this output
console.log("Why I am " + typeof + "");
// returns "Why I am number"
Because +"" is 0.
If you want to check whether it is a number or not you could use the below function
function isNumber(a){
/* first method : */ return (+a == a);
/* second method : */ return (+(+a) >= 0);
// And so many other exists
}
Someone correct me if I am wrong somewhere..
I found one case for _.isNaN
It shows different result with the native one if you pass there an object
_.isNaN({}) => false
//but
isNaN({}) => true

Categories

Resources