TomRed.net

  • Increase font size
  • Default font size
  • Decrease font size
Subscribe Bookmark and Share
Home Tutorials JavaScript JavaScript If Else using Conditional Operators (?:)

JavaScript If Else using Conditional Operators (?:)

User Rating: / 0
PoorBest 

It is often useful to consolidate your IF statement into a single line, like when you are assigning a value based on an operation.  I have covered the standard use of JavaScript IF ELSE functionality in a separate tutorial JavaScript If, Else and Else If .  Here I am going to cover the Conditional operators ?: these are simple and a favourite time saver when writing JavaScript.  I am going to cover the same problem as the "Do Something 4" example in the previous tutorial.

Essentially we want to evaluate and expression and based on the results of the evaluation do one thing or another.  This is the age old problem with programming,  to reduce the amount of code when doing IF logic we have the ?: conditional operators. 

Standard JavaScript IF ELSE functionality

function doSomethingStandard(){
	var text = "my string";
	if(text === "not my string"){
		alert('var text is equal to "my string"');
	}else{
		alert('var text is not equal to "my string"');
	}
}

Conditional JavaScript ?: functionality

function doSomethingConditional(){
	var text = "my string";
	(text === "not my string") ? alert('var text is equal to "my string"') : alert('var text is not equal to "my string"');
}

Having previous explained the standard IF ELSE functionality I will not discuss that here;  I will though explain what I have done it the second example.  Firstly I would like to point out that the functionality is identical.  Essentially everything before the ? is the expression to be evaluated.  This expression like the standard IF ELSE must evaluate to a Boolean (TRUE or FALSE).  If the value is true then the expression following the ? but before : is run.  If the expression evaluates to false then the expression following the : is run.  It is as simple as that.  Everything after the : is equal to the ELSE.

One thing to stress is that while in the example above I have surrounded the expression before the ? with ( ) parentheses this is not always necessary, I have done so for clarity.  Secondly the statement after the ? but before the : must not be followed by ; (semi-colon) as this will throw an error looking for the :.  Finally remember to close off the statement like anyother in JavaScript with ; (semi-colon) at the end of the statement.

I hope you have found this useful if you have any questions, don't hesitate to leave a comment.