简体   繁体   中英

How to translate a one-line condition in Javascript

I am currently translating a code I made from Python to Javascript.

I would like to know how I can translate to Javascript an instruction like this:

function(arg1, arg2=True if condition else False)

I can't find this specific case on Google.

Many thanks!

Your are looking for ternary operator , it looks like this:

const condition = true;
function(arg1, condition ? "true" : "false")

The logic behind it:

First argument (before?) is the condition, eg:

const age = 18
age >= 18 ? ....

The second argument (after?) is the True statement and after the : is the False statement

? "Above 18" : "Under 18"

Final result:

const age = 18;
console.log(age >= 18 ? "Above 18" : "Under 18"); // prints "Above 18"

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