Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare String and Symbol in Javascript? [duplicate]

I've a String and a Symbol defined in Javascript with same value Hello, Stack Overflow!. How do I compare them for equality? All the comparisons I've tried below return false.

var string="Hello, Stack Overflow!";
var symbol=Symbol("Hello, Stack Overflow!");

console.log(string == symbol);
console.log(string == symbol.toPrimitive);
console.log(string == symbol.toString);
console.log(string == symbol.toStringTag);
console.log(string === symbol);
console.log(string === symbol.toPrimitive);
console.log(string === symbol.toString);
console.log(string === symbol.toStringTag);
like image 396
Beginner Avatar asked Jun 13 '26 04:06

Beginner


1 Answers

You can convert the string to symbol then perform the comparison.

console.log(Symbol(string).toString() == symbol.toString())
like image 131
Mohammed Athar Imran Ahmed Avatar answered Jun 14 '26 17:06

Mohammed Athar Imran Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!