📒
SDV503
  • SDV503
  • Command Prompt
    • Windows Command Prompt
    • Mac OS Terminal
  • GIT & GITHub
    • GitHub
    • Git
      • Git Workflow
        • Forking Workflow
  • README
    • How to write a readme.md file?
    • Write a better README.me
    • Generate a README for GitHub Repo Quickly
  • Code-comments
    • Clean Comments
    • Writing Comments in a Good way
  • Pair Coding
    • What is Pair Coding?
    • Pair Programming Experience
  • Programming?
    • What is Programming?
    • What Is A Programming Paradigm?
    • JavaScript Programming Paradigms
  • Number Systems
    • Decimal and Binary numbers
  • JavaSCript
    • Introduction To JavaScript
      • The JavaScript Engine
  • JS Call Stack
    • JavaScript call stack
    • JavaScript & Memory
      • Memory Leaks in JavaScript
    • Execution Context and Execution Stack in Javascript
      • Javascript Execution Context and Hoisting
  • JavaScript Variables
    • Introduction to JS Data Types
    • Primitive and Non-Primitive
    • Operator precedence and associativity
      • JS Operators Part One
      • JS Operators Part Two
      • JS Operators Part Three
    • Clean Code for JS Variables
  • JavaScript Scopes
    • Scope (Chain) Visualized
  • Javascript  — this keyword
  • JavaScript Data Types
    • More JavaScript Data Types
  • JavaScript Expressions and Statements
  • if/else, switch and ternary operator
    • If/Else statement
  • Switch Statement
  • Ternary Operator
  • JavaScript Loops
    • Loops in JavaScript
      • Trouble With Loops
  • Objects
    • JavaScript Objects
      • Prototypal Inheritance Visualized
      • JavaScript Number Object
      • JavaScript String Object
  • Functions
    • JavaScript Function Part One
    • JavaScript Function Part Two
    • Immediately Invoked Function Expressions ~ IIFE
    • JS => Arrow Functions
    • JavaScript Callback
    • Hoisting in JavaScript
      • Hoisting Visualized
    • Recursion Functions
    • Curry and Function Composition
  • JavaScript Features
    • JSpread Operator
    • JavaScript Built-in Functions & Objects
  • Data Structures&Algorithms
    • JavaScript’s Data Types
    • Data Structures in JavaScript
      • Introduction to Big O Notation
      • Big O Notation in Javascript
      • Linked Lists
        • Linked Lists — 2
      • Hash Tables
      • Stack & Queue
  • TLDR
    • Single quotes (‘ ’) and double quotes (“ ”) in JavaScript
  • ES6
    • Generators and Iterators
    • Javascript Classes
    • JavaScript closures
    • JavaScript Promises & Async/Await
      • Event Loop Visualized
  • C#
    • What does C#? (C Sharp)
    • C# vs JavaScript
    • What Is The Difference Between C#, .NET, ASP.NET, Microsoft.NET, and Visual Studio?
    • What is the .NET Framework?
    • Methods and Properties of Console Class in C#
    • Datatypes in C#
    • C# Code Comments
    • The if statement
    • The switch statement
    • Loops
    • Comparison operators
    • Addition assignment operators
    • The String Interpolation Operator
    • Arrays
    • Lists
    • Dictionaries
Powered by GitBook
On this page
  • The if/else statement
  • Comparison operators
  • === vs == (or !== vs !=)
  • Comparing objects and arrays
  • Truthy and Falsy

Was this helpful?

  1. if/else, switch and ternary operator

If/Else statement

The if/else statement

The if/else statement helps to control what your program does in specified situations. It looks like this:

if (condition) {   
  // Do something 
} else {   
  // Do some other thing 
}

The condition tells JavaScript what to check for before continuing. If the condition evaluates to true, JavaScript executes the code within the if block.

If the condition evaluates to false, JavaScript executes code from the else block.

In a traffic light example, we check whether the light is red:

// Note: This example doesn't contain valid code yet 
if (light is red) {
  stop walking 
} else {
  continue walking 
}

If you need to check for more than one condition, you can use else if, which goes between if and else.

When would you need such a second condition?

Well, let’s say you want to cross a small road. If there aren’t any cars around, would you wait for the traffic light to turn green? You still cross, don’t you?

In code, this would look like:

if (light is red) { 
  // Stop walking 
} else if (cars around) { 
  // Stop walking 
} else if (yet another condition) { 
  // Do yet another thing 
} else { 
  // Do the final thing 
}

In this case, if the first condition evaluates to true, JavaScript executes the code in the if block.

If the first condition evaluates to false, JavaScript checks the condition in the next else if block and sees whether it evaluates to true. It goes on and on until all else if blocks are exhausted.

To check whether a condition evaluates to true or false, JavaScript relies on two things:

  1. Comparison operators

  2. Truthy and falsy values

Comparison operators

There are four main types of comparison operators:

  1. Greater than (>) or greater or equal to (>=)

  2. Smaller than (<) or smaller or equal to (<=)

  3. Strictly equal (===) or equal ==

  4. Strictly unequal (!==) or unequal !=

The first two types of comparison operators are straightforward. You use them to compare numbers.

24 > 23 // True 
24 > 24 // False 
24 >= 24 // True 24 < 25 // True 
24 < 24 // False 
24 <= 24 // True

The next two types of comparison operators are quite straightforward as well. You use them to check whether things are equal or unequal to each other.

24 === 24 // True 
24 !== 24 // False

However, there’s a difference between strictly equal (===) vs equal (==), and strictly unequal (!==) vs unequal (!=):

'24' === 24 // False 
'24' == 24 // True '24' !== 24 // True 
'24' != 24 // False

As you can see from the example above, when you compare a string of 24 vs the number 24, === evaluates to false while == evaluates to true.

Why is this so? Let’s look at the difference between strictly equal and equal.

=== vs == (or !== vs !=)

JavaScript is a loosely-typed language. What this means is that, when we declare variables, we don’t care what type of value goes into the variable.

You can declare any primitive or object, and JavaScript does the rest for you automatically:

const aString = 'Some string' 
const aNumber = 123 
const aBoolean = true

When comparing things with strictly equal (===) or strictly unequal (!==), JavaScript checks the type of variable. This is why a string of 24 and a number 24 do not equate.

'24' === 24 // False 
'24' !== 24 // True

When comparing things with equal (==) or unequal (!=), JavaScript converts (or casts) the types so they match each other.

Generally, JavaScript tries to convert all types to numbers when you use a conversion operator. In the example below, the string 24 is converted into the number 24 before the comparison.

That’s why a string of 24 equates to a number of 24 when you use ==.

'24' == 24 // True 
'24' != 24 // False

Booleans can also be converted into numbers. When JavaScript converts Booleans into numbers, true becomes 1 and false becomes 0.

0 == false // True 
1 == true // True 
2 == true // False

Automatic type conversion (when using comparison operators) is one of the common causes of hard-to-find bugs. Whenever you compare for equality, always use the strict versions (=== or !==).

Comparing objects and arrays

Try comparing objects and arrays with === or ==. You’ll be very surprised.

const a = { isHavingFun: true } 
const b = { isHavingFun: true } console.log(a === b) // false 
console.log(a == b) // false

In the example above, both a and b look exactly the same. They are both objects, they have the same values.

The strange thing is, a === b is always going to be false. Why?

Let’s say you have an identical twin brother/sister. You look exactly the same as your twin. Same hair color, same face, same clothes, same everything. How can people differentiate the two of you? It’ll be hard.

In JavaScript, each object has an “identity card.” This identity card is called the reference to the object. When you compare objects with equality operators, you’re asking JavaScript to check if the two objects have the same reference (same identity card).

Is it a surprise that a === b is always going to be false now?

Let’s tweak it a little and assign a to b.

const a = { isHavingFun: true } 
const b = a

In this case, a === b evaluates to true because b now points to the same reference as a.

console.log(a === b) // true

Truthy and Falsy

If you write a single variable (like hasApples in the example below) as the condition of an if/else statement, JavaScript checks for a truthy or a falsy value.

const hasApples = 'true' if (hasApples) { 
  // Eat apple 
} else { 
  // Buy apples 
}

A falsy value is a value that evaluates to false when converted into a boolean. There are six possible falsy values in JavaScript:

  1. false

  2. undefined

  3. null

  4. 0 (numeric zero)

  5. "" (empty string)

  6. NaN (Not A Number)

A truthy value, on the other hand, is a value that evaluates to true when converted into a Boolean. In the case of numbers, anything that’s not 0 converts to true.

Automatic type conversion to truthy and falsy values are highly encouraged in JavaScript, because they make code shorter and easier to comprehend.

For example, if you want to check if a string is empty, you can use the string in the condition straightaway.

const str = '' if (str) { 
  // Do something if string is not empty 
} else { 
  // Do something if string is empty 
}

if/else statements are used to control what your program does in specific situations. It lets you determine whether to walk or cross the road, depending on the conditions given to you.

To check if a condition is true or false, Javascript relies on two things:

  1. comparison operators

  2. truthy/falsy values

PreviousJavaScript Expressions and StatementsNextSwitch Statement

Last updated 5 years ago

Was this helpful?