Difference between typeof === and typeof == - javascript

What is the difference in using typeof === or typeof == or is same thing?, since both return the same value.
function main() {
var number = 10;
console.log(typeof number == 'number'); // true
console.log(typeof number === 'number'); // true
}
main();

The typeof operator always returns a string. The === compares both the value and the type whereas == operator only compares the value.
This means both the == and === comparators will always act the same when you have typeof and a string on two sides of them.

Prefer using the strict equality comparison === as is a subset of the ==. The latter does type conversations like null and undefined being equal which can be surprising.

=== makes a strict comparison and only returns true if the compared elements have the same value and type
== compares only in terms of values, not type of data

Related

JS: difference between undefined and `undefined`

Looking at this code; why doesn't a satisfy (a === typeof a)
var a;
(a === undefined)?console.log("a is undefined"):null;
(typeof a === 'undefined')?console.log("typeof a is 'undefined'"):null;
According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof typeof always returns a string.
Because:
var a;
typeof a === 'undefined';
a === undefined;
One is a string with the string value 'undefined', one is the undefined primitive. Those two are not the same.
typeof x always returns string values such as "undefined", "boolean", "string", "object", etc....

Why is the following true: "Dog" === ("Cat" && "Dog")

Why does the && operator return the last value (if the statement is true)?
("Dog" == ("Cat" || "Dog")) // false
("Dog" == (false || "Dog")) // true
("Dog" == ("Cat" && "Dog")) // true
("Cat" && true) // true
(false && "Dog") // false
("Cat" && "Dog") // Dog
("Cat" && "Dog" && true) // true
(false && "Dog" && true) // false
("Cat" && "Dog" || false); // Dog
Fiddle
Logical Operators - && (MDN)
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both
operands are true; otherwise, returns false.
For your expression "Cat" && "Dog" , the first expression "Cat" can't be converted to false or a boolean value, hence it returns "Dog"
Think of && in JavaScript like this (based on ToBool from the es5 spec)
function ToBool(x) {
if (x !== undefined)
if (x !== null)
if (x !== false)
if (x !== 0)
if (x === x) // not is NaN
if (x !== '')
return true;
return false;
}
// pseudo-JavaScript
function &&(lhs, rhs) { // lhs && rhs
if (ToBool(lhs)) return rhs;
return lhs;
}
Now you can see that ToBool("Cat") is true so && will give rhs which is "Dog", then === is doing "Dog" === "Dog", which means the line gives true.
For completeness, the || operator can be thought of as
// pseudo-JavaScript
function ||(lhs, rhs) { // lhs || rhs
if (ToBool(lhs)) return lhs;
return rhs;
}
Why does the && operator return the last value?
Because that's what it does. In other languages, the && operator returns the boolean true or false. In Javascript, it returns the first or second operand, which is just as well since those values themselves are "truthy" or "falsey" already.
Hence 'Cat' && 'Dog' results in the value 'Dog', which is equal to 'Dog'.
Because you asked if true === (true && true). If you use a non Boolean in a Boolean operation, javascript will convert to Boolean. Non empty strings are "true" so it returns correct.
I'm guessing the language designers wanted to enable users to use the || operator as a "coalesce" operator, in the style of e.g. the "null coalesce" operator ?? in C#.
In other words, if you want a default value, you can use the following idiom:
var x = input || "default";
//x will be equal to input, unless input is falsey,
//then x will be equal to "default"

Javascript : Seems like typeof doesn't work

