DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on • Updated on

Scopes/ Loops/ break/ continue

Scopes

Image description

In JavaScript, scope refers to the current context of execution, which determines the accessibility of variables. There are mainly three types of scope:

  1. Global Scope:
  • Variables declared outside any function or block have global scope.

  • They can be accessed from anywhere in the code.

var globalVar = "I'm a global variable";
function showGlobalVar() {
    console.log(globalVar); // Accessible
}
showGlobalVar(); // Logs: I'm a global variable

Enter fullscreen mode Exit fullscreen mode
  1. Function Scope:
  • Variables declared within a function are in the function scope.

  • They can only be accessed within that function.

function myFunction() {
    var functionVar = "I'm a function variable";
    console.log(functionVar); // Accessible
}
myFunction(); // Logs: I'm a function variable
console.log(functionVar); // Error: functionVar is not defined

Enter fullscreen mode Exit fullscreen mode
  1. Block Scope:
  • Introduced in ES6 with let and const.

  • Variables declared within a block (inside {}) have block scope.

  • They can only be accessed within that block.

if (true) {
    let blockVar = "I'm a block variable";
    console.log(blockVar); // Accessible
}
console.log(blockVar); // Error: blockVar is not defined

// ------------------------------------
Variable in global scope can access function scope but in global scope we can't call variable in function scope.

const age = 26;
const name = 'Khojiakbar';

function info(age) {
    // name = 'Muhammad'
    age = 33
    console.log(`My name is ${name} and I am ${age} years old`);
}
info()

console.log(`My name is ${name} and I am ${age} years old`);

Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Global Scope: Variables are accessible throughout the code.

  • Function Scope: Variables are accessible only within the function they are declared.

  • Block Scope: Variables are accessible only within the block they are declared (using let or const).

var globalVar = "global";

function myFunction() {
    var functionVar = "function";
    if (true) {
        let blockVar = "block";
        console.log(globalVar);  // Accessible
        console.log(functionVar); // Accessible
        console.log(blockVar);    // Accessible
    }
    console.log(globalVar);    // Accessible
    console.log(functionVar);  // Accessible
    console.log(blockVar);     // Error: blockVar is not defined
}

myFunction();
console.log(globalVar); // Accessible
console.log(functionVar); // Error: functionVar is not defined
console.log(blockVar);    // Error: blockVar is not defined

Enter fullscreen mode Exit fullscreen mode

Loops

Image description
1. for Loop

A for loop is ideal when you know how many times you want to execute a block of code.

Basic Structure:

for (let i = 0; i < 5; i++) {
    console.log(i); // Outputs: 0, 1, 2, 3, 4
}
Enter fullscreen mode Exit fullscreen mode
  • Initialisation: let i = 0 sets the counter i to 0.
  • Condition: i < 5 runs the loop as long as i is less than 5.
  • Increment: i++ increases i by 1 after each loop iteration.

2. while Loop

A while loop is used when you don't know in advance how many times you need to run the code. The loop continues as long as a condition is true.

let i = 0;
while (i < 5) {
    console.log(i); // Outputs: 0, 1, 2, 3, 4
    i++; // Increment the counter
}

Enter fullscreen mode Exit fullscreen mode
  • Condition: i < 5 keeps the loop running as long as i is less than 5.

  • Increment: i++ inside the loop increases i by 1 each time the loop runs.

3. do...while Loop

A do...while loop is similar to a while loop, but it guarantees that the code block executes at least once before checking the condition.

let i = 0;
do {
    console.log(i); // Outputs: 0, 1, 2, 3, 4
    i++; // Increment the counter
} while (i < 5);

Enter fullscreen mode Exit fullscreen mode
  • First execution: The code block runs and outputs 0.

  • Condition: i < 5 is checked after the first execution and keeps the loop running as long as i is less than 5.

4. for...in Loop

A for...in loop is used to iterate over the properties of an object. It loops through all the enumerable properties of an object.

const person = {name: "John", age: 30, city: "New York"};
for (let key in person) {
    console.log(key + ": " + person[key]); // Outputs: name: John, age: 30, city: New York
}
Enter fullscreen mode Exit fullscreen mode
  • key: Each property name (name, age, city) is assigned to key in each loop iteration.

  • person[key]: Accesses the value of each property.

5. for...of Loop

A for...of loop is used to iterate over the values of an iterable object, such as an array, string, map, set, etc.

const fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
    console.log(fruit); // Outputs: apple, banana, cherry
}
Enter fullscreen mode Exit fullscreen mode
  • fruit: Each value from the fruits array is assigned to fruit in each loop iteration.

Summary with Practical Examples:

Iterating Over Arrays:

const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]); // Outputs: 1, 2, 3, 4, 5
}
Enter fullscreen mode Exit fullscreen mode

Iterating Over Object Properties:

const car = {make: "Toyota", model: "Corolla", year: 2020};
for (let key in car) {
    console.log(`${key}: ${car[key]}`); // Outputs: make: Toyota, model: Corolla, year: 2020
}
Enter fullscreen mode Exit fullscreen mode

Handling Dynamic Conditions:

let count = 0;
while (count < 3) {
    console.log(count); // Outputs: 0, 1, 2
    count++;
}
Enter fullscreen mode Exit fullscreen mode

Ensuring Code Runs At Least Once:

let index = 0;
do {
    console.log(index); // Outputs: 0, 1, 2
    index++;
} while (index < 3);
Enter fullscreen mode Exit fullscreen mode

Iterating Over Values of Iterable Objects:

const fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
    console.log(fruit); // Outputs: apple, banana, cherry
}
Enter fullscreen mode Exit fullscreen mode

break Statement

Image description

The break statement is used to exit a loop immediately, regardless of the loop's condition. When break is encountered, the loop stops, and control is passed to the statement following the loop.

for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break; // Exit the loop when i equals 5
    }
    console.log(i); // Outputs: 0, 1, 2, 3, 4
}
Enter fullscreen mode Exit fullscreen mode

continue Statement

The continue statement skips the rest of the code inside the current iteration of the loop and jumps to the next iteration. It does not terminate the loop but skips to the next iteration.

for (let i = 0; i < 10; i++) {
    if (i % 2 === 0) {
        continue; // Skip the rest of the loop iteration if i is even
    }
    console.log(i); // Outputs: 1, 3, 5, 7, 9
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
mukhriddinweb profile image
Mukhriddin Khodiev (work)

πŸš€