Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an inline IF statement in JavaScript?

How can I use an inline if statement in JavaScript? Is there an inline else statement too?

Something like this:

var a = 2; var b = 3;  if(a < b) {     // do something } 
like image 683
takeItEasy Avatar asked Apr 22 '12 17:04

takeItEasy


People also ask

How do you write an inline if in JavaScript?

Method 1: In this method we write an inline IF statement Without else, only by using the statement given below. Method 2: In this method, we will use ternary operator to write inline if statement. Syntax: result = condition ?

What is an inline if statement?

It is commonly referred to as the conditional operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c . One can read it aloud as "if a then b otherwise c".

Can I use && in if statement in JavaScript?

In the logical AND ( && ) operator, if both conditions are true , then the if block will be executed. If one or both of the conditions are false , then the else block will be executed.

What is inline function in JavaScript?

An inline function is a javascript function, which is assigned to a variable created at runtime. You can difference Inline Functions easily with Anonymous since an inline function is assigned to a variable and can be easily reused.


1 Answers

You don't necessarily need jQuery. JavaScript alone will do this.

var a = 2; var b = 3;     var c = ((a < b) ? 'minor' : 'major'); 

The c variable will be minor if the value is true, and major if the value is false.


This is known as a Conditional (ternary) Operator.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator

like image 93
MattW Avatar answered Sep 23 '22 02:09

MattW