简体   繁体   中英

Converting Ternary Operator to if / else statements

I found a fix for my application, but I copied and pasted the code, which doesn't match with the rest of the code, I want to turn these ternary operators into if/else statements.

const name = persona ? persona.player_name : steamID.getSteamID64();

I tried to do:

const name = persona;
if (name = persona) {
    persona.player_name;
} else {
    steamID.getSteamID64;
}

But it didn't work, any help will be appreciate it thanks!

Just do:

let name = '';
if (persona) {
   name = persona.player_name;
} else {
   name = steamID.getSteamID64();
}

The mistake is, that the ternary operator doesn't check for equality in this example but for undefined , that means that you example will translate to the following:

let name = undefined;
if (persona !== undefined) {
    name = persona.player_name;
} else {
    name = steamID.getSteamID64();
}

It would be written in human language like this: If persona is defined, assign property player_name to the variable named name . If persona is not defined, assign the result of steamID.getSteamID64() to name .

This is possible because just checking if(foo) is a shorthand for if (foo !== undefined) . And the ternary operator is an inline if-condition, so if(foo) can be translated to foo ? then : else foo ? then : else .

You could take a var statement for declaring the value and assign later.

const needs a value and be careful by taking name as variable, becaus this is a short form of the window's name window.name .

var name;

if (persona) name = persona.player_name;
else name = steamID.getSteamID64();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM