- JS Tutorial
- JS Exercise
- JS Interview Questions
- JS Operator
- JS Projects
- JS Examples
- JS Free JS Course
- JS A to Z Guide
- JS Formatter
JavaScript Ternary Operator
The Ternary Operator in JavaScript is a shortcut for writing simple if-else statements. It’s also known as the Conditional Operator because it works based on a condition. The ternary operator allows you to quickly decide between two values depending on whether a condition is true or false.
How Does the Ternary Operator Work?
The ternary operator works with three parts: Condition: A statement that returns true or false. Value if True: What happens if the condition is true? Value if False: What happens if the condition is false? Syntax: condition ? trueExpression : falseExpression
Characteristics of Ternary Operator
- The expression consists of three operands: the condition, value if true, and value if false.
- The evaluation of the condition should result in either a true/false or a boolean value.
- The true value lies between “ ? ” & “ : ” and is executed if the condition returns true. Similarly, the false value lies after “:” and is executed if the condition returns false.
Nested Ternary Operators
The below code assigns a grade to marks using nested ternary operators. It checks ranges: <40 as “Unsatisfactory”, <60 as “Average”, <80 as “Good”, and >=80 as “Excellent”, then prints the result.
Alternate Implementation:
JavaScript Ternary Operator – FAQs
What is the ternary operator in javascript.
The ternary operator is a shorthand for the if-else statement. It takes three operands and is the only operator that takes three operands. It is used to evaluate a condition and return one of two values based on whether the condition is true or false.
What is the syntax of the ternary operator?
The syntax of the ternary operator is: condition ? expressionIfTrue : expressionIfFalse.
How does the ternary operator work?
The ternary operator evaluates the condition. If the condition is true, it returns expressionIfTrue; otherwise, it returns expressionIfFalse.
Can you use the ternary operator for multiple conditions?
Yes, you can nest ternary operators to handle multiple conditions. However, this can make the code hard to read, so it’s usually better to use if-else statements for complex conditions.
Is the ternary operator only used for returning values?
Primarily, the ternary operator is used for returning values based on a condition. However, it can also be used to execute code conditionally, but this is not recommended as it can make the code less readable.
Similar Reads
- JavaScript Tutorial JavaScript is a programming language used for creating dynamic content on websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line providing more flexibility. HTML adds Structure to a Webpage, CSS s 7 min read
JavaScript Basics
- Introduction to JavaScript JavaScript is a lightweight, cross-platform, single-threaded, and interpreted compiled programming language. It is also known as the scripting language for webpages. It is well-known for the development of web pages, and many non-browser environments also use it. JavaScript is a weakly typed languag 9 min read
- JavaScript Versions JavaScript is a popular programming language used by developers all over the world. It’s a lightweight and easy-to-learn language that can run on both the client-side (in your browser) and the server-side (on the server). JavaScript was created in 1995 by Brendan Eich. In 1997, JavaScript became a s 2 min read
- How to Add JavaScript in HTML Document? To add JavaScript in HTML document, several method can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file. Table of Content Inline JavaScriptInternal JavaScript (Within <script> Tag)1. JavaScript Code Inside <head> Tag 4 min read
- JavaScript Syntax JavaScript syntax refers to the rules and conventions dictating how code is structured and arranged within the JavaScript programming language. This includes statements, expressions, variables, functions, operators, and control flow constructs. Syntax console.log("Basic Print method in JavaScript"); 6 min read
- JavaScript Output JavaScript provides different methods to display output, such as console.log(), alert(), document.write(), and manipulating HTML elements directly. Each method has its specific use cases, whether for debugging, user notifications, or dynamically updating web content. Here we will explore various Jav 4 min read
- JavaScript Comments Comments help explain code (they are not executed and hence do not have any logic implementation). We can also use them to temporarily disable parts of your code. 1. Single Line CommentsA single-line comment in JavaScript is denoted by two forward slashes (//), [GFGTABS] JavaScript // A single line 2 min read
JS Variables & Datatypes
- Variables and Datatypes in JavaScript Variables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, getting a good grasp of these concepts is important for writing code that works well and is easy to understand. VariablesIn Java 4 min read
- Global and Local variables in JavaScript In JavaScript, understanding the difference between global and local variables is important for writing clean, maintainable, and error-free code. Variables can be declared with different scopes, affecting where and how they can be accessed. Global VariablesGlobal variables in JavaScript are those de 4 min read
- JavaScript Let The let keyword in JavaScript is used to make variables that are scoped to the block they're declared in. Once you've used let to define a variable, you cannot declare it again within the same block. It's important to declare let variables before using them. The let keyword was introduced in the ES6 4 min read
- JavaScript Const The const keyword in JavaScript is used to create variables that cannot be redeclared or changed after their first assignment. This keeps the variable's value fixed. Additionally, const doesn’t allow redeclaration of the same variable within the same block, and it provides block scope. It was introd 5 min read
- JavaScript var The JavaScript var statement declares variables with function scope or globally. Before ES6, var was the sole keyword for variable declaration, without block scope, unlike let and const. Var is rarely used these days. Syntax: var variableName = valueOfVar;Function ScopeThe variables declared inside 3 min read
JS Operators
- JavaScript Operators JavaScript Operators are symbols used to perform specific mathematical, comparison, assignment, and logical computations on operands. They are fundamental elements in JavaScript programming, allowing developers to manipulate data and control program flow efficiently. Understanding the different type 11 min read
- Operator precedence in JavaScript Operator precedence refers to the priority given to operators while parsing a statement that has more than one operator performing operations in it. Operators with higher priorities are resolved first. But as one goes down the list, the priority decreases and hence their resolution. ( * ) and ( / ) 2 min read
- JavaScript Arithmetic Operators JavaScript Arithmetic Operators are the operator that operate upon the numerical values and return a numerical value. Addition (+) OperatorThe addition operator takes two numerical operands and gives their numerical sum. It also concatenates two strings or numbers. [GFGTABS] JavaScript // Number + N 6 min read
- JavaScript Assignment Operators Assignment operators are used to assign values to variables in JavaScript. [GFGTABS] JavaScript // Lets take some variables x = 10 y = 20 x = y // Here, x is equal to 20 console.log(x); console.log(y); [/GFGTABS]Output20 20 More Assignment OperatorsThere are so many assignment operators as shown in 6 min read
- JavaScript Comparison Operators JavaScript comparison operators are essential tools for checking conditions and making decisions in your code. 1. Equality Operator (==) The Equality operator is used to compare the equality of two operands. [GFGTABS] JavaScript // Illustration of (==) operator let x = 5; let y = '5'; // Che 5 min read
- JavaScript Logical Operators Logical operators in JavaScript are used to perform logical operations on values and return either true or false. These operators are commonly used in decision-making statements like if or while loops to control the flow of execution based on conditions. In JavaScript, there are basically three type 5 min read
- JavaScript Bitwise Operators In JavaScript, a number is stored as a 64-bit floating-point number but bitwise operations are performed on a 32-bit binary number. To perform a bit-operation, JavaScript converts the number into a 32-bit binary number (signed) and performs the operation and converts back the result to a 64-bit numb 5 min read
- JavaScript Ternary Operator The Ternary Operator in JavaScript is a shortcut for writing simple if-else statements. It’s also known as the Conditional Operator because it works based on a condition. The ternary operator allows you to quickly decide between two values depending on whether a condition is true or false. [GFGTABS] 3 min read
- JavaScript Comma Operator JavaScript Comma Operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. [GFGTABS] JavaScript let x = (1, 2, 3); console.log(x); [/GFGTABS]Output3 Here is another example to show that all expressions are actually executed. [GFGTABS] Java 2 min read
- JavaScript Unary Operators JavaScript Unary Operators work on a single operand and perform various operations, like incrementing/decrementing, evaluating data type, negation of a value, etc. Unary Plus (+) OperatorThe unary plus (+) converts an operand into a number, if possible. It is commonly used to ensure numerical operat 4 min read
- JavaScript in and instanceof operators JavaScript Relational Operators are used to compare their operands and determine the relationship between them. They return a Boolean value (true or false) based on the comparison result. JavaScript in OperatorThe in-operator in JavaScript checks if a specified property exists in an object or if an 3 min read
- JavaScript String Operators JavaScript String Operators are used to manipulate and perform operations on strings. There are two operators which are used to modify strings in JavaScript. These operators help us to join one string to another string. 1. Concatenate OperatorConcatenate Operator in JavaScript combines strings using 3 min read
JS Statements
- JavaScript Statements In JavaScript, a statement is like a complete instruction that tells the computer to do something. These statements are made up of different parts: Values, Operators, Keywords, Expressions, and Comments. Each statement is executed by the browser in the order it appears, line by line. Examples of Jav 3 min read
- JavaScript if-else JavaScript if-else statement executes a block of code based on a condition. If the condition evaluates to true, the code inside the "if" block executes; otherwise, the code inside the "else" block, if present, executes. Such control statements are used to cause the flow of execution to advance and b 4 min read
- JavaScript switch Statement The JavaScript switch statement evaluates an expression and executes a block of code based on matching cases. It provides an alternative to long if-else chains, improving readability and maintainability, especially when handling multiple conditional branches. Switch Statement Example: Here, we will 5 min read
- JavaScript Break Statement JavaScript break statement is used to terminate the execution of the loop or the switch statement when the condition is true. In Switch Block (To come out of the block)[GFGTABS] JavaScript const fruit = "Mango"; switch (fruit) { case "Apple": console.log("Apple is healthy. 2 min read
- JavaScript Continue Statement The continue statement in JavaScript is used to break the iteration of the loop and follow with the next iteration. Example of continue to print only odd Numbers smaller than 10 [GFGTABS] JavaScript for (let i = 0; i < 10; i++) { if (i % 2 == 0) continue; console.log(i); } [/GFGTABS]Output1 3 5 7 1 min read
- JavaScript return Statement The JavaScript return statement is used to stop the function's execution and optionally return a value to the caller. If there is no return statement in a function, then it returns undefined. Returning a Single ValueThis code defines a function Product(a, b) that returns the product of a and b. [GFG 2 min read
- JavaScript Loops JavaScript loops are essential for efficiently handling repetitive tasks. They execute a block of code repeatedly as long as a specified condition remains true. These loops are powerful tools for automating tasks and streamlining your code. For example, suppose we want to print “Hello World” 5 times 8 min read
- JavaScript For Loop JavaScript for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. [GFGTABS] javascript // for loop begins when x=2 // and runs till x <= 4 for (let x = 2; x <= 4; x++) 5 min read
- JavaScript While Loop The while loop executes a block of code as long as a specified condition is true. In JavaScript, this loop evaluates the condition before each iteration and continues running as long as the condition remains true Here's an example that prints from 1 to 5. [GFGTABS] JavaScript let count = 1; while (c 3 min read
- JavaScript For In Loop The JavaScript for...in loop iterates over the properties of an object. It allows you to access each key or property name of an object. [GFGTABS] JavaScript const car = { make: "Toyota", model: "Corolla", year: 2020 }; for (let key in car) { console.log(`${key}: ${car[key]}`); } 3 min read
- JavaScript for...of Loop The JavaScript for...of loop is a modern, iteration statement introduced in ECMAScript 2015 (ES6). Works for iterable objects such as arrays, strings, maps, sets, and more. It is better choice for traversing items of iterables compared to traditional for and for in loops, especially when we have bre 3 min read
- JavaScript do...while Loop A do...while loop in JavaScript is a control structure where the code executes repeatedly based on a given boolean condition. It's similar to a repeating if statement. One key difference is that a do...while loop guarantees that the code block will execute at least once, regardless of whether the co 4 min read
JS Perfomance & Debugging
- JavaScript | Performance JavaScript is an essential part of almost every web app and web-based software. JavaScript’s client-side scripting capabilities can make applications more dynamic and interactive, but it also increases the chance of inefficiencies in code. Thus, poorly written JavaScript can make it difficult to ens 4 min read
- Debugging in JavaScript Debugging in JavaScript refers to the process of identifying and fixing errors or bugs in code. It involves using various tools like browser consoles, debuggers, and logging techniques to analyze runtime behavior, trace program flow, and resolve issues efficiently. Table of Content Using debugger ke 4 min read
- JavaScript Errors Throw and Try to Catch In JavaScript, errors can be thrown using the throw statement to indicate an exceptional condition. The try block is used to wrap code that might throw an error, and the catch block handles the error, preventing the program from crashing and allowing graceful error management. But all errors can be 3 min read
- Objects in Javascript An object in JavaScript is a data structure used to store related data collections. It stores data as key-value pairs, where each key is a unique identifier for the associated value. Objects are dynamic, which means the properties can be added, modified, or deleted at runtime. There are two primary 4 min read
- Introduction to Object Oriented Programming in JavaScript As JavaScript is widely used in Web Development, in this article we will explore some of the Object Oriented mechanisms supported by JavaScript to get the most out of it. Some of the common interview questions in JavaScript on OOPS include: How is Object-Oriented Programming implemented in JavaScrip 7 min read
- JavaScript Objects In our previous article on Introduction to Object Oriented Programming in JavaScript we have seen all the common OOP terminology and got to know how they do or don't exist in JavaScript. In this article, objects are discussed in detail. Creating Objects: In JavaScript, Objects can be created using t 6 min read
- Creating objects in JavaScript An object in JavaScript is a collection of key-value pairs, where keys are strings (properties) and values can be any data type. Objects can be created using object literals, constructors, or classes. Properties are defined with key-value pairs, and methods are functions defined within the object, e 5 min read
- JavaScript JSON Objects JSON (JavaScript Object Notation) is a handy way to share data. It's easy for both people and computers to understand. In JavaScript, JSON helps organize data into simple objects. Let's explore how JSON works and why it's so useful for exchanging information. JSON object Syntax:const jsonData = { "k 4 min read
- JavaScript Object Reference JavaScript Objects are the most important data type and form the building blocks for modern JavaScript. The "Object" class represents the JavaScript data types. Objects are quite different from JavaScript’s primitive data types (Number, String, Boolean, null, undefined, and symbol). It is used to st 4 min read
JS Function
- Functions in JavaScript A function in JavaScript is a reusable block of code that performs a specific task. You define it once, and then you can run (or "call") it whenever you need that task done in your program. [GFGTABS] JavaScript function sum(x, y) { return x + y; } console.log(sum(6, 9)); [/GFGTABS]Output15 Function 4 min read
- How to write a function in JavaScript ? JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod 4 min read
- JavaScript Function Call The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). This allows borrowing methods from other objects, executing them within a different context, overriding the default value, and passing arguments. Syntax: cal 2 min read
- Different ways of writing functions in JavaScript A JavaScript function is a block of code designed to perform a specific task. Functions are only executed when they are called (or "invoked"). JavaScript provides different ways to define functions, each with its own syntax and use case. Below are the ways of writing functions in JavaScript: Table o 3 min read
- Difference between Methods and Functions in JavaScript Grasping the difference between methods and functions in JavaScript is essential for developers at all levels. While both are fundamental to writing effective code, they serve different purposes and are used in various contexts. This article breaks down the key distinctions between methods and funct 3 min read
- Explain the Different Function States in JavaScript In JavaScript, we can create functions in many different ways according to the need for the specific operation. For example, sometimes we need asynchronous functions or synchronous functions. In this article, we will discuss the difference between the function Person( ) { }, let person = Person ( ), 3 min read
- JavaScript Function Complete Reference A JavaScript function is a set of statements that take inputs, perform specific computations, and produce outputs. Essentially, a function performs tasks or computations and then returns the result to the user. Syntax: function functionName(Parameter1, Parameter2, ..) { // Function body}Example: Bel 3 min read
- JavaScript Arrays An array in JavaScript is a data structure used to store multiple values in a single variable. It can hold various data types and allows for dynamic resizing. Elements are accessed by their index, starting from 0. 1. Create using LiteralCreating an array using array literal involves using square bra 7 min read
- JavaScript Array Methods JavaScript array methods are built-in functions that allow efficient manipulation and traversal of arrays. They provide essential functionalities like adding, removing, and transforming elements, as well as searching, sorting, and iterating through array elements, enhancing code readability and prod 10 min read
- Best-Known JavaScript Array Methods An array is a special variable in all programming languages used to store multiple elements. JavaScript array come with built-in methods that every developer should know how to use. These methods help in adding, removing, iterating, or manipulating data as per requirements. There are some Basic Java 7 min read
- What are the Important Array Methods of JavaScript ? In this article, we will try to understand various important Array methods (like push(), pop(), and so on) with the help of certain examples. Let us first understand how we can create an array in JavaScript by using certain syntax provided. Syntax: let array = [element1, element2, .....]Alternativel 7 min read
- JavaScript Array Reference JavaScript Array is used to store multiple elements in a single variable. It can hold various data types, including numbers, strings, objects, and even other arrays. It is often used when we want to store a list of elements and access them by a single variable. Syntax:const arr = ["Item1", "Item2", 4 min read
- JavaScript Strings 'A JavaScript String is a sequence of characters, typically used to represent text. In JavaScript there is no character type (Similar to Python and different from C, C++ and Java), so a single character string is used when we need a character.Like Java and Python, strings in JavaScript are immutable 6 min read
- JavaScript String Methods JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing. The following are methods that we can call on strings. slice() extr 12 min read
- JavaScript String Reference JavaScript strings are used for storing and manipulating text content. They can contain zero or more characters within single or double quotes, like "Geeksforgeeks" or 'Geeksforgeeks'. SyntaxString(object)Example: In this example, we will return the length of a string. [GFGTABS] JavaScript function 5 min read
- JavaScript Numbers JavaScript numbers are primitive data types and, unlike other programming languages, you don't need to declare different numeric types like int, float, etc. JavaScript numbers are always stored in double-precision 64-bit binary format IEEE 754. This format stores numbers in 64 bits: 0-51 bits store 6 min read
- How numbers are stored in JavaScript ? In this article, we will try to understand how numbers are stored in JavaScript. Like any other programming language, all the data is stored inside the computer in the form of binary numbers 0 and 1. Since computers can only understand and process data in the form of 0's and 1's. In JavaScript, ther 6 min read
- How to create a Number object using JavaScript ? In this article, we will discuss how to create a Number object using JavaScript. A number object is used to represent integers, decimal or float point numbers, and many more. The primitive wrapper object Number is used to represent and handle numbers. examples: 20, 0.25. We generally don't need to w 2 min read
- JavaScript Number Reference JavaScript Numbers are always stored in double-precision 64-bit binary format IEEE 754. The types of number literals You can use decimal, binary, octal, and hexadecimal. Syntax: Number(object) C/C++ Code function func() { // Original string let a = true; let value = Number(a); console.log(value); } 3 min read
- JavaScript Math Object JavaScript Math object is used to perform mathematical operations on numbers. All the properties of Math are static and unlike other objects, it does not have a constructor. We use Math only on Number data type and not on BigInt Example 1: This example uses math object properties to return their val 2 min read
- What is the use of Math object in JavaScript ? The Math object in JavaScript provides a set of methods and properties for mathematical constants and functions. It is a built-in object that allows for performing mathematical operations and accessing mathematical constants without creating an instance. What is the Math Object?The Math object is an 4 min read
- JavaScript Math Reference JavaScript Math object is used to perform mathematical operations on numbers. Math is an inbuilt object that works with numbers types but it does not work with BigInt. Example: Below example will give you a brief idea of JavaScript math objects. C/C++ Code // Return PI value(3.141592653589793) conso 4 min read
- Map in JS A JavaScript Map holds key-value pairs and similar to Hash Map or Dictionary in other languages. Preserves the original insertion order. It supports any type, including objects and primitives, as keys or values. This feature allows for efficient data retrieval and manipulation.JavaScript Maps intern 4 min read
- What is JavaScript Map and how to use it ? What is Map?A Map in JavaScript is a collection of key-value pairs where keys can be any data type. Unlike objects, keys in a Map maintain insertion order. It provides methods to set, get, delete, and iterate over elements efficiently, making it useful for data storage and retrieval tasks. Syntaxnew 3 min read
- JavaScript Map Reference JavaScript Map is a collection of elements where each element is stored as a key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, and value pair in the same order as inserted. You can create a JavaScri 3 min read
- Set in JavaScript A Set in JavaScript is used to store a unique collection of items, meaning no duplicates are allowed. Sets internally use hash table which makes search, insert and delete operations super fast compared to arrays. Please note that a hash table data structure allows these operations in constant time o 8 min read
- How are elements ordered in a Set in JavaScript ? In JavaScript, a new object called Set was introduced in the ES6 version. The Set object is similar to Map but the major difference is that elements in the set are unique and repeated addition of the same type of elements is not possible. The set can store any type of value whether primitive or obje 2 min read
- Iterate over Set in JavaScript or JS We will iterate over set elements in JavaScript. A set is a collection of unique elements i.e. no element can appear more than once in a set. Below are the approaches to iterate over set elements in JavaScript: Approach 1: Using for...of loopThe for…of loop iterates over the iterable objects (like A 3 min read
- How to sort a set in JavaScript ? Sorting a Set based on the values of its elements is a common need in JavaScript. While the built-in sort() function can't be directly applied to a Set, there's a workaround. Let's explore how we can achieve this: Instead of directly sorting the Set, we'll: Convert the Set into an array to make it s 4 min read
- JavaScript Set Reference JavaScript Set is a collection of items that are unique, meaning no element can be repeated. Elements of the set can be iterated in the insertion order. A Set can store any type of value, whether primitive or objects. Syntaxnew Set()Example: This example will show the use of Set() constructor. [GFGT 3 min read
- JavaScript Date The JavaScript Date object represents a specific moment in time, measured in milliseconds since the Unix Epoch (January 1, 1970). It's crucial for working with date and time in web applications, providing methods for tasks like date manipulation, formatting, and calculations. What is the JavaScript 4 min read
- JavaScript Promise JavaScript promises might sound a bit complicated at first, but once you get a clear understanding of them, they make working with code that takes time to complete, like fetching data from a website or waiting for a timer, much easier to manage. Let's break down what promises are and how you can use 7 min read
- JavaScript BigInt JavaScript BigInt is a built-in object that represents whole numbers larger than (2^{53} - 1). A BigInt value, also known as a bigint primitive, is created by appending n to an integer literal or by calling the BigInt() function with an integer or string value. It allows precise arithmetic with inte 4 min read
- JavaScript Boolean JavaScript Boolean represents true or false values. It's used for logical operations, condition testing, and variable assignments based on conditions. Values like 0, NaN, empty strings, undefined, and null are false; non-empty strings, numbers other than 0, objects, and arrays are true. Note: A vari 4 min read
- JavaScript Proxy/Handler JavaScript Proxy is an object which intercepts another object and resists the fundamental operations on it. This object is mostly used when we want to hide information about one object from unauthorized access. A Proxy consists of two parts which are its target and handler. A target is a JavaScript 3 min read
- JavaScript WeakMap A WeakMap in JavaScript is a collection where keys can only be objects or non-registered symbols. It allows values of any type and doesn't prevent the keys from being garbage collected, making its values eligible for garbage collection when their keys are collected. Syntaxnew WeakMap()new WeakMap(it 3 min read
- JavaScript WeakSet JavaScript WeakSet is similar to Set (Does not hold duplicates) with the following differences. Stores by weak reference. That is, if an object is not referenced by anything else, it would be cleaned from the WeakSet.Allows only Objects and Symbols to be stored. Example 1: In this example, we create 2 min read
- JavaScript Function Generator A generator function uses the yield keyword to generate values, pausing execution and sending values to the caller. It retains the state to resume execution after yield, continuing immediately after the last yield run. Syntax : // An example of generator functionfunction* gen(){ yield 1; yield 2; . 5 min read
- JavaScript JSON JSON, short for JavaScript Object Notation, is a way to organize data. It's similar to XML in that it structures information, but it's more lightweight and easier for humans to read and write. Web applications commonly use JSON to exchange data between each other. What is JSON?JSON (JavaScript Objec 5 min read
- Arrow functions in JavaScript ES6 introduced the Arrow functions in JavaScript which offer a more concise and readable way to write function expressions. They use the => (arrow) syntax, which not only reduces boilerplate but also binds this lexically, making them particularly useful in certain scenarios like handling callback 4 min read
- JavaScript this Keyword In JavaScript, this keyword refers to the object that is currently executing a function or method. Its value is determined by how a function is called. this typically represents the context in which a function operates, allowing access to the properties and methods of its containing object. What is 6 min read
- "use strict" in JavaScript In JavaScript, "use strict" is a directive that enables strict mode, which was first introduced in ECMAScript 5 (ES5) to assist in the writing of safer and more error-free code. "Use strict" is used to indicate that the code should be executed in strict mode, applying a stricter set of rules for Jav 5 min read
- Introduction to ES6 ES6 or ECMAScript 2015 is the 6th version of the ECMAScript programming language. ECMAScript is the standardization of Javascript which was released in 2015 and subsequently renamed as ECMAScript 2015.ECMAScript and Javascript are both different. ECMAScript vs JavaScriptECMAScript: It is the specifi 9 min read
- JavaScript Hoisting JavaScript Hoisting is the behavior where the interpreter moves function and variable declarations to the top of their respective scope before executing the code. This allows variables to be accessed before declaration, aiding in more flexible coding practices and avoiding "undefined" errors during 5 min read
- Async and Await in JavaScript Async and Await in JavaScript is used to simplify handling asynchronous operations using promises. By enabling asynchronous code to appear synchronous, they enhance code readability and make it easier to manage complex asynchronous flows. Async FunctionThe async function allows us to write promise-b 4 min read
JavaScript Exercises
- JavaScript Exercises, Practice Questions and Solutions JavaScript Exercise covers interactive quizzes, track progress, and enhance coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up your JavaScript proficiency at your own pace. Start coding now! A step-by-step JavaScript practice guide for beginner to advanc 4 min read
- Web Technologies
- javascript-operators
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- Português (do Brasil)
Conditional (ternary) operator
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy . This operator is frequently used as an alternative to an if...else statement.
An expression whose value is used as a condition.
An expression which is executed if the condition evaluates to a truthy value (one which equals or can be converted to true ).
An expression which is executed if the condition is falsy (that is, has a value which can be converted to false ).
Description
Besides false , possible falsy expressions are: null , NaN , 0 , the empty string ( "" ), and undefined . If condition is any of these, the result of the conditional expression will be the result of executing the expression exprIfFalse .
A simple example
Handling null values.
One common usage is to handle a value that may be null :
Conditional chains
The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain:
This is equivalent to the following if...else chain.
Specifications
Browser compatibility.
- Nullish coalescing operator ( ?? )
- Optional chaining ( ?. )
- Making decisions in your code — conditionals
- Expressions and operators guide
Popular Tutorials
Popular examples, reference materials, certification courses.
Created with over a decade of experience and thousands of feedback.
JS Introduction
- Getting Started
- JS Variables & Constants
- JS console.log
- JavaScript Data types
JavaScript Operators
- JavaScript Comments
- JS Type Conversions
JS Control Flow
- JS Comparison Operators
- JavaScript if else Statement
- JavaScript for loop
- JavaScript while loop
- JavaScript break Statement
- JavaScript continue Statement
- JavaScript switch Statement
JS Functions
- JavaScript Function
- Variable Scope
- JavaScript Hoisting
- JavaScript Recursion
- JavaScript Objects
- JavaScript Methods & this
- JavaScript Constructor
- JavaScript Getter and Setter
- JavaScript Prototype
- JavaScript Array
- JS Multidimensional Array
- JavaScript String
- JavaScript for...in loop
- JavaScript Number
- JavaScript Symbol
Exceptions and Modules
- JavaScript try...catch...finally
- JavaScript throw Statement
- JavaScript Modules
- JavaScript ES6
- JavaScript Arrow Function
- JavaScript Default Parameters
- JavaScript Template Literals
- JavaScript Spread Operator
- JavaScript Map
- JavaScript Set
- Destructuring Assignment
- JavaScript Classes
- JavaScript Inheritance
- JavaScript for...of
- JavaScript Proxies
JavaScript Asynchronous
- JavaScript setTimeout()
- JavaScript CallBack Function
- JavaScript Promise
- Javascript async/await
- JavaScript setInterval()
Miscellaneous
- JavaScript JSON
- JavaScript Date and Time
- JavaScript Closure
- JavaScript this
- JavaScript use strict
- Iterators and Iterables
- JavaScript Generators
- JavaScript Regular Expressions
- JavaScript Browser Debugging
- Uses of JavaScript
JavaScript Tutorials
JavaScript if...else Statement
JavaScript Comparison and Logical Operators
JavaScript null and undefined
- JavaScript typeof Operator
- JavaScript while and do...while Loop
JavaScript Ternary Operator
A ternary operator can be used to replace an if..else statement in certain situations. Before you learn about ternary operators, be sure to check the JavaScript if...else tutorial .
- What is a Ternary operator?
A ternary operator evaluates a condition and executes a block of code based on the condition.
Its syntax is:
The ternary operator evaluates the test condition.
- If the condition is true , expression1 is executed.
- If the condition is false , expression2 is executed.
The ternary operator takes three operands, hence, the name ternary operator. It is also known as a conditional operator.
Let's write a program to determine if a student passed or failed in the exam based on marks obtained.
Example: JavaScript Ternary Operator
Suppose the user enters 78 . Then the condition marks >= 40 is checked which evaluates to true . So the first expression pass is assigned to the result variable.
Suppose the use enters 35 . Then the condition marks >= 40 evaluates to false . So the second expression fail is assigned to the result variable.
Ternary Operator Used Instead of if...else
In JavaScript, a ternary operator can be used to replace certain types of if..else statements. For example,
You can replace this code
The output of both programs will be the same.
- Nested ternary operators
You can also nest one ternary operator as an expression inside another ternary operator. For example,
Note : You should try to avoid nested ternary operators whenever possible as they make your code hard to read.
Table of Contents
- Ternary operator used instead if...else
Video: JavaScript Ternary Operators
Sorry about that.
Our premium learning platform, created with over a decade of experience and thousands of feedbacks .
Learn and improve your coding skills like never before.
- Interactive Courses
- Certificates
- 2000+ Challenges
Related Tutorials
JavaScript Tutorial
Home » JavaScript Tutorial » JavaScript Ternary Operator
JavaScript Ternary Operator
Summary : in this tutorial, you will learn how to use the JavaScript ternary operator to make your code more concise.
Introduction to JavaScript ternary operator
When you want to execute a block if a condition evaluates to true , you often use an if…else statement. For example:
In this example, we show a message that a person can drive if the age is greater than or equal to 16. Alternatively, you can use a ternary operator instead of the if-else statement like this:
Or you can use the ternary operator in an expression as follows:
Here’s the syntax of the ternary operator:
In this syntax, the condition is an expression that evaluates to a Boolean value, either true or false .
If the condition is true , the first expression ( expresionIfTrue ) executes. If it is false, the second expression ( expressionIfFalse ) executes.
The following shows the syntax of the ternary operator used in an expression:
In this syntax, if the condition is true , the variableName will take the result of the first expression ( expressionIfTrue ) or expressionIfFalse otherwise.
JavaScript ternary operator examples
Let’s take some examples of using the ternary operator.
1) Using the JavaScript ternary operator to perform multiple statements
The following example uses the ternary operator to perform multiple operations, where each operation is separated by a comma. For example:
In this example, the returned value of the ternary operator is the last value in the comma-separated list.
2) Simplifying ternary operator example
See the following example:
If the locked is 1, then the canChange variable is set to false , otherwise, it is set to true . In this case, you can simplify it by using a Boolean expression as follows:
3) Using multiple JavaScript ternary operators example
The following example shows how to use two ternary operators in the same expression:
It’s a good practice to use the ternary operator when it makes the code easier to read. If the logic contains many if...else statements, you should avoid using the ternary operators.
- Use the JavaScript ternary operator ( ?: )to make the code more concise.
How to Use the Ternary Operator in JavaScript – Explained with Examples
Tired of bulky if-else statements? JavaScript's ternary operator offers a powerful solution. This handy tool lets you condense complex conditional logic into a single line, making your code cleaner, more elegant, and efficient.
In this article, we'll take a deep dive into the ternary operator, understanding its syntax and showcasing real-world examples to help you understand how it works to harness its full potential.
Here is What We'll Cover:
What is a ternary operator, how to use the ternary operator.
- How to Refactor if-else Statements to Ternary operator
How to Chain Ternary Operators
- Best Practices when using the Ternary Operator
A ternary operator is a conditional operator in JavaScript that evaluates a conditional expression and returns either a truthy or falsy value.
To understand how this works, let's take a closer look at its syntax below:
From the syntax above, the condionalExpression is the expression that serves as the evaluation point, determining either a truthy or falsy value.
Following the ? (question mark), the value provided is returned in case the expression evaluates to truthy, whereas the value following the : (colon) is returned if the expression results in a falsy outcome.
The truthyValue and falsyValue can be anything in JavaScript. It can encompass various entities such as functions, values stored in variables, objects, numbers, strings, and more. The ternary operator grants you the flexibility to return any desired value, offering versatility in your code.
Now that we've examined the syntax and its functionality, let's explore how to use the ternary operator to deepen our understanding.
Consider this scenario: we're building a gaming platform that only allows users that are aged 18 and above. We'll design a function to check a user's age. If they're under 18, they'll be denied access; otherwise, they'll gain entry to the platform.
From the code snippet above, we created a function, canAccessPlatform , which evaluates whether a user, represented by their age parameter, meets the requirement to access the platform.
It utilizes a ternary operator to determine if the age is 18 or older, assigning true to shouldAccess if the condition is met, and false otherwise. Finally, it returns the value of shouldAccess , indicating whether the user can access the platform or not.
If the age is 18 or older, the expression becomes true, so the operator returns true after the ? . Otherwise, it returns false. This result is saved in a variable and then returned from the function.
While this basic use case simplifies code and improves readability by replacing unnecessary if-else blocks, it's important to use it sparingly to avoid cluttering and complicating your code. Later, we'll discuss best practices for using the ternary operator.
Here's another example illustrating the use of the ternary operator. We'll create a function to determine whether a number is even or odd. Check out the code snippet below:
From the code snippet above:
- We define a function checkEvenOrOdd that takes a number parameter.
- Inside the function, we use the ternary operator to check if the number is even or odd.
- If the number modulo 2 equals 0 (meaning it's divisible by 2 with no remainder), then the condition evaluates to true, and the string "even" is assigned to the result variable.
- If the condition evaluates to false (meaning the number is odd), the string "odd" is assigned to result .
- Finally, the function returns the value of result , which indicates whether the number is even or odd.
This code shows how the ternary operator quickly checks if a number is even or odd, making the code easier to read and understand.
How to Refactor if-else Statements to Ternary Operator
An advantage of the ternary operator is avoiding unnecessary if-else blocks, which can complicate code readability and maintenance. In this section, we'll refactor some if-else statements into ternary operations, providing a clearer understanding of how to use ternary operators effectively.
Let's start with our first example:
This function, decideActivity , takes a weather parameter and determines the appropriate activity based on the weather condition.
If the weather is "sunny", it suggests to "go out". Otherwise, it advises to "stay in". When we call the function with different weather conditions like "raining" or "snowing", it outputs the corresponding activity recommendation using console.log() .
For instance, calling decideActivity("raining") will output "stay in". Similarly, decideActivity("snowing") also outputs "stay in". When decideActivity("sunny") is called, it outputs "go out". This straightforward function helps decide on activities based on the weather condition provided.
Now, we can refactor these blocks of code to make them look simpler and neater. Let's see how to do that below:
From the code sample above, this function, decideActivity , uses the ternary operator to quickly determine the activity based on the weather condition. It checks if the weather is "sunny" and assigns "go out" if true, otherwise "stay in".
We've simplified the if-else statements into a one-liner ternary operator. This makes our code cleaner, clearer, and easier to read.
Let take a look at another example:
Let's explain what the code above is doing:
- Function Definition : We begin by defining a function named checkNumber that takes a single parameter called number .
- Variable Declaration : Inside the function, we declare a variable named result without assigning any value to it yet. This variable will store the result of our check.
- Conditional Statement (if-else) : We have a conditional statement that checks whether the number parameter is greater than 0.
- If the condition is true (meaning the number is positive), we assign the string "positive" to the result variable.
- If the condition is false (meaning the number is not positive, (meaning it is either negative or zero), we assign the string "non-positive" to the result variable.
- Return Statement : Finally, we return the value stored in the result variable.
- Function Calls :We then call the checkNumber function twice with different arguments: 5 and -2.
When we call checkNumber(5) , the function returns "positive", which is then logged to the console.
Similarly, when we call checkNumber(-2) , the function returns "non-positive", which is again logged to the console.
This function efficiently determines whether a number is positive or non-positive and provides the appropriate result based on the condition.
Let's simplify and improve the code by rewriting it using a ternary operator.
Great job! By refactoring the function and utilizing the ternary operator for conditional evaluation, we've achieved cleaner, more concise, and readable code.
This code, using the ternary operator, feels more concise and elegant. It efficiently determines if a number is positive or non-positive, making the code cleaner and easier to understand. When we call checkNumber(5) , it returns "positive", while checkNumber(-2) returns "non-positive". Overall, the ternary operator enhances the code's readability.
When dealing with conditional checks, sometimes a single condition isn't enough. In such cases, we use 'else-if' statements alongside 'if/else' to incorporate multiple conditions.
Let's take a look at the syntax:
This can be translated into an if/else chain:
Let's explore an example below:
This code above defines a function called checkNumber that takes a number parameter and determines its status (positive, zero, or negative). It utilizes an if-else block with one else-if statement to evaluate the number's value. If the number is greater than 0, it's considered positive and if it's equal to 0, it's zero. Otherwise, it's negative. The function returns the result.
Let's refactor this code using a ternary operator to achieve the same functionality.
That's it! We've refactored the function, and upon closer examination, we can observe that the operators are chained together. Now, let's explore how the chained ternary operator works in the checkNumber function.
In the first ternary operator:
- The first part number > 0 checks if the number is greater than 0.
- If it's true, the expression returns "Positive".
In the second ternary operator (chained):
- If the first condition is false (meaning the number is not greater than 0), it moves to the next part of the expression: number === 0 .
- This part checks if the number is equal to 0.
- If it's true, the expression returns "Zero".
And the default value:
- If neither of the above conditions is true (meaning the number is not greater than 0 and not equal to 0), it defaults to the last part of the expression: "Negative" .
- This part acts as the default value if none of the preceding conditions are met.
In summary, the chained ternary operator evaluates multiple conditions in a single line of code. It checks each condition sequentially, and the first condition that evaluates to true determines the result of the entire expression. This allows for concise and efficient conditional logic.
Let's examine another example of a chained ternary operator.
In the given code sample, the ternary operators are chained together to provide different drink suggestions based on the age provided. Each conditional expression in the chain evaluates a specific age range.
If the first condition is true (truthy), it returns 'Enjoy a cocktail'. If false (falsy), it moves to the next conditional expression, and so on. This chaining process continues until a condition evaluates to true. If none of the conditions in the chain are true, the last value is returned as a fallback, similar to the 'else' block in an if/else statement.
The concept of 'chaining' ternary operators involves linking conditional expressions based on the value of the previous expression. This can be compared to the else if structure in an if/else statement, providing a concise way to handle multiple conditions in JavaScript.
Best Practices when Using the Ternary Operator
Using the ternary operator efficiently can significantly enhance code readability and conciseness. In this section, we'll explore key best practices for utilizing the ternary operator effectively.
- Keep it simple and readable : Write concise expressions that are easy to understand at a glance. Avoid nesting too many ternary operators or writing overly complex conditions.
- Use for simple assignments: Ternary operators are ideal for simple assignments where there are only two possible outcomes based on a condition. For more complex scenarios, consider using if/else statements.
- Know when to use it : Use the ternary operator when you need to perform a simple conditional check and assign a value based on the result. It's particularly useful for assigning default values or determining the value of a variable based on a condition.
- Test thoroughly : Test your code thoroughly to ensure that the ternary operator behaves as expected under different conditions. Check for edge cases and validate the correctness of the assigned values.
- Avoid nested ternaries: While chaining ternaries is possible, excessive nesting can lead to code that is difficult to read. Prefer clarity and consider using if/else for complex conditions.
- Keep ternaries short: Aim to keep ternary expressions short and concise. Long ternaries can be difficult to read and understand, leading to code maintenance challenges.
These best practices outline guidelines for effectively utilizing the ternary operator. While they are not strict rules, they offer valuable insights to enhance the clarity and readability of your code.
As we conclude this article, you've gained a comprehensive understanding of the ternary operator—its application in daily coding tasks, converting if/else statements, chaining operators, and best practices. I'm confident that you've acquired valuable insights that will enhance your coding practices using the ternary operator.
Thank you for reading, and see you next time!
Contact information
Would you like to get in touch with me? Don't hesitate to reach out through any of the following channels:
- Twitter / X: @developeraspire
- Email: [email protected]
A Frontend & Mobile Engineer with over 4 years of experience in the industry, I am passionate about creating engaging, user-friendly, and high-performing websites, mobile and web applications.
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
IMAGES
VIDEO
COMMENTS
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement. condition ? expr1 : expr2 If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.
In this article, we'll explore how so-called conditional statements work in JavaScript. A basic understanding of HTML, CSS, and JavaScript first steps. To understand how to use conditional structures in JavaScript. You can have it on one condition!
The Ternary Operator in JavaScript is a shortcut for writing simple if-else statements. It’s also known as the Conditional Operator because it works based on a condition. The ternary operator allows you to quickly decide between two values depending on whether a condition is true or false. [GFGTABS]
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x.
The ternary operator (?:), also known as the conditional operator, is a shorthand way of writing conditional statements in JavaScript – you can use a ternary operator instead of an if..else statement.
What is a Ternary operator? A ternary operator evaluates a condition and executes a block of code based on the condition. Its syntax is: The ternary operator evaluates the test condition. If the condition is true, expression1 is executed. If the condition is false, expression2 is executed.
Summary: in this tutorial, you will learn how to use the JavaScript ternary operator to make your code more concise. When you want to execute a block if a condition evaluates to true, you often use an if…else statement. For example: let message; if (age >= 16) { message = 'You can drive.'; message = 'You cannot drive.';
Know when to use it: Use the ternary operator when you need to perform a simple conditional check and assign a value based on the result. It's particularly useful for assigning default values or determining the value of a variable based on a condition.