code

JavaScript If Statements

// Use Conditional Logic with If Statements

/*
If statements are used to make decisions in code. The keyword if tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as Boolean conditions and they may only be true or false.

When the condition evaluates to true, the program executes the statement inside the curly braces. When the Boolean condition evaluates to false, the statement inside the curly braces will not execute.

/*NOTE Boolean is true or false*/

if (condition is true) {
  statement is executed
}
*/

function test (myCondition) {
  if (myCondition) {
     return "It was true";
  }
  return "It was false";
}
test(true);
test(false);

function equalityTest(myVal) {
  if (myVal == 10) {
     return "Equal";
  }
  return "Not Equal";
}

// Comparison with the Strict Equality Operator

/*Strict equality (===) is the counterpart to the equality operator (==). However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.

If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.*/

3 ===  3
3 === '3'

function testNotEqual(val) {
  if (val) { // Change this line
    return "Not Equal";
  }
  return "Equal";
}

testNotEqual(10);

// Comparison with the Strict Inequality Operator

3 !==  3
3 !== '3'
4 !==  3

// Comparison with the Greater Than Operator

5   >  3
7   > '3'
2   >  3
'1' >  9

// Comparisons with the Logical And Operator

if (num > 5 && num < 10) {
  return "Yes";
}
return "No";

// Comparisons with the Logical Or Operator

if (num > 10 || num < 5) {
  return "No";
}
return "Yes";

// Else Statements

if (num > 10) {
  return "Bigger than 10";
} else {
  return "10 or Less";
}

// Else-If Statements

if (num > 15) {
  return "Bigger than 15";
} else if (num < 5) {
  return "Smaller than 5";
} else {
  return "Between 5 and 15";
}

Leave a Reply

Matt is the author of five Apress books including Learn RStudio IDE, Quick, Effective, and Productive Data Science, Objective-C Recipes, Swift Quick Syntax Reference, Objective-C Quick Reference, and the upcoming Pro Data Visualization with R and JavaScript. He has over 20 years of experience in technology, psychometrics, and data analytics working in major higher education institutions such as The College Board and Educational Testing Service. He has earned a Master’s degree in Information Systems Management and a Bachelor’s degree in Quantitative Psychology.