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 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:
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:
If the test score is more than 50, 'Congratulations, you passed!' is printed. Otherwise, it prints 'Sorry, you failed. Better luck next time.'.
