This is a two part question. And is different than other questions that are based on equality in JavaScript because it deals with a specific warning that is displayed in the IDE "Visual Studio Code" and why that warning message is or is not in error.
I'm getting the following warning message in Visual Studio code:
Operator '===' cannot be applied to types 'number' and => 'string'
on the following line of code:
var x = 23;
var y = "23";
x.valueOf() === y.valueOf() ?
console.log("Types ARE the same")
: console.log("Types ARE NOT the same");
Now this technique definitely works for me and I understand the reason for using a triple equal for this type of thing rather than a double equal. This same code I have learned in several fundamentals courses at codeschool and pluralsight as a way to generate a boolean value based on the type of two different values where the product or returned value is that of either true or false and the technique can come in handy.
MY QUESTIONS:
How is the code above any different from:
x === y ?
console.log("Types ARE the same")
: console.log("Types ARE NOT the same");
in this simple example of comparing two simple values and their types, is there something additional I can do by using the valueOf() method along with it?
Also is Visual Studio Code wrongly generating this warning and if not is there a better way to do this type of check?
Because no matter what method I use above I get the same warning error in Visual Studio Code, but it works fine for me in practice.
Going by what I see from the MDN docs here for String.prototype.valueOf(); and here for Number.prototype.valueOf(); and the code that you have, I must say you already have x and y holding primitive values of string and number. There is no need to do a valueOf() on x and y as they are not of Object type.
You would ideally use String.prototype.valueOf(); on a String Object to get it's primitive value and Number.prototype.valueOf(); to get primitive value of the Number Object which result in string data type and number data type values respectively.
Hence, the warning I suppose. Although I dont have prior experience with visual-studio, but I feel it understands that .valueOf() should be used on an Object type rather than that on a primitive type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With