Logo


ternary operator in javascript

Ternary operator in javaScript


In simple words ternary operator is if else of javascript but it is inline. It has tree blocks, one is condition, second block will be return if condistion is true and third block will return if condition is false.The following ternary condition works such that if userAuth is true, then msg will be set to welcome. Otherwise, the value will be restricted.


In the below example we are setting value to msg variable based on certian condition. If auth is true then 'welcome' will be store in msg otherwise 'restricted' will be store.

1let msg = (userAuth) ? 'welcome' : 'restricted'

The above example equivalent to the following if else statements

1let msg = ''
2if (userAuth) {
3msg = 'welcome'
4} else {
5msg = 'restricted'
6}

In some cases, the ternary (?) operator is a shorter version of if/else. But there’s a big difference between them if you try to use the ternary operator as an expression (where it returns a value). This code is valid JS:



About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share