user994165 user994165 - 1 year ago 77
Javascript Question

JavaScript string comparison fails in Node

I'm comparing two strings. For some reason no matter how I try to compare them, it appears as if they're not equal but they are.

logger.trace("eval Str: "+util.inspect(evalStr));
logger.trace("Is next():" + evalStr == "next()");
logger.trace("Is next():" + evalStr.valueOf() == "next()".valueOf());

2016-10-02T12:10:55.446-04:00 - trace: eval Str: 'next()'
2016-10-02T12:10:55.447-04:00 - trace: false
2016-10-02T12:10:55.448-04:00 - trace: false
2016-10-02T12:10:55.448-04:00 - trace: 6e6578742829
2016-10-02T12:10:55.449-04:00 - trace: 6e6578742829

function toHex(str) {
var hex = '';
for(var i=0;i<str.length;i++) {
hex += ''+str.charCodeAt(i).toString(16);
return hex;

Answer Source

The problem is the + in the trace calls, you're not comparing what you think you're comparing. You want to add explicit () so you're grouping the way you want to group:

logger.trace("Is next():" + (evalStr == "next()"));
// Note --------------------^-------------------^


Your original code:

logger.trace("Is next():" + evalStr == "next()"); evaluated like this:

logger.trace(("Is next():" + evalStr) == "next()");
// Note -----^----------------------^

...which is why you're not seeing Is next(): in the output. "Is next():next()" == "next()" is false, so... :-)

And == or === are the correct way to compare strings in JavaScript. If both operands are strings, it doesn't matter which you use. If either of the operands may or may not be a string, use == if you want the abstract equality conversion rules (which are complicated) or === if you want the comparison to be false when the operands aren't the same type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download