I want to set a Value in a javascript object only when it is not set. My (test) function looks like:
var test = function(){
this.value = {};
this.setValue = function(seperator, newValue){
console.log((this.value[seperator] === "undefined")); //Why both times false?
if(typeof(this.value[seperator] === "undefined")){
this.value[seperator] = newValue;
}else{
//noop
}
console.log(this.value[seperator]);
}
}
var blubb = new test();
blubb .setValue("foo","bar");
blubb .setValue("foo","notme");
in the js console it returns
false
bar
false
notme
Can someone tell me why both time my test of "undefined" told me that is not defined?
thanks in advance
Because undefined in JS is not a string, it's a property of global object and you comparing by type using ===.
=== will compare not only values but their types too:
1 === "1" // false
1 == "1" // true
Try this:
console.log(( typeof this.value[seperator] === "undefined"));
typeof operator transforms variable type to string and only then you can check if your variable is equal to string undefined.
In your second piece of code:
if(typeof(this.value[seperator] === "undefined")){
you use typeof operator outside of the variable so your code first checks if this.value[seperator] === "undefined" then it returns false to you and then you check by "typeof false", it will return boolean for you.
In final step your code converts to:
if( "boolean" ){
And this is always true as string is not empty.
Short answer:
"undefined" !== undefined
Check for undefined instead.
> var foo = { foo: 'foo' };
> foo['bar']
undefined
> typeof(foo['bar'])
"undefined"
Also note that typeof(this.value[seperator] === "undefined") means typeof(boolean) as it'd first evaluate your expression (this.value[seperator] === "undefined") and then get the type of that.
You probably meant typeof(this.value[seperator]) === "undefined".
Your brackets are in the wrong place in this line:
if(typeof(this.value[seperator] === "undefined")){
You're doing the typeof of (this.value[seperator] === "undefined") - that's a boolean condition (will return true or false) so I'd expect typeof to give you "boolean". Then your if statements condition is the string "boolean" which, since it's not zero length, is considered true in JavaScript.
What you wanted is:
if((typeof this.value[seperator]) === "undefined") {

How can I check if variable in java script is type of a particular object

How can I check if variable in java script is type of a particular object? What will be the result of this
var myvalue = "200"+50+44;
1) The typeof operator returns a string indicating the type of the unevaluated operand.
2) The result will be 2005044
I think you're trying like this
parseInt("200", 10)+50+44 // returns 294
Check parseInt(string, radix) for more information.
The type can be checked with the typeof operator.
typeof myvalue === "number"
The possible types are "number", "string", "object", "undefined". This has a few problems though.
typeof someArray === "object"
typeof null === "object"
The better way is compare constructors.
someArray.constructor === Array
someNumber.constructor === Number
You do however need to check if it's null or undefined, because neither have a constructor property.
someThing != null && someThing.constructor === SomeConstructor

How can I check if a var is a string in JavaScript?

How can I check if a var is a string in JavaScript?
I've tried this and it doesn't work...
var a_string = "Hello, I'm a string.";
if (a_string typeof 'string') {
// this is a string
}
You were close:
if (typeof a_string === 'string') {
// this is a string
}
On a related note: the above check won't work if a string is created with new String('hello') as the type will be Object instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.
The typeof operator isn't an infix (so the LHS of your example doesn't make sense).
You need to use it like so...
if (typeof a_string == 'string') {
// This is a string.
}
Remember, typeof is an operator, not a function. Despite this, you will see typeof(var) being used a lot in the wild. This makes as much sense as var a = 4 + (1).
Also, you may as well use == (equality comparison operator) since both operands are Strings (typeof always returns a String), JavaScript is defined to perform the same steps had I used === (strict comparison operator).
As Box9 mentions, this won't detect a instantiated String object.
You can detect for that with....
var isString = str instanceof String;
jsFiddle.
...or...
var isString = str.constructor == String;
jsFiddle.
But this won't work in a multi window environment (think iframes).
You can get around this with...
var isString = Object.prototype.toString.call(str) == '[object String]';
jsFiddle.
But again, (as Box9 mentions), you are better off just using the literal String format, e.g. var str = 'I am a string';.
Further Reading.
Combining the previous answers provides these solutions:
if (typeof str == 'string' || str instanceof String)
or
Object.prototype.toString.call(str) == '[object String]'
Following expression returns true:
'qwe'.constructor === String
Following expression returns true:
typeof 'qwe' === 'string'
Following expression returns false (sic!):
typeof new String('qwe') === 'string'
Following expression returns true:
typeof new String('qwe').valueOf() === 'string'
Best and right way (imho):
if (someVariable.constructor === String) {
...
}
Now days I believe it's preferred to use a function form of typeof() so...
if(filename === undefined || typeof(filename) !== "string" || filename === "") {
console.log("no filename aborted.");
return;
}
check for null or undefined in all cases a_string
if (a_string && typeof a_string === 'string') {
// this is a string and it is not null or undefined.
}
My personal approach, which seems to work for all cases, is testing for the presence of members that will all only be present for strings.
function isString(x) {
return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}
See: http://jsfiddle.net/x75uy0o6/
I'd like to know if this method has flaws, but it has served me well for years.

Categories