Comparison operators, if..else

  1. Logical conditions
  2. Boolean conversions
  3. String comparison
  4. Comparison of different types
  5. Strict equality
  6. Special values
  7. Ternary operator "?"

The if..else construct checks for a condition and executes different code whenever it is true or false.

Most well-known comparison operators are:

  • ==
  • >, <, >=, <=

The if operator checks it and executes the code if the condition is correct, or in other words, true:

if (price > 100) {
  alert('Expensive!')
}

The else block is executed when the condition is wrong or, in other words, false:

if (price > 100) {
  alert('Expensive!')
} else {
  alert('Give me 2!')
}

It is also possible to specify additional conditions using else if:

var access  // the access level of the user based on his userId

if (userId > 1) {
  access = "visitor";
} else if (userId == 1) {
  access = "superuser";
} else if (userId == 0) {
  access = "all-powered-genie";
}

Write the code to prompt user for a value, and alert:

  • 1, if the value is greater than zero,
  • -1, if the value is less than zero,
  • 0, if the value is zero.

See it in action here: tutorial/intro/if_sign.html

Open solution

Logical conditions

Conditions can be combined by operators && (AND), || (OR) or negated by !(NOT).

Check if x is more than 1 AND less than 5:

var x = 3

if (x>=1 && x<=5) {
  alert('The number is between 1 and 5')
}

Check if x is less than 10 OR more than 20:

var x = 3

if (x<10 || x>20) {
  alert('The number is outside of 10..20 interval')
}

Conditions can be grouped in brackets and negated by NOT:

var x = 15

if ( !(x<10 || x>20) ) {
  alert('The number is *inside* 10..20')
}

Write the code to prompt for a login.

If the input is “Monty”, then promptfor a password, for any other input alert “Wrong login”. If the user presses CANCEL (or Escape), do nothing.

If the password is “Cheese”, then output “Access granted”, otherwise output “Wrong password”.

See it in action here: tutorial/intro/if_pass.html

Open hint 1
Hint 1
Open solution
Solution
The solution is based on nested `if`: Open it at [play src="tutorial/intro/if_pass.html"]. Please, pay attention to code formatting and extra line spaces in high-level `if`. **Spaces are sweet for better readability.**

Warning! The task below looks complicated Wink


Write the code to prompt for a login.

If the input is ”Monty” or “Chip”, then prompt for a password, for any other input alert “Wrong login”. If the user presses CANCEL (or Escape), do nothing.

If the password is ”Cheese” for Monty and “Gadget” for Chip, then output “Access granted”, otherwise output “Wrong password”.

See it in action here: tutorial/intro/if_pass2.html

Open hint 1
Hint 1
Open solution
Solution

The solution is based on nested if:

Open it at tutorial/intro/if_pass2.html. Please, pay attention to code formatting and extra line spaces in high-level if. Spaces are sweet for better readability.

Boolean conversions

Traditionally, it is possible to put a value into if. In this case, it gets converted into boolean.

var x = 1

if (x) {
  alert('true')
}

String comparison

String are compared in lexicographic order, also known as a phone-book order:

// true, because "Anna" would go after "Abba" in a phone book. 
alert( "Anna" > "Abba" )  // true

  1. The first character of the left string is compared against the first character of the right string.
  2. If it is greater or less in alphabet order, then it becomes the result.
  3. If they are equal, then go on to the next character.

No-character is less than any character. That’s, again, like in the phone-book:

// Pope would go after Pop 
alert( "Pope" > "Pop" )  // true

For strings, the comparison is case-sensivite.

For example:

alert('abba' > 'Zend') // true

That’s because a lowercased letter is always greater than an uppercased.

Comparison of different types

Comparison can be done for values of different types. To perform the comparison, the interpreter converts values to numbers.

Here are the examples:

alert("01" < 2)   // true, "01" converts to 1
alert(1 == true)  // true, because true converts to 1

Watch out when comparing numbers which you got as strings:

alert( "2" > "14" ) // true

That’s because of lexicographical order. Convert the values explicitly to make sure you are dealing with numbers.

Strict equality

Sometimes we need to differ between 0 and false. How to check that?

alert(0 == false) // true, because false becomes 0

For such occasions, there are strict equality and inequality operators: === and !==.

They do not convert type, so values of different types are always inequal.

alert(0 === false) // false, because different types

Special values

Special values are inclined to really weird behavior in comparisons.

Here is a couple of examples.

Crazy?

Come on, check it out:

alert(null > 0); // false
alert(null == 0); // false

And now tadaaaam:

alert(null >= 0); // true 8-()

How can it be? It’s not greater, not equal, but >= returns true.

Hint. Processing of null is hardcoded. See ECMA-262 standard for the details. Hope you’ll never get into this pitfall.

Uncomparable

Undefined and NaN values can’t be compared with a number.

alert(undefined > 0); // false
alert(undefined  == 0); // false
alert(undefined  < 0); // false

Use strict comparisons === to check against undefined.

But even a strict comparison fails with NaN, use isNaN() function to check it.

Why does it behave like that? The short answer is: “because that’s written in the standard”. A longer one is “JavaScript was created in 10 days. What you’d await?”.

Ternary operator "?"

A regular use-case is when a variable gets a value depending on a condition:

if (cash > 100) {
  me = "Rich"
} else {
  me = "Poor"
}

The ternary operator comes in as a handy shortcut. The syntax is:
result = condition ? value_if_true : value_if_false.

It evaluates the condition and returns the value_if_true value if it is correct or value_if_false otherwise.

The if can be rewritten as:

me = (cash > 100) ? 'Rich' : 'Poor'

Brackets around cash > 100 can be safely removed, because operator “?” has lower priority. But they are usually kept for readability.

The following statements are equal:

rich = (money > 10) ? true : false
// same as
rich = money > 10

Another example, getting the absolute value of x:

abs = (x > 0) ? x : -x

Tutorial

Donate

Donate to this project