Newby Coder header banner

Javascript Conditions


if - else statements

Basic syntax

if (condition) {
  //code to run if condition is true
} else {
  //code to run if condition is not true
}

It contains :

  1. keyword if followed by some parentheses
  2. A condition(also can be called as expression) to test , placed inside parentheses, might make use of comparison operators and returns true or false
  3. A set of curly braces, with some code inside, to be run if condition returns true
  4. else keyword
  5. Another set of curly braces, with code inside, to be run if condition is false

else part isn't a requirement :

if (condition) {
  //code to run if condition is true
}
//code not dependent on above if condition

if - else statements can be written without curly braces, in case their corresponding code can be written in a single statement:

if (navigator.platform.indexOf('linux') != -1) isLinux = true;
else console.log("Error: not linux");

else if

else if is used to add additional blocks between an if and else block

var n = 1332;
if(n === 1) {
	console.log("One");
}
else if (n === 2) {
	console.log("Two");
}
else if (n === 3) {
	console.log("Three");
}
else {
	console.log("not one, two or three, what is it?");
}

Comparison operators are used to test conditions inside conditional statements

Any value that is not false, undefined, null, 0, NaN, or an empty string ('') returns true when tested as a conditional statement

Therefore a variable name can be used on its own to test whether it is true, or even that it exists (i.e. it is not undefined)

var x = 'what';
if (x) {
  console.log('x is something');
} else {
  console.log('ain't no x there ');
}

Since x is declared, it returns x is something


Nesting if - else

One if - else statement can be put inside another one — to nest them

Following example checks whether a number is positive, negative or 0

# define function to check number
function check_number(num) {
    if (num >= 0) {
        if (num == 0)
            console.log(num, "is the zero");
        else
            console.log(num, "is a positive number");
	}
    else
        console.log(num, "is a negative number");
}

check_number(0.1);
check_number(-5);
check_number(0);

Output

0.1 is a positive number
-5 is a negative number
0 is the zero

Logical operators: AND, OR and NOT

logical operators can be used to test multiple conditions

When used in conditions, the first two do the following:

Example :

if (username === undefined || username.trim().length === 0) {
  alert('Error: empty username');
}
else if (username.length <= 4 && username.indexOf('slang') != -1) {
  alert("Don't use slang in short username");
} 

switch statements

switch statements take a single expression/value as an input, and then look through a number of choices until they find one that matches that value, executing corresponding code that goes along with it

switch (expression) {
  case choice1:
    run this code
    break;

  case choice2:
    run this code instead
    break;

  // include more cases as necessary

  default:
    run this code if no break statement gets executed
}

Above contains :

  1. The keyword switch, followed by parentheses
  2. An expression or value inside the parentheses
  3. The keyword case, followed by a choice that the expression/value could be, followed by a colon
  4. Some code to run if this choice matches expression
  5. A break statement, followed by a semi-colon
  6. If previous choice matches expression/value, browser stops executing code block here, and moves on to any code that appears below the switch statement
  7. As many other cases (bullets 3–5) as required
  8. The keyword default, followed some code, acting as default option that runs if no choice matches

Note: default section — is not mandatory and can be omitted

however, it can be of use to include it to handle unknown cases

switch example
switch (x) {
    case 1:
      para.textContent = 'got one';
      break;
    case 2:
      para.textContent = 'Numerical Two';
      break;
    case 'Three':
      para.textContent = 'Alphabetical 3';
      break;
    default:
      para.textContent = "ain't no case for x, didn't break anything";
}

Ternary operator

ternary or conditional operator is a syntax that

This is typically used as shorthand of an if else block since it takes up lesser code

( condition ) ? run this code : run this code instead

Example

var fontColor = ( backgroundColor == "white" ) ? 'black' : 'white';

Here, value of a variable backgroundColor is checked

If it is white then value of fontColor is set to black

Otherwise, value of fontColor is set to black