DEV Community

Cover image for Conditional branching: if, '?'
Karthick (k)
Karthick (k)

Posted on

Conditional branching: if, '?'

Q1, JavaScript - Conditional Statements

JavaScript conditional statements are used to make decisions in a program based on given conditions. They control the flow of execution by running different code blocks depending on whether a condition is true or false.

  1. Conditions are evaluated using comparison and logical operators.
  2. They help in building dynamic and interactive applications by responding to different inputs.

Types of Conditional Statements

1. if Statement

The if statement checks a condition written inside parentheses. If the condition evaluates to true, the code inside {} is executed; otherwise, it is skipped.

if (condition) {
// code runs if the condition is true
}

2. if-else Statement

The if-else statement executes one block of code if a condition is true and another block if it is false. It ensures that exactly one of the two code blocks runs.

3. else if Statement

The else if statement is used to test multiple conditions in sequence. It executes the first block whose condition evaluates to true.

Q2.Explain The Concept of Truthy & Falsy Values in JavaScript

In JavaScript, truthy and falsy values are concepts related to Boolean evaluation. Every value in JavaScript has an inherent boolean "truthiness" or "falsiness," which means they can be implicitly evaluated to true or false in boolean contexts, such as in conditional statements or logical operations.

What Are Truthy Values?

Truthy values are values that are evaluated to be true when used in a Boolean context. Simply put, any value that is not explicitly falsy is considered truthy.

These are some truthy values

Non-zero numbers: 42, -1, 3.14
Non-empty strings: "hello", "0", " "
Objects and arrays: {}, []
Functions: function() {}
Dates: new Date()
Symbols: Symbol()
BigInt values other than 0n: 10n

if (42) console.log("This is truthy!");
if ("hello") console.log("Non-empty strings are truthy!");
if ({}) console.log("Objects are truthy!");

What Are Falsy Values?

Falsy values are values that evaluate to false when used in a Boolean. JavaScript has a fixed list of falsy values

false
0 (and -0)
0n (BigInt zero)
"" (empty string)
null
undefined
NaN
document. all (used for backward compatibility)

if (0) console.log("This won't run because 0 is falsy.");
if ("") console.log("This won't run because an empty string is falsy.");
if (null) console.log("This won't run because null is falsy.");

Top comments (0)