Wednesday, October 7, 2020

JavaScript Condition

Like many other programming languages, JavaScript also allows you to write code that performs different actions based on the results of a logical or comparative test conditions at run time. This means you can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions.

There are several conditional statements in JavaScript that you can use to make decisions:

  • The if statement
  • The if...else statement
  • The if...else if....else statement
  • The switch...case statement

We will discuss each of these statements in detail in the coming sections.

The if Statement

The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest JavaScript's conditional statements and can be written like:

if(condition) {
    
// Code to be executed
}

The following example will output "Have a nice weekend!" if the current day is Friday:

Example

var now = new Date();

var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6 

if(dayOfWeek == 5) {

    alert("Have a nice weekend!");

}

 

The if...else Statement

You can enhance the decision making capabilities of your JavaScript program by providing an alternative choice through adding an else statement to the if statement.

The if...else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false. It can be written, like this:

if(condition) {
    
// Code to be executed if condition is true
else {
    
// Code to be executed if condition is false
}

The JavaScript code in the following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output the text "Have a nice day!".

Example

var now = new Date();

var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

if(dayOfWeek == 5) {

    alert("Have a nice weekend!");

} else {

    alert("Have a nice day!");

}

 

The if...else if...else Statement

The if...else if...else a special statement that is used to combine multiple if...else statements.

if(condition1) {
    
// Code to be executed if condition1 is true
else if(condition2) {
    
// Code to be executed if the condition1 is false and condition2 is true
else {
    
// Code to be executed if both condition1 and condition2 are false
}

The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday, otherwise it will output "Have a nice day!"

Example

var now = new Date();

var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

 if(dayOfWeek == 5) {

    alert("Have a nice weekend!");

} else if(dayOfWeek == 0) {

    alert("Have a nice Sunday!");

} else {

    alert("Have a nice day!");

}

You will learn about the JavaScript switch-case statement in the next chapter.

 

The Ternary Operator

The ternary operator provides a shorthand way of writing the if...else statements. The ternary operator is represented by the question mark ( ? ) symbol and it takes three operands: a condition to check, a result for true , and a result for false . Its basic syntax is:

var result = (condition) ? value1 : value2

If the condition is evaluated to true the value1 will be returned, otherwise value2 will be returned. To understand how this operator works, consider the following examples:

Example

var userType;

var age = 21;

if(age < 18) {

    userType = 'Child';

} else {

    userType = 'Adult';

}

alert(userType); // Displays Adult

Using the ternary operator the same code could be written in a more compact way:

Example

var age = 21;

var userType = age < 18 ? 'Child' : 'Adult';

alert(userType); // Displays Adult

As you can see in the above example, since the specified condition evaluated to false the value on the right side of the colon ( : ) is returned, which is the string 'Adult'.

Tip: Code written using the ternary operator can be difficult to read sometimes. However, it provides a great way to write compact if-else statements.

 

JavaScript Comparison


We know many comparison operators from maths.

In JavaScript they are written like this:

  • Greater/less than: a > b, a < b.
  • Greater/less than or equals: a >= b, a <= b.
  • Equals: a == b, please note the double equality sign == means the equality test, while a single one a = b means an assignment.
  • Not equals. In maths, the notation is ≠, but in JavaScript it’s written as a != b.

Boolean is the result

All comparison operators return a boolean value:

  • true – means “yes”, “correct” or “the truth”.
  • false – means “no”, “wrong” or “not the truth”.

For example:

alert( 2 > 1 );  // true (correct)

alert( 2 == 1 ); // false (wrong)

alert( 2 != 1 ); // true (correct)

A comparison result can be assigned to a variable, just like any value: 

let result = 5 > 4; // assign the result of the comparison

alert( result ); // true

 

String comparison

To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or “lexicographical” order.

In other words, strings are compared letter-by-letter.

For example:

alert( 'Z' > 'A' ); // true

alert( 'Glow' > 'Glee' ); // true

alert( 'Bee' > 'Be' ); // true

 

The algorithm to compare two strings is simple:

  1. Compare the first character of both strings.
  2. If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. We’re done.
  3. Otherwise, if both strings’ first characters are the same, compare the second characters the same way.
  4. Repeat until the end of either string.
  5. If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.

In the first example above, the comparison 'Z' > 'A' gets to a result at the first step.

The second comparison 'Glow' and 'Glee' needs more steps as strings are compared character-by-character:

  1. G is the same as G.
  2. l is the same as l.
  3. o is greater than e. Stop here. The first string is greater.

How string comparison play

The comparison algorithm given above is roughly equivalent to the one used in dictionaries or phone books, but it’s not exactly the same.

For instance, case matters. A capital letter "A" is not equal to the lowercase "a". Which one is greater? The lowercase "a". Why? Because the lowercase character has a greater index in the internal encoding table JavaScript uses (Unicode). We’ll get back to specific details and consequences of this in the chapter Strings.

 

Comparison of different types

When comparing values of different types, JavaScript converts the values to numbers.

For example:

alert( '2' > 1 ); // true, string '2' becomes a number 2

alert( '01' == 1 ); // true, string '01' becomes a number 1

For boolean values, true becomes 1 and false becomes 0. 

For example:

alert( true == 1 ); // true

alert( false == 0 ); // true

A funny consequence

It is possible that at the same time:

  • Two values are equal.
  • One of them is true as a boolean and the other one is false as a boolean.

For example:

let a = 0;

alert( Boolean(a) ); // false 

let b = "0";

alert( Boolean(b) ); // true 

alert(a == b); // true!

 

From JavaScript’s standpoint, this result is quite normal. An equality check converts values using the numeric conversion (hence "0" becomes 0), while the explicit Boolean conversion uses another set of rules.


Strict equality

A regular equality check == has a problem. It cannot differentiate 0 from false:

alert( 0 == false ); // true

The same thing happens with an empty string:

alert( '' == false ); // true

This happens because operands of different types are converted to numbers by the equality operator ==. An empty string, just like false, becomes a zero.

What to do if we’d like to differentiate 0 from false? 

A strict equality operator === checks the equality without type conversion.

In other words, if a and b are of different types, then a === b immediately returns false without an attempt to convert them.

Let’s try it: 

alert( 0 === false ); // false, because the types are different

There is also a “strict non-equality” operator !== analogous to !=.

The strict equality operator is a bit longer to write, but makes it obvious what’s going on and leaves less room for errors.


Comparison with null and undefined

There’s a non-intuitive behavior when null or undefined are compared to other values.

For a strict equality check ===

These values are different, because each of them is a different type.

alert( null === undefined ); // false 

For a non-strict check ==

There’s a special rule. These two are a “sweet couple”: they equal each other (in the sense of ==), but not any other value.

alert( null == undefined ); // true 

For maths and other comparisons < > <= >=

null/undefined are converted to numbers: null becomes 0, while undefined becomes NaN.


Tuesday, October 6, 2020

JavaScript Boolean

JavaScript provides a boolean primitive type that has two values of true and false. The following example declares two variables that hold boolean values of false and true: 

let isPending = false;

let isDone = true;


When you apply the typeof operator to a variable that holds primitive boolean value, you get the boolean as the following example:

console.log(typeof(isPending)); //  boolean

console.log(typeof(isDone));    // boolean 

 

JavaScript Boolean object

In addition to the boolean primitive type, JavaScript also provides you with the global Boolean() function, with the letter B in uppercase, to cast a value of another type to boolean.


The following example shows you how to use the Boolean()  function to convert a string into a boolean value. Because the string is not empty, therefore it returns true.

let a = Boolean('Hi');

console.log(a); // true

console.log(typeof(a)); // boolean


The Boolean is also a wrapper object of the boolean primitive type. It means that when you use the Boolean constructor and pass in either true or false, you create a Boolean object.

let b = new Boolean(false);


To get the primitive value back, you call the valueOf() method of the Boolean object as follows:

console.log(b.valueOf()); // false


However, if you call the toString() method of a Boolean object, you get a string value "true" or "false". See the following example.

console.log(b.toString()); // "false"



The  typeof of Boolean object returns object, whereas the  typeof of a primitive boolean value returns boolean.

console.log(typeof foo); // boolean

console.log(typeof bar); // object



When applying the instanceof operator to a Boolean object, it returns true. However, it returns false if you apply the instanceof operator to a boolean value.

console.log(foo instanceof Boolean); // false

console.log(bar instanceof Boolean); // true


It is a good practice to never use the Boolean object because it will create much confusion especially when you use it in an expression. See the following example.

let falseObj = new Boolean(false);

if (falseObj) {

     console.log("weird part of the Boolean object");

}

How the script works.

  • First, create falseObj as a Boolean object wrapper for the false value.
  • Second, use falseObj in the  if statement. Because falseObj is an object, and JavaScript engine coerces it to a boolean value of true. As a result, the statement inside the if block is executed.