+ 2
Let's Discuss About JavaScript "Weird Parts"
Strange ways JavaScript behaves that makes it quite hard to grasp but ultimately makes it a very beautiful and amazing programming language. e.g console.log(1 < 2 < 3) and console.log(3 < 2 < 1) both prints: true Very confusing and weird.....Lol
6 Answers
+ 3
It's because of JavaScript Associativity and Coercion.
Associativity:
How JavaScript reads code upon encountering multiple operators of the same precedence, whether to read: Left-to-Right or Right-to-Left.
For the example above the associativity is Left-to-Right.
e.g
(1 < 2 < 3)
1 and 2 are first compared and the result of the two later compared to 3. So
( 1 < 2 < 3 ) => ( true < 3 )
The result above triggers JavaScript inbuilt weird part, Coercion.
Coercion:
How implicitly JavaScript automatically convert data types. One of the reasons why JavaScript is a dynamically typed language. Just the same "var" word could be used to declare and assigned values of any type ( string, boolean, number, symbol, undefined).
So the result above: ( true < 3 )
JavaScript infers a comparison between a
boolean: true and number: 3 and automatically coerce the boolean: true => 1, before compared to the number. Hence:
( true < 3 ) => ( 1 < 3 )
So the whole process is this:
( 1 < 2 < 3 ) => ( true < 3 ) => ( 1 < 3 ) => true
Also:
( 3 < 2 < 1 ) => ( false < 1 ) => ( 0 < 1 ) => true
That's it! go on share any weird JavaScript behavior.
+ 1
why is it like that
0
can you provide me some best angular Js reference
0
I didn't understand ..
- 1
SGS gvahvshsdhz jwbshshjsbsbzjssbhshhhshfyusb gwgs
- 1
new hello