3
Ternary Operators © Copyright 2014, Fred McClurg All Rights Reserved

Ternary Operators © Copyright 2014, Fred McClurg All Rights Reserved

Embed Size (px)

Citation preview

Page 1: Ternary Operators © Copyright 2014, Fred McClurg All Rights Reserved

Ternary Operators

© Copyright 2014, Fred McClurg All Rights Reserved

Page 2: Ternary Operators © Copyright 2014, Fred McClurg All Rights Reserved

2

Ternary Operator: “if” Shortcut

Description:

Abbreviated notation of the “if” condition. Often used on one line. Used for returning a value upon a true or false condition.

Syntax:

condition ? trueValue : elseValue ;

Page 3: Ternary Operators © Copyright 2014, Fred McClurg All Rights Reserved

3

Simple Ternary Operator

var word = "Alumn";var totalCount = 4;var maleCount = 1;

if ( maleCount >= 1 ) { // use masculine tense // append singular or plural ending word += ( totalCount == 1 ) ? "us" : "i";} else { // use feminine tense // append singular or plural ending word += ( totalCount == 1 ) ? "a" : "ae";}

var report = word + " attended: " + totalCount;console.log( report ); ternary.html