Computer Science

Javascript Ternary Operator

The Javascript Ternary Operator is a shorthand way of writing an if-else statement. It consists of three operands: a condition, a value to return if the condition is true, and a value to return if the condition is false. It is often used to simplify code and make it more readable.

Written by Perlego with AI-assistance

4 Key excerpts on "Javascript Ternary Operator"

  • Book cover image for: JavaScript All-in-One For Dummies
    • Chris Minnick(Author)
    • 2023(Publication Date)
    • For Dummies
      (Publisher)
    To use the conditional operator, write a condition followed by a question mark. After the question mark comes the expression that will run if the condition is true. Follow that expression with a colon and then the expression to run if the condition is false: Controlling Flow CHAPTER 5 Controlling Flow 93 const dt = Date(); const hours = dt.getHours(); let msg; msg = hours < 12 ? ('Good morning!') : ('Welcome'); console.log(msg); Assuming that the timeOfDay variable uses the 24-hour clock, the preceding example returns 'Good morning!' before noon and a generic greeting otherwise. You can try out this code by typing or pasting it into your JavaScript console. All the code from this book is also available for download from the book’s website. Note that the ternary operator can only be used to switch between two choices. If your code needs to decide between more than two outcomes, use the if ... else statements or the switch statement, which you can read about in the next section. Switch statements The switch statement decides which statement to run based on the result of a single expression. Each possible outcome of a switch statement is called a case. Here’s the syntax for the switch statement: switch(expression){ case x: // code to run when expression === x break; case y: // code to run when expression === y break; default: // code to run if nothing else matches expression } In Listing 5-1, I’ve created a new program that displays a different holiday based on the current month of the year. In addition to showing how the switch state- ment works, this example demonstrates how to use JavaScript to display text in a web browser. To try it out, use VS Code to save it as a .html file and then open it in a web browser. You can right-click the filename in the VS Code Explorer pane and select Open in Live Server to view it in a browser.
  • Book cover image for: Pro Angular
    eBook - PDF
    • Adam Freeman(Author)
    • 2017(Publication Date)
    • Apress
      (Publisher)
    You just express the value you require, and JavaScript will act accordingly. In the listing, I have defined an integer value, defined a floating-point value, and prefixed a value with 0x to denote a hexadecimal value. Using JavaScript Operators JavaScript defines a largely standard set of operators. I’ve summarized the most useful in Table 5-3 . Using Conditional Statements Many of the JavaScript operators are used in conjunction with conditional statements. In this book, I tend to use the if/else and switch statements. Listing 5-22 shows the use of both, which will be familiar if you have worked with pretty much any programming language. Table 5-3. Useful JavaScript Operators Operator Description ++, --Pre- or post-increment and decrement +, -, *, /, % Addition, subtraction, multiplication, division, remainder <, <=, >, >= Less than, less than or equal to, more than, more than or equal to ==, != Equality and inequality tests ===, !== Identity and nonidentity tests &&, || Logical AND and OR ( || is used to coalesce null values) = Assignment + String concatenation ?: Three operand conditional statement CHAPTER 5 ■ JAVASCRIPT AND TYPESCRIPT: PART 1 80 Listing 5-22. Using the if/else and switch Conditional Statements in the primer.ts File let name = Adam; if (name == Adam) { console.log(Name is Adam); } else if (name == Jacqui) { console.log(Name is Jacqui); } else { console.log(Name is neither Adam or Jacqui); } switch (name) { case Adam: console.log(Name is Adam); break; case Jacqui: console.log(Name is Jacqui); break; default: console.log(Name is neither Adam or Jacqui); break; } The results from the listing are as follows: Name is Adam Name is Adam The Equality Operator vs. the Identity Operator The equality and identity operators are of particular note. The equality operator will attempt to coerce (convert) operands to the same type in order to assess equality. This is a handy feature, as long as you are aware it is happening.
  • Book cover image for: JavaScript for Web Warriors
    • Patrick Carey, Sasha Vodnik, Patrick Carey(Authors)
    • 2021(Publication Date)
    Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. CHAPTER 2 WORKING WITH FUNCTIONS, DATA TYPES, AND OPERATORS 56 Developers commonly take advantage of falsy and truthy values to make comparison operations more compact. In a conditional statement that tests whether a text field in a form contains a value, you could write the code for the conditional statement as (document.getElementById("fname").value !== "") ?↵ // code to run if condition is true :↵ // code to run if condition is false; However, it’s simpler to test whether the value of the text field is falsy or truthy by omitting the comparison operator and writing the statement as follows: (document.getElementById("fname").value) ?↵ // code to run if condition is true :↵ // code to run if condition is false; Note that this code tests only the value of the text field. If it is an empty string (""), it is treated as false. Logical Operators Logical operators are used when combining expressions that will result in Boolean value of true or false or for negating a Boolean value, turning true to false or false to true. Figure 2-12 lists the three logical operators supported by JavaScript. Logical operators are often used within conditional and looping statements such as the if, for, and while statements. You will learn about conditional and looping statements in Chapter 3. Note OPERATOR DEFINITION EXAMPLE DESCRIPTION && and (x === 5) && (y === 8) Tests whether x is equal to 5 and y is equal to 8 || or (x === 5) || (y === 8) Test whether x is equal to 5 or y is equal to 8 ! not ! (x < 5) Test whether x is not less than 5 Figure 2-12 Logical operators The following conditional operator uses the And operator (&&) to combine two conditions testing whether the value of the member variable is “prime” and the value of the plan variable is “gold”.
  • Book cover image for: HTML and CSS
    eBook - ePub

    HTML and CSS

    The Comprehensive Guide

    • Jürgen Wolf(Author)
    • 2023(Publication Date)
    • SAP PRESS
      (Publisher)
    else construct with the selection operator. This is very useful, for example, if you want to assign a specific value to a variable depending on the condition. The structure of the operator is as follows:
    let val = condition ? value1 : value2 ;
    Here the value1 value is assigned to the variable val if condition is true . If condition is false , the value2 will be assigned to val . With regard to the if -else construct, this roughly corresponds to the following:
    let val ; if ( condition ) { val = value1 ; } else { val = value2 ; }
    The else branch can be omitted if val is initialized with false at the beginning. However, this is also more about demonstrating the counterpart of the selection operator.
    Here’s an example of the selection operator, where prompt() is used to query a pseudo password, and according to the input, true or false gets assigned to the isAdmin variable:
    let pwd = prompt( 'Enter password: ' ); let isAdmin = pwd == 12345678 ? true : false ; console .log( isAdmin );

    17.7.5    Logical Operators

    The logical operators in JavaScript are && (AND), || (OR), and ! (NOT). Logical operators are used with truth values. If you use numbers, they will be implicitly converted to a truth value before they are linked with && , || , or !.
    Operator Meaning
    &&
    Expressions linked with the AND operator return true only if all expressions are true . Example:
    if ( ival1 > 0 && ival2 > 0 ) {  // Both expressions are true = true.}
    ||
    Expressions combined with the logical OR operator return true if at least one of the expressions is true. Example:
    if ( ival1 > 0 || ival2 > 0 ) {  // At least one expression is true = true.}
    !
    You can use the logical NOT
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.