Conditionals, Loops, and Functions
Table of contents
No headings in the article.
Conditionals allow us to make decisions in code based on conditions.
They take the form of
1, if, else if, and else statements.
For instance;
let num = 10; if (num > 0) { console.log("Number is positive"); } else if (num < 0) { console.log("Number is negative"); } else { console.log("Number is zero"); }
Loops**
Loops are used for repetitive tasks.
There are three main types: for, while, and do...while loops.
For Loop**
for (let i = 0; i < 5; i++) { console.log(i); }
While Loop**
let i = 0; while (i < 5) { console.log(i); i++; }
Do...While Loop**
let i = 0; do { console.log(i); i++; } while (i < 5);
FUNCTIONS**
Functions are blocks of reusable code.
They have a declaration, a scope, and various properties like hoisting and nesting.
Function Declaration function greet(name) { return Hello, ${name}!
; } console.log(greet("Alice"));
Function Scope let globalVar = "I am global";
function scopeExample() { let localVar = "I am local"; console.log(globalVar); console.log(localVar); }
scopeExample(); console.log(globalVar); // console.log(localVar); // This will throw an error as localVar is not accessible outside the function.
Nesting Functions function outerFunction() { function innerFunction() { console.log("Inside inner function"); } innerFunction(); } outerFunction();
Function Hoisting**
hoistedFunction(); // This works due to hoisting
function hoistedFunction() { console.log("This function was hoisted"); }