JavaScript Basics | Statements and Operators cover image

JavaScript Basics | Statements and Operators

Jonathan Barrios β€’ September 4, 2020

javascript

Introduction

Welcome to the JavaScript Basics series for beginners. In Part 4, we'll focus on Statements and Operators from if-else statements to short-circuiting. See you there!

Prerequisites

To get the most out of this course, you should know:

In Part 4 of JavaScript Basics, we'll focus on:

In future JavaScript Basics posts, we will:

Note: It takes years of focused practice to become a great JavaScript engineer. This JavaScript Basics course is an introduction to JavaScript fundamentals and will improve your coding skills, but don't expect to transform into a JavaScript expert overnight instantly. Remember, the JavaScript learning journey is a marathon, not a sprint.

Statements and Operators

In this section, we'll dive into if and else statements which evaluate a condition and carry out an action, if the condition is true, else it may carry out another action. We'll also explore comparisons, logical and tertiary operators, and how to use them.

The if-else statement

So what does an if statement actually do? The if statement checks to see if the condition is true and will only execute if true. The else statement handles what to do when an if statement returns false. To illustrate this, here are two examples, an if statement followed by an if-else statement.

if (true) {
  console.log('True');
}

// Else
if (false) {
  console.log('if statement ran');
} else {
  console.log('else statement ran');
}

In the second example, you can see that the condition evaluated to false, allowing the else statement to execute.

Comparison Operators

The equality operators == and != are Boolean types, which evaluate if the comparisons are true. To check the equality of value and type, use ===, !==. Variable assignment with = is not the same thing, so let's start with a variable assignment example followed by comparisons.

// Not an equality operator, just declaring a variable
const price = 5;

// Equal Value
if (price == 5) {
  console.log('True');
}

// Not Equal Value
if (price != 5) {
  console.log('True');
} else {
  console.log('False');
}

// Equal Value & Type
if (price === 5) {
  console.log('True');
}

// Not Equal Value & Type
if (price !== 5) {
  console.log('True');
} else {
  console.log('False');
}

if (price === '5') {
  console.log('True');
} else {
  console.log('False, strings and integers are not the same type');
}

// Less than
if (price < 5) {
  console.log('True');
} else {
  console.log('False');
}
// Greater than
if (price > 5) {
  console.log('True');
} else {
  console.log('False');
}

// Greater than or equal to
if (price >= 5) {
  console.log('True');
} else {
  console.log('False');
}

// Else If
const color = 'red';
if (color === 'red') {
  console.log('Red');
} else if (color === 'green') {
  console.log('Green');
} else {
  console.log('no idea');
}

// Logical Operators

// AND &&
const price = 99;
if (price <= 5 && price >= 2) {
  console.log(`${price} is in between 2 and 5`);
} else {
  console.log(`${price} is not between 2 and 5`);
}
// OR ||
if (price === 99 || price === 0) {
  console.log(`${price} is one of the numbers`);
} else {
  console.log(`${price} is not one of the numbers`);
}

// Ternary Operators
console.log(price === 100 ? 'Yes' : 'No');

Switches

A switch statement evaluates

let price = prompt('Enter a number under 11');

switch (Number(price)) {
  case 1:
    console.log(`Yes, the number is ${price}`);
    break;
  case 5:
    console.log(`Yes, the number is ${price}`);
    break;
  case 10:
    console.log(`Yes, the number is ${price}`);
    break;
  default:
    console.log('Try again.');
}

Truthy vs. Falsy

A solid understanding of truthy and falsy is a crucial skill for JavaScript developers. To accurately predict conditional statements' outcome, you will need to understand truthy and falsy statements in the context of type coercion––think like a computer, "affirmative".

Keep in mind that the if() statement is always trying to make the condition return a boolean value, much like the Boolean() function behaves. For example, "Hi" is not a boolean value, so the if() statement will coerce that value to determine if the value is true or false. What is the boolean value of "Hi"? Let's try it out.

if ('Hi') {
  console.log('Yes.'); // Returns True
} else {
  console.log('No.');
}
console.log(Boolean('Hi'));

if (0) {
  console.log('Yes.');
} else {
  console.log('No.');
} // Returns False

The non-boolean value of "Hi" returned true because it was not a falsy value. When we tried 0, it returned false because 0 is clearly false. If you're wondering how to keep all of these falsy values in your mind, remember these six falsy values and consider everything else as truthy:

The takeaway here is to avoid direct comparisons to a boolean, for example:

const authenticated = "
if (authenticated === false) {
}
//  Instead use this
if (!authenticated) {
}
// Same for the opposite
const authenticated = ''
if (authenticated === true) {
}
//  Instead use this
if (authenticated) {
}

Also, try to use === whenever possible instead of the == because === does not allow type conversion.

if (undefined == null) {
  console.log('Same?');
} else {
  console.log('Not same');
}

Clearly, undefined and null are not the same type, so use === whenever possible.

if (undefined === null) {
  console.log('Same?');
} else {
  console.log('Not same');
}

Short-circuiting

const response = prompt('Enter anything');
const username = response || 'Guest'; // This is short-circuiting
console.log(username);

If the user does not enter a responce, username = 'Guest' and if the user enters a name, like Jonathan, then username = 'Jonathan'. Try both entering a name and not entering anything. πŸ™ŒπŸΌ

Now that you finished the statements and operators portion of JavaSctipt Basics, we'll begin learning all about JavaScript functions in Part 5. Follow me on Twitter @_jonathan_codes for more JavaScript Basics and other web development frameworks, databases, and more. As always, Happy coding! πŸ‘‹πŸΌ