Skip to content

1.7 Conditional Statements -3-

Short way: Ternary Operator

Task 1: if the student's mark is greater than 60, he/she passes the exam; otherwise, he/she fails.

var mark = 70;
if(mark > 60){
  var pass = true;
}else{
  var pass = false;
}
console.log(pass);

You will get: true.

Task 2: We re-wrote the code in task 1. Check it out:

var mark = 70;
var pass =  mark > 60 ? true : false;
console.log(pass);

You will get: true

What did happen here? mark > 60 ? true : false is the same as the if statement in task 1.

Note(1): condition ? successValue : failureValue is called Ternary Operator or Conditional Operator.

Let's practice more and you will have a better understanding of Ternary Operator.

Task 3: if the value is less than or equal to 30, display "low" in the console; otherwise, display "high".

var value = 50;
if(value <= 30){
  console.log('low');
}else{
  console.log("high");
}

You will get: high.

Now let's use the ternary operator:

var value = 50;
var result = value <=30 ? "low" : "high";
console.log(result);

you will get: high

Task 4: if the user provided a name, set the username to the name + 123; otherwise, set the username to the userEmail.

var name = "Ali";
var userEmail = "mail@gmail.com";
if(name){
    var username = name + 123;
}else{
    var username = userEmail;
}

You will get: Ali123.

You can also write:

var name = "Ali";
var userEmail = "mail@gmail.com";
var username = name? name + 123 : userEmail;

You will get: mail@gmail.com

Task 5: if the password is strong, display "great" in the console; otherwise, display "not secure!".

var isStrong = true;
var message = isStrong ? "great" : "not secure!";
console.log(message);

You will get: great

Task 6: if the temperature is greater than 30, the weather is hot; otherwise, it is okay.

var temp = 20;
var weather = temp > 30 ? "Hot" : "Okay";
console.log(weather);

You will get: Okay

Task 7: if the paragraph has more than 500 words, it is a long paragraph; otherwise, it is short.

var wordsCount = 300;
var isLong = wordsCount > 500 ? true : false;
console.log(isLong);

You will get: false

Task 8: if the YouTube video is longer than or equal to 30, display "Good"; otherwise, "Not Bad".

var videoLength = 40;
var msg = videoLength >= 40 ? "Good" : "Not Bad";
console.log(msg);

You will get: Good