Javascript questionmark operator5/31/2023 If the condition is true, value1 is returned. The condition is a statement that returns true or false. This operator can save you time and lines of code. It's the only one JavaScript currently has, though. JavaScript’s question mark is commonly used in the ternary operator, which is an abbreviated version of an if-else statement. They can even be chained: serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine') īe careful, though, or you will end up with convoluted code like this: var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j ġ Often called "the ternary operator," but in fact it's just a ternary operator. Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification: userIsYoungerThan21 ? serveGrapeJuice() : serveWine() ServeDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine") This can be shortened with the ?: like so: var userType = userIsYoungerThan18 ? "Minor" : "Adult" Here is an example of code that could be shortened with the conditional operator: var userType This is a one-line shorthand for an if-else statement.
0 Comments
Leave a Reply. |