Understanding Truthy and Falsy Values in JavaScript

In this lesson, we'll discover truthy and falsy values in JavaScript. These values play a fundamental role in the decision-making structures found in code. Unique to programming, these concepts form the basis of how JavaScript and many other programming languages make decisions.

In JavaScript, a value can be considered 'truthy' or 'falsy'. If a value is interpreted as true in a context where a boolean is expected, it is considered 'truthy'. Conversely, if it is interpreted as false, it is considered 'falsy'. For example, 1 (the number one) is truthy, while 0 (the number zero) is falsy. Most values are considered truthy, but others like false, 0, '' or "", null, undefined, and NaN are inherently falsy.

Conditional Statements in JavaScript

Conditional statements give your code the ability to behave differently under various conditions. An "if-else" statement, for instance, executes one block of code if the condition is truthy and another block if it's falsy. The anatomy of if-else statement is shown below:

// Minimal example
if (condition) {
    // Code to execute if the condition is true
}

// An example of standard if-else block
if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if all the above conditions are false
}

// An example of extended if-else block
if (condition) {
    // Code to execute if the condition is true
} else if (anotherCondition) {
    // Code to execute if the first condition is false and the second condition is true
} else {
    // Code to execute if all the above conditions are false
}

In this if statement, the code inside the {} is the block. It only runs if the condition is true, similarly the else branch has its block which runs if the condition is false. In JavaScript, a block refers to a group of code enclosed within curly braces {}. Think of a block like a container that holds related code together. Blocks are important in JavaScript because they define the scope of different code statements, which means they control where certain variables and functions can be accessed and used in your code.

Let's consider an example we all could relate to, an online test score updater:

let score = 85;

if (score > 50) { // Check if the score is greater than 50
    console.log('Congratulations, you passed!');
} else {
    console.log('Sorry, you failed. Better luck next time.');
}

If the test score is more than 50, 'Congratulations, you passed!' is printed. Otherwise, it prints 'Sorry, you failed. Better luck next time.'.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal