The use of the ternary operator and the switch keyword


#1

To write the question shortly, are the ternary operator and switch statements only able to be substituted for if ( a === b) statements?


#2

Ternary expressions are directly correlated to if..else if..else.

expression ? outcome if true : expression ? outcome if true : default outcome

Switches are slightly different, and closely compared to if..else if..else, just in a different form.

 switch (expression) {
    case matchesExpression: action branch; break;
    default: action branch when no cases match expression;
}

#3

What I mean is that in switches and ternary operators, so far it seems that they can only be used like if (a === b), but not (a > b).

As you said,

The code of the first case is executed if it matches the expression; which is similar to if (a === b) statements, but can’t work like if (a < b) statements.


#4
case 2:

That would be a direct identity when the switch argument equates to 2. However, we can switch up the expression.

switch (true) {
case x < 2:
case x > 2:
default: // we know that x === 2
}

The key here is to see that we are able to match expressions. The order we match them in is arbitrary, deemed by the scenario.

?

That is the ternary operator.

x ? 1 : 0

That is a ternary expression.

console.log(x ? 1 : 0)

That is a ternary statement.

When all we have is a simple conditional branch, the if..else if..else statement is more than adequate for our needs. I like using ternaries as expressions, not statements, so the last example is a good illustration of that. Instead of having two console.log() statements, we log the outcome of the ternary.

switch on the other hand, apart from being very versatile, is also better organized when there are several branches.


#5

So… it DOES work with switches. But ternary operators can’t use things like > or <? Or can they use them, just like switches?


#6

Also, when would one want to use a ternary operator? It seems to be a very specific type of if statement that is drastically simplified, which could be helpful, but not very useful.


#7

Alright, I tested some code, and thank you very much for your replies.

What I’ve figured so far is:

Ternary statements execute the part after the ternary operator if whatever is in front of the operator has a truthy value. For example, if a variable is defined, then it has a truthy value and it runs. It’s all coming together now; the part between the parentheses ( ) after the if statement is what is checked for truthiness, so whatever you write there is what is written before a ternary operator. Then the code in the block beneath is executed if whatever you wrote is truthy, and that’s what you write before the colon. The code inside the else block in an if…else statement is what is written after the colon.


#8

Here’s a snippet of code I created from that.

let myVar = 1;

myVar > 0 ? console.log('more than 0') : console.log('less than 0');
//prints more than 0

#9

It’s okay to have a statement in the expression but better in my to view to have the expression in the statement.

let myVar = 1;

console.log(myVar > 0 ? 'more than 0' : 'less than or equal to 0');

As in the above, anytime you wish to do some logic within a statement use the expression.

function num_type(x):
    return x % 1 ? 'float' : 'integer';

We can use a ternary anywhere an expression can be used. Recall that an expression will always boil down to a value.

index[expression_that_yields_an_integer]

In the above example we could access an array element with the value yielded by the expression.

Bottom line, use what works for you and what you are comfortable with. In time you will find opportunities to exploit either ternary or switch, but let the scenario dictate, not your personal preference. Each is very useful but need to fit our use case or it is meaningless.


#10

Is that just because you don’t need to log to the console twice?

That could be achieved with an if…else or a switch too, right?

(sorry if you already answered, but)
When would ternary be more useful than if…else or switch other than length?


#11

Is there any time an if…else statement or switch does not use an expression?


#12

Not really when we consider that a number or string is a form of expression.

if (expression) {
    // action code
}

You mentioned earlier that truthy is starting to make more sense. All expressions can be coerced to truthy or falsy.

if ('a') {
    // truthy since it is not an empty string
} else if (-1) {
    // truthy since is non-zero
} else if ([]) {
    // truthy since it is an object
} else if ({}) {
    // truthy since it is an object
} else {
    // nothing truthy so far
}

Bottom line, all conditionals are boolean expressions since they are all coerced to a boolean value.


#13

Continuing on looking at the possible uses of the Ternary Statement, I’ve tested a couple times and it appears that a ternary operator can’t carry out more than one action at a time. For example,

let myVar = 3;
let anotherVariable = 1;

myVar > 0 ? console.log('more than 0') anotherVariable += 1 : console.log('not more than 0') anotherVariable += 1;

When run, it returns an error, because the ternary operator doesn’t expect anything after the first ‘action’ - in this case, removing the code affecting anotherVariable makes the code run, but as it is there, the ternary statement doesn’t work and an error is returned. Meanwhile, an if statement CAN carry out multiple tasks in its block and so can a switch.


#14

Like I said, statements do not rightly belong in a ternary. However, we can use callbacks.

{
function half(x) {
    return x / 2;
}
function double(x) {
    return x * 2;
}
x = 11
console.log((x % 2 ? double : half)(x))
}
// 22

The functions may contain any amount of code, which will be executed according to the outcome.

Note: I’ve enclosed all the code in an anonymous block so it can be pasted straight into the console as a block, and immediately execute.


#15

True. Would creating functions that do things for the ternary be more helpful than just creating the if…else blocks or switches, which already have their blocks to hold as much code as they need? I guess in certain cases using the ternary would also be better formatting if it was really necessary.

Back to the point though, it makes sense. However, I’m a bit confused with the part after the colon -

Why don’t we need to put another (x) after double? Is it implicit that both functions will use (x) as their parameter?


#16

The invocation takes place on the outcome of the ternary.

(x % 2 ? double : half)(x)

will reduce to,

double(x) 

or,

half(x)

Note how the expression is enclosed in parens.

Here is another paste-in block.

{
function half(x) {
    return x / 2;
}
function double(x) {
    return x * 2;
}
function report(x) {
    return `The input value ${x} is ${x % 2 ? 'odd so will be doubled' : 
    'even so will be halved'} to equal ${(x % 2 ? double : half)(x)}`;
}
for (n of [11, 22]) {
    console.log(report(n));
}
}
   The input value 11 is odd so will be doubled to equal 22
   The input value 22 is even so will be halved to equal 11
<- undefined

FYI, I use Chrome’s JavaScript Console even while my browser of normal use is Firefox.

Open a Chrome window, and in the location bar, type,

about:blank

and Enter it. This will give you a blank page with no code behind it other than the user agent style sheet. Bookmark it on your Bookmarks bar for convenient access.

Open a new tab and test your bookmark. Now Ctrl+Shift+J will give you the console with a document portal at top, and a command prompt, >. That’s where to paste my anonymous block, above.

When I’m done my experiment, I just close Chrome. Three steps to instant blank canvas… Click taskbar shortcut to Chrome, click about:blank shortcut, Ctrl+Shift+J and Bob’s your uncle.


#17

Thanks! I always thought about:blank was just some sort of useless blank page, but sometimes blankness is helpful! I’ll be sure to test my code there.
Note to any people reading: on some devices, F12 opens the console.


#18

How are you handling the callback concept? If it’s a bit confusing, that’s normal. It takes some understanding and knowledge of the lay of the land.

By lay of the land we mean the namespace, and our knowledge that those two functions exist. The understanding is of references and passing functions to other functons and letting those functions invoke them on their local variables.

When we yield double in the ternary, it is not a string, but an identifier for a function object in the namespace. The computer satisfies polling of that object by returning an object id to the poller. Now armed with that object id the poller can invoke the function any time it wants.

We can create shortcut variables to otherwise lots of typing and typos…

{
    random = Math.random;
    floor = Math.floor;

    console.log(floor(random() * 6));

    x = Math.PI
    console.log(x % 1 ? random() : floor(random() * x) + x % 1 * 1)
    x = 13
    console.log(x % 1 ? random() : floor(random() * x) + x % 1 * 1)
}

#19

Slightly off-topic, but here’s a great game for bored people. Coded it myself. :stuck_out_tongue:

for (let j = 0; j <= 100; j++) {alert('Click Me! :P');}

#20

So far I haven’t used it yet, but it seems to make sense. So far, here’s what I’ve thought about - if what is in front of the ternary operator (the conditional? Forgot exact term) is truthy, it executes the code before the colon. You can call the function to execute the function. If the conditional evaluates to false, or is falsy, it executes the code after the colon, and you can also call a function there. If I got anything wrong, feel free to correct.