+ 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

11th Feb 2017, 6:16 PM
Benneth Yankey
Benneth Yankey - avatar
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.
11th Feb 2017, 10:13 PM
Benneth Yankey
Benneth Yankey - avatar
+ 1
why is it like that
11th Feb 2017, 9:42 PM
Elvis Chima
Elvis Chima - avatar
0
can you provide me some best angular Js reference
14th Feb 2017, 6:01 PM
Sandeep Shrestha
Sandeep Shrestha - avatar
0
I didn't understand ..
28th Feb 2017, 7:05 AM
AMAAN WANIE
AMAAN WANIE - avatar
- 1
SGS gvahvshsdhz jwbshshjsbsbzjssbhshhhshfyusb gwgs
13th Feb 2017, 9:57 AM
rohit
- 1
new hello
21st Feb 2017, 3:05 PM
Nerold Abedin
Nerold Abedin - avatar