1

Sometimes I need to make sure that a variable is a String. I used to do that by using the operator new String(value).

However, when I do that, the comparison doesn't work. For example:

var dude = new String("dude");
var dude2 = new String("dude");
console.log(dude == dude2); //will print 'false'

How to make string comparison when using the "new String()"?

I'm using JS as in the Google Apps Script

2 Answers 2

1

you can do that:

dude.toString() == dude2.toString()
Sign up to request clarification or add additional context in comments.

1 Comment

That's a good workaround. But still, why can't we compare two variables when we used the new String(value) to define them?
1

This is the reason why 'dude' and 'dude2' are unequal:

var dude = new String("dude");
var dude2 = new String("dude");

console.log(typeof dude)    //object
console.log(typeof dude2)   //object

you can do it like this:

 var dude = String('dude');
 var dude2 = String('dude');
 dude === dude2  //true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.