metzz
metzz

Reputation: 41

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!

Upvotes: 0

Views: 720

Answers (3)

SteapStepper69
SteapStepper69

Reputation: 1295

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.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386620

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();

Upvotes: 0

Jeremy Harris
Jeremy Harris

Reputation: 24549

Just do:

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

Upvotes: 1

Related Questions