Javascript operator precedence

Javascript operator precedence
0

#1

in YDKJS types and grammar there is this code snippet:

var a = 42;
var b = "foo";
var c = false;

var d = a && b || c ? c || b ? a : c && b : a;

d;		// 42

And the author stated that the correct operation sequence is something like this:

((a && b) || c) ? ((c || b) ? a : (c && b)) : a

I can understand that in JS the operation precedent goes something like this :

&&>|| but what about ? and : ?
do they come together?

For the snippet above I understand the ((a&&b)||c) part. but why ((c || b) ? a : (c && b))

also could someone give me some more example of how to use conditional/ternary operator?
i dont really get how it works…


#2

Given a is a boolean value,

a ? b : c

is roughly equivalent to

if (a) {
  b
} else {
  c
}

I say roughly because a ternary is an expression (it represents a value, and can be written anywhere you want a value), not a statement (which is effectively an action - an if/else block is an example).

So

let a = 100; // assume this value is coming from somewhere else, so could be any number
let b = (a > 10) ? "var a is greater than ten" : "var a is not greater than ten"; 

(b will have a value of "var a is greater than ten")

Which is not quite the same as

let a = 100;
let b;

if (a > 10) {
  b = "var a is greater than ten";
} else {
  b = "var a is not greater than ten";
}

Ternary are imo very useful because they are expressions; there are many situations where you want/need a value (e.g. within JSX when using React) not a statement.


#3

Thing 1: In real life please don’t get this cute with shorthand. Other developers who read your code (including Future You) will be annoyed.
image

Thing 2: The difference with : is that it’s right associative

Thing 3: Without worrying about what I said in Thing 2, translate all of this into longhand and the order will make more sense:

if (a && b || c) {
   if (c || b) {
        d = a;
    }
    else {
        d = c && b;
   }
else {
    d = a;
}

#4

i see. thanks for the warning LOL.
i was simply following YDKJS instruction.

I think I will make my code more readable by not using all those “shortcuts”.

also the meme is on point :smile:


#5

wait you left out one } in your code I think. XD


#6

Quite possibly. I didn’t check it.