How do you use the ? : (conditional) operator in JavaScript?

前端 未结 18 1610
感动是毒
感动是毒 2020-11-21 05:48

In simple words, what is the ?: (conditional, "ternary") operator and how can I use it?

18条回答
  •  甜味超标
    2020-11-21 05:54

    Ternary Operator

    Commonly we have conditional statements in Javascript.

    Example:

    if (true) {
        console.log(1)
    } 
    else {
        console.log(0)
    }
    # Answer
    # 1
    

    but it contain two or more lines and cannot assign to a variable. Javascript have a solution for this Problem Ternary Operator. Ternary Operator can write in one line and assign to a variable.

    Example:

    var operator = true ? 1 : 0
    console.log(operator)
    # Answer
    # 1
    

    This Ternary operator is Similar in C programming language.

提交回复
热议问题