Ternary operator in JavaScript
Link for all dot net and sql server video tutorial playlists http://www.youtube.com/user/kudvenkat/playlists Link for slides, code samples and text version of the video http://csharp-video-tutorials.blogspot.com/2014/11/ternary-operator-in-javascript.html Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help. https://www.youtube.com/channel/UC7sEwIXM_YfAMyonQCrGfWA/?sub_confirmation=1 Ternary operator can be used as a shortcut for if...else... statement. Here is the syntax for the ternary operator Boolean Expression that returns true or false ? Statements to execute if true : Statements to execute if false The following example checks if the number is even or odd. We are using if...else... statement. var userInput = Number(prompt("Please enter a number")); var message = ""; if (userInput % 2 == 0) { message = "Your number is even"; } else { message = "Your number is odd"; } alert(message); Ternary operator example : In the above example if...else... statement can be replaced with the ternary operator as shown below. var userInput = Number(prompt("Please enter a number")); var message = userInput % 2 == 0 ? "Your number is even" : "Your number is odd"; alert(message); Can we have multiple statements per case with a ternary operator Yes, we can put the multiple statements in a bracket and separate them with a comma. Example : var userInput = Number(prompt("Please enter a number")); userInput % 2 == 0 ? (alert("Your number is even"), alert("Your number is " + userInput )) : (alert("Your number is odd"), alert("Your number is " + userInput)); Multiple if..else if... statements can be replaced with ternary operator. The following example displays the month name based on the month number that is provided using if...else if... statement var userInput = Number(prompt("Please enter a month number - 1, 2 or 3")); var monthName = ""; if (userInput == 1) { monthName = "January"; } else if (userInput == 2) { monthName = "February"; } else if (userInput == 3) { monthName = "March"; } else { monthName = "Unknown month number" } alert(monthName); Ternary operator with multiple conditions example : In the following example, if...else if... statements are replaced with ternary operator var userInput = Number(prompt("Please enter a month number - 1, 2 or 3")); var monthName = userInput == 1 ? "January" : userInput == 2 ? "February" : userInput == 3 ? "March" : "Unknown month number"; alert(monthName);
Download
1 formatsVideo Formats
Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.