Typescript Scoping and Destructuring

Level : Advanced
Mentor: Shailendra Chauhan
Duration : 00:00:45

Scoping and Destructuring:

Scoping refers to the visibility and accessibility of variables within different parts of your code, while destructuring allows you to extract specific values from objects or arrays. Combining these concepts enables you to control variable scope and efficiently extract data from complex structures.

Example:

// Scoping and Destructuring
function extractData() {
    if (true) {
        let { name, age } = { name: "John", age: 30 };
        console.log(name); // "John"
    }
    console.log(name); // Error: 'name' is not defined
}
extractData();

Block Scoping:

Block scoping involves declaring variables within a specific block of code, limiting their scope to that block. This helps avoid naming conflicts and ensures that variables are only accessible where needed.

Example:

// Block Scoping
function blockScopeDemo() {
    if (true) {
        let message = "Inside if block";
        console.log(message); // "Inside if block"
    }
    console.log(message); // Error: 'message' is not defined
}
blockScopeDemo();

Hoisting:

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during compilation, allowing you to use them before they are declared in your code.

Example:

// Hoisting
function hoistingDemo() {
    console.log(hoistedVar); // undefined
    var hoistedVar = "I am hoisted!";
    console.log(hoistedVar); // "I am hoisted!"
}
hoistingDemo();
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this