I am trying to write ANTLR grammar for reading JavaScript arithmetic operations.
Specifically, I want to support boolean values in arithmetic operations such as 0 + true = 1 and 0 + false = 0.
I have the following right now:
BOOLEAN: 'true'
| 'false';
How can I make 1 also mean "true", and "0" also mean false?
How to allow boolean values in arithmetic operations
By making BOOLEAN one possible alternative for your expression rule. In fact, this will already be the case if you wrote your grammar the normal way. Something like 0 + true is syntactically valid in virtually any language that supports infix operators (it'd be a type error in many languages, but still syntactically valid).
How can I make 1 also mean "true", and "0" also mean false?
By treating it as such in your type checking, code generation and/or evaluation code. The grammar doesn't specify what things mean - only what is and isn't syntactically valid and what the resulting parse tree will look like.
I have some old code that doesn't have any comments that is using javascript differently then how I've ever used it. The following is doing math on strings.
if ((toFind > nextOptionText) && (toFind < lookAheadOptionText))
I've found questions like this one - that basically states that "a" < "b":
how exactly do Javascript numeric comparison operators handle strings?
However in my example I have some special characters that it is comparing against. In my code the parameters from above are:
if (("A" > "+") && ("A" < ">EINFUHRUNG ZUM"))
This is equaling TRUE - For me in my case I need it to equal FALSE, but I'm not asking how to make it false, I really just want to understand what the developer that wrote this code was thinking and how does the above if statement work.
Obviously I'm also dealing with a foreign language (German) - I'm pretty sure that this code was written prior to the application becoming multi-lingual.
If there is other suggestions that I should look into, please let me know (i.e. like using the locale or doing a different type of comparison).
My quick test shows that this code evaluates to FALSE, as expected.
if (("A" > "+") && ("A" < ">EINFUHRUNG ZUM")) {
alert('true')
} else {
alert( 'false')
}
In general, the comparison is done as usual according to the character codes, therefore "A" > ">" and "A" > "+".
To compare strings with non-ASCII letters, you might find this reference useful.
This question already has answers here:
Object.is vs ===
(6 answers)
Closed 5 years ago.
We know what the difference between == and === is - basically, === prevents Javascript engine to convert one of the parameter for making both parameters of the same type. But now, in ES6, came a new operator - Object.is which is a bit confusing (or maybe === is now confusing..)
From Mozila website (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) we can see the difference:
Sameness Comparisons:
x y == === Object.is
+0 -0 true true false
NaN NaN false false true
So, for me, looks like Object.is is even more strict in comparing parameters, if so, question raises - how unstrict was === (called "Strict Equality") :)
From the article you linked:
When to use Object.is versus triple equals
Aside from the way it treats NaN, generally, the only time Object.is's special behavior towards zeros is likely to be of interest is in the pursuit of certain meta-programming schemes, especially regarding property descriptors when it is desirable for your work to mirror some of the characteristics of Object.defineProperty. If your use case does not require this, it is suggested to avoid Object.is and use === instead. Even if your requirements involve having comparisons between two NaN values evaluate to true, generally it is easier to special-case the NaN checks (using the isNaN method available from previous versions of ECMAScript) than it is to work out how surrounding computations might affect the sign of any zeros you encounter in your comparison.
Via MDN:
This is also not the same as being equal according to the === operator. The === operator (and the == operator as well) treats the number values -0 and +0 as equal and treats Number.NaN as not equal to NaN.
I know the rule:
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.
So, if("true") passes but if("true" == true) fails because it is handle like if(NaN == 1).
I was wondering what the rational is behind this when one value is boolean. In other weak typed languages like php, this is handle this differently--if one value is a boolean, the other is converted to a boolean for comparisons (and not covert both to numbers as in javascript).
I'm assuming this choice was made for the == operator on careful consideration. Can anyone provide rational as to why this was the chosen functionality? Is there a common use case that this was chosen to address? I'm betting is wasn't just a mistake.
A remarkably quick response just in from Brendan Eich from the es-discuss#mozilla.org mailing list :
Consider Perl:
$ perl -e 'print 0 == "true";'
1
Ok, poor rationale -- but I created JS in May 1995, in the shadow of AWK, Perl 4, Python 1.2 (IIRC), TCL.
I should have paid more attention to AWK than Perl, given
$ awk 'END {print(0 == "0")}'
1D
$ awk 'END {print(0 == "")}'
0D
In some ways, JS's == operator splits the difference between Perl (where non-numeric strings such as "true" convert to 0) and AWK (where only "0" converts to 0) by converting to NaN. That way, at least, we have
js> 0 == ""
true
js> 0 == "true"
false
But the full truth is not that I was carefully emulating other languages. Rather, some Netscapers working to embed JS (then "Mocha") in a PHP-like server (LiveWire) wanted sloppy conversions, so programmers could match HTTP header strings (server side) or HTML form fields (client side) against, e.g., 404 and the like, without explicit coercion by the programmer.
But it was the 90s, I was in a tearing hurry, these ex-Borland Netscapers were persistent. So, as I said at Strange Loop last year, "I was an idiot! I gave them what they wanted!"
Implicit conversions are my biggest regret in JS's rushed design, bar none. Even including 'with'!
Does anyone know the exact reason the choice was made not to convert to boolean any value compared against a boolean in with the == operator?
The general idea is the narrower type should widen. Thus, true == 1 follows by projecting boolean {false, true} onto {0, 1}, as in C++.
But why not widen true to string, since the other operand in your example is "true"? Good question. The bias toward comparing strings as numbers if either operand is a number or a boolean stems from the HTTP header and numeric-string HTML form field use-cases. Not good reasons, again, but that's how JS "works" :-|.
You can see this in the ECMA-262 Edition 5.1 spec, 11.9.3 The Abstract Equality Comparison Algorithm, steps 6 & 7 (read in light of steps 4 & 5):
4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
This is all in a big "else clause where Type(x) and Type(y) for x == y are not the same.
Sorry there's no pearl (sic) of wisdom here. In addition to implicit conversions, == and != do not widen operands directly (no intermediate conversions) to the narrowest width that can hold the other operand without data loss. This narrowing string to number is just a botch.
If we fixed this botch, we'd still have:
0 == "0"
1 == "1"
true != "1"
false != "0"
But we would also have what your example wants:
true == "true"
false != ""
Per my calling the preference for number over string conversion a botch, we would not have true == "1" or false == "0", because that narrows from string to number. It's true the narrowing loses no bits, and one can widen 0 back to "0" and 1 back to "1", but I meant to illustrate what removing all number-over-string bias from the implicit conversion spec for == would do.
Would such a change break a lot of code on the web? I'd bet large sums it would.
Some take this botch, on top of any implicit conversion under the hood, as another reason to use === and !== always (because they never convert), and to utterly shun == and !=. Others disagree (especially when testing x == null, a one-operator way to test x === null || x === undefined).
Since the web grows mostly-compatibly until very old forms die off, we're stuck with == and !=, so I say it pays to learn what the sloppy equality operators do. Having done that, it seems to me one may use them where they win: when you know the operands are same-type, e.g.
typeof x == "function", etc.
x == null
And otherwise, use === and !==.
The bias toward comparing strings as numbers if either operand is a number or a boolean stems from the HTTP header and numeric-string HTML form field use-cases. Not good reasons, again, but that's how JS "works" :-|.
One more note: it could be argued that narrowing from string to number would be ok (as in, useful most of the time, and not unsafe) if any non-numeric, non-empty string-to-number implicit conversion attempt threw an exception.
Here's where another path-dependent bias in JS's design bit: no try/catch in JS1 or any ECMA-262 standard till ES3.
The lack of exception handling also meant undefined is imputed for missing obj.foo property get where obj has no such property. That is still biting back, perhaps as much as or more than implicit conversions bite ==. It is also the basis of web JS's winning "object detection" pattern, which fairly beats all other versioning schemes I've seen, especially a-priori ones based on explicit numbering and opt-in.
If only I'd taken the time to add an existential operator for object detection, so one could write
function emulateRequestAnimationFrame(...) {...}
if (!window.requestAnimationFrame?)
window.requestAnimationFrame = emulateRequestAnimationFrame;
IOW, if only I'd made window.noSuchProperty throw but window.noSuchProperty? evaluate to truthy or false (details still TBD, see the "fail-fast object destructuring" thread revival, the Nil idea).
I think some clarification is in order. According to the ECMA specification the entire expression for the if statement (the part within the parentheses) is converted to a boolean.
So imagine it like this:
if (ToBoolean("true" == true)) { //false
vs
if (ToBoolean("true")) { //true
I suppose the rational for why the ToBoolean coercion was added to the if expression was to ensure the expression always evaluates safely and correctly.
ToBoolean coerces a single value to a boolean. A comparison does not coerce each value to a boolean, that wouldn't make sense as you get some pretty strange results. It checks for equality, a different operation. As for why one value isn't converted to boolean when the other is one I am not sure, but try the Mozilla ECMA mailing list: https://mail.mozilla.org/listinfo/es-discuss
See:
http://www.ecma-international.org/ecma-262/5.1/#sec-9.2
http://www.ecma-international.org/ecma-262/5.1/#sec-12.5
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.1
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1
Question: does operand order make any difference when evaluating equality or identity in JavaScript?
In code, is (0 == value) faster or more correct than (value == 0)? (Note that this question is equally valid for the identity operator, ===.)
Since both the equality and identity operators are commutative, I don't believe the operand order should make a difference in evaluation performance, unless there's some inherent benefit to the left-side literal in the computation of the equality algorithm itself. The only reason I wonder is that I recently used Google's Closure Compiler to boil down some JavaScript, and noticed that
if (array.length == 0 && typeof length === 'number') {
had been compiled to
if(0 == b.length && "number" === typeof c) {.
In both equality expressions—one loose and one strict—Closure has reversed the order of my operands, placing a Number literal and a String literal on the left–hand sides of their respective expressions.
This made me curious.
I read through the Equality Operators section of the ECMAScript 5.1 Language Specification (section 11.9, pp. 80–82) and found that while the equality algorithms start by examining the left–hand operands first, there's no indication that it's faster or better to use a literal as that operand.
Is there something about ECMAScript's type–checking that makes examination of literals optimal? Could it be some optimization quirk in the Closure compiler? Or perhaps an implementation detail in an older version of ECMAScript's equality algorithm which has been nullified in this newer version of the spec?
A lot of time people code with the variable on the right as a style convention. Main reason it can catch errors with sloppy coding.
The following code is most likely a bug, but the if statement will evaluate to true.
if( n = 1 ) { }
and this will throw an error
if( 1 = n ) { }
http://jsperf.com/lr-equality
I can't really give you an explanation, but you can check the numbers. They seem to be equal (now).