In the world of JavaScript, where code dictates what happens on your screen, the boolean data type reigns supreme in the realm of decision-making. Simply put, booleans are like tiny switches that can only be in two positions: on (true) or off (false).
But don’t be fooled by their simplicity! These fundamental building blocks are crucial for controlling program flow, making your JavaScript applications intelligent and responsive.
Truth Be Told: Declaring Booleans
Declaring a boolean variable in JavaScript is straightforward. You can use the keywords true
or false
to assign a boolean value:
let isLoggedIn = true;
let isNightTime = false;
Beyond True and False: Falsy and Truthy
While true
and false
are the only “true” booleans, JavaScript has a concept called “truthy” and “falsy” values. These are values that get converted to true
or false
during comparisons or conditional statements. Here’s a quick rundown:
Truthy values: These evaluate to true
when used in a boolean context. Examples include non-zero numbers, strings (except the empty string ""
), objects, and arrays.
Falsy values: These evaluate to false
when used in a boolean context. Examples include the number 0
, the empty string ""
, null
, undefined
, and NaN
(Not a Number).
Falsy and Truthy values are very important values that will help in one’s journey as a developer, better helping you to effectively use conditional statements. There will be a follow-up post that talks about conditional statements and how to use boolean values. Let’s look forward to that!