CONDITIONNAL : IF - JS

Tests on empty / non-empty values

Tests on non-null values

/*
 If it's not null, we can return a true
*/

const myVariable = msg.payload.myVariable;
let booleanNotNull;

if (myVariable){
    booleanNotNull = true ;
}

Tests on non empty values

/*
 If it's empty, we can return an empty String 
*/

const myVariable = msg.payload.myVariable;
let booleanNotEmpty;

if (myVariable != ""){
    booleanNotEmpty = true;
}

Tests with numbers

const var1 = 2;
const var2 = 3;

// EQUALITY
if (var1 == var2){  // FALSE
    //...
}

// INEQUALITY
if (var1 != var){ // TRUE
    //...
}

// STRICTLY SUPERIOR
if (var1 > var){ // FALSE
    //...
}

// SUPERIOR OR EQUALS
if (var1 > var){ // FALSE
    //...
}

// INFERIOR OR EQUALS
if (var1 <= var){ // TRUE
    //...
}

Tests with strings

const string1 = "this is my string"
const string2 = "this is a string"

// EQUALITY
if (string1 == string2) { // FALSE
    //...
}

// INEQUALITY
if (string1 != string2) { // TRUE
    //...
}

Operands

/*
    AND
*/
if (var1 == var2 && var2 == var3){
    //....
}

/*
    OR
*/
if (var1 == var2 || var2 == var3){
    //....
}

Switch

const expr = 'Papayas';
switch (expr) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    // expected output: "Mangoes and papayas are $2.79 a pound."
    break;
  default:
    console.log(`Sorry, we are out of ${expr}.`);
}

Was this article helpful?

Powered by Zendesk