Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    6Topics
    |
    6 Quizzes
Lesson 3, Topic 6
In Progress

JavaScript: Truthy and Falsy

Yasin Cakal 31 Oct 2021
Lesson Progress
0% Complete

Consider how non-boolean data types, such as strings and numbers, are evaluated within a condition.

You might want to check if a variable exists, but you don’t necessarily want it to have a specific value — you just want to see if it has been assigned one.

let newVariable = 'The variable exist!';
 
if (newVariable) {
   console.log(newVariable)
} else {
   console.log('The variable does not exist.')
}


//Output: The variable exist!

The if statement’s code block will execute because newVariable has a truthy value; even though newVariable‘s value is not explicitly true, it evaluates to true when used in a boolean or conditional context because it has been assigned a non-falsy value.

So, which values are false—or, when checked as a condition, evaluate to false? The following are examples of falsy values:

  1. 0
  2. Empty strings such as “
  3. undefined, which denotes the absence of a value for a declared variable.
  4. null, which denotes the absence of any value 
  5. NaN, or Not a Number

Here’s an example with numbers:

let numberOfPen = 2;
 
if (numberOfPen){
   console.log('Lets write diary!');
} else {
   console.log('No pen left!');
}
 
// Prints 'Lets write diary!'

Because the value of numberOfPen is 2, the condition evaluates to true. Because 2 is a true value, the if statement’s code block will execute.

Responses

Leave a Reply

%d bloggers like this: