Teachnique
      CourseRoadmaps
      Login

      OverviewPlacementSyntaxHello WorldConsole.log()CommentsVariableslet StatementConstantsData TypesType ConversionsStrict ModeReserved Keywords

      OperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsConditional Operatorstypeof OperatorNullish Coalescing OperatorDelete OperatorComma OperatorGrouping OperatorYield OperatorSpread OperatorExponentiation OperatorOperator Precedence

      If...ElseWhile LoopsFor LoopFor...in LoopFor...of LoopLoop ControlBreak StatementContinue StatementSwitch CaseUser Defined Iterators

      FunctionsFunction ExpressionsFunction ParametersDefault ParametersFunction() ConstructorFunction HoistingArrow FunctionsFunction InvocationFunction call() MethodFunction apply() MethodFunction bind() MethodClosuresVariable ScopeGlobal VariablesSmart Function Parameters

      NumberBooleanStringsArraysDateMathRegExpSymbolSetsWeakSetMapsWeakMapIterablesReflectTypedArrayTempate LiteralsTagged Templates

      Objects OverviewClassesObject PropertiesObject MethodsStatic MethodsDisplay ObjectsObject AccessorsObject ConstructorsNative PrototypesES5 Object MethodsEncapsulationInheritanceAbstractionPolymorphismDestructuring AssignmentObject DestructuringArray DestructuringNested DestructuringOptional ChainingGlobal ObjectMixinsProxies

      HistoryVersionsES5ES6ECMAScript 2016ECMAScript 2017ECMAScript 2018ECMAScript 2019ECMAScript 2020ECMAScript 2021ECMAScript 2022

      CookiesCookie AttributesDeleting Cookies

      Browser Object ModelWindow ObjectDocument ObjectScreen ObjectHistory ObjectNavigator ObjectLocation ObjectConsole Object

      Web APIHistory APIStorage APIForms APIWorker APIFetch APIGeolocation API

      EventsDOM Events

      Feedback

      Submit request if you have any questions.

      Course
      Conditional Operators

      JavaScript Tutorial

      This JavaScript tutorial is crafted for beginners to introduce them to the basics and advanced concepts of JavaScript. By the end of this guide, you'll reach a proficiency level that sets the stage for further growth. Aimed at empowering you to progress towards becoming a world-class software developer, this tutorial paves the way for a successful career in web development and beyond.

      Conditional Operators

      JavaScript Conditional Operators

      The conditional operator in JavaScript first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator is also known as the ternary operator.
      The JavaScript conditional (ternary) operator is only operator that takes three operands – a condition followed by a question mark (?), then the first expression to be executed if the condition is truthy followed by a colon (:), and finally the second expression to be executed if the condition is falsy.
      There are six falsy values in JavaScript. These are − 0 (zero), false, empty string ('' or ""), null, undefined, and NaN. All other values are treated as truthy in JavaScript.

      Syntax

      Following is the syntax of conditional (ternary) operator in JavaScript
      var variable = condition ? exp1 : exp2;

      Parameters

      Here, we have explained the parameters in the above statement.
      • condition − It is a conditional statement.
      • exp1 − If the conditional statement evaluates truthy, control flow executes the exp1 expression.
      • exp2 − If the conditional statement evaluates falsy, control flow executes the exp2 expression.
      If the value of the condition is any falsy value, the result of the expression will be the value of exp2; otherwise, it will be the value of exp1.

      Example

      In the example below, we compare the value of the num1 and num2 variables in the conditional statement. Here, the conditional statement evaluates true, so the result variable contains the value of the first expression.
      <html>
      <body>
      <div id="output"></div>
      <script>
      var num1 = 90;
      var num2 = 67;
      var res = num1 > num2 ? "num1 is greater than num2" : "num2 is greater than num1";
      document.getElementById("output").innerHTML = res;
      </script>
      </body>
      </html>
      It will produce the following result
      num1 is greater than num2

      Example

      In the example below, we assign the value to the object property according to the conditional statement’s result.
      Now, imagine what if you need to write the if-else statement to assign value to each property conditionally. The code will become complex, but with the ternary operator, you can easily do it with a single line of code.
      <html>
      <body>
      <div id="output"></div>
      <script>
      const year = 2004;
      const obj = {
      name: "John",
      age: year < 2005 ? "adult" : "minor",
      city: "New York"
      };
      
      document.getElementById("output").innerHTML =
      obj.name + " is " + obj.age + " and lives in " + obj.city;
      </script>
      </body>
      </html>
      It will produce the following result
      John is adult and lives in New York

      Example

      This example demonstrates that you can also use the expression instead of values. According to the conditional statement, control flow evaluates the first or second expression and assigns the resultant value to the 'result' variable.
      <html>
      <body>
      <div id="output"></div>
      <script>
      let operator = '-';
      let res = operator == '+' ? 10 + 20 : 10 - 20;
      document.getElementById("output").innerHTML = "The result is: " + res;
      </script>
      </body>
      </html>
      It will produce the following result
      The result is: -10
      In short, you can use the ternary or conditional operator to shorten the code, which uses the if-else statement.

      Handling null values

      We can use the JavaScript conational operator to handle null value to set a default value if the user passes a null value.

      Example

      Try the following example
      <html>
      <body>
      <div id="output"></div>
      <script>
      const greet = (user) => {
      const name = user? user.name : "stranger";
      return `Hello, ${name}`;
      };
      document.getElementById("output").innerHTML =
      greet({ name: "John" }) + "<br>" +
      greet(null);
      </script>
      </body>
      </html>
      It will produce the following result
      Hello, John
      Hello, stranger