#2 JavaScript var, let & const keyword

Поделиться
HTML-код
  • Опубликовано: 4 окт 2024
  • In JavaScript, var, let, and const are used for variable declarations, but they have some differences in terms of scope, hoisting, and reassignment.
    1) var:
    Variables declared with var are function-scoped. This means that their scope is limited to the function in which they are declared.
    var variables are hoisted to the top of their scope.
    This means that you can use a var variable before it's declared in the code.
    var variables can be reassigned and updated.
    Example:
    function example() {
    if (true) {
    var x = 10;
    console.log(x); // Outputs 10
    }
    console.log(x); // Outputs 10
    }
    2) let:
    Variables declared with let are block-scoped. This means that their scope is limited to the block (statement or compound statement) in which they are declared.
    let variables are also hoisted, but they are not initialized until the interpreter reaches the declaration.
    let variables can be reassigned, but they cannot be re-declared in the same scope.
    Example:
    function example() {
    if (true) {
    let y = 20;
    console.log(y); // Outputs 20
    }
    // console.log(y); // Error: y is not defined (outside the block scope)
    }
    3) const:
    Variables declared with const are block-scoped like let.
    const variables must be initialized during declaration, and their value cannot be reassigned.
    The identifier declared with const cannot be re-declared in the same scope.
    Example:
    const z = 30;
    // z = 40; // Error: Assignment to a constant variable
    In modern JavaScript, it's generally recommended to use let and const over var because they provide more predictable scoping behavior and help prevent certain types of bugs related to variable redeclaration and unintentional variable hoisting. Use let when you need to reassign the variable, and use const when the value should remain constant.

Комментарии • 7

  • @ucandoit1892
    @ucandoit1892 10 месяцев назад

    Vera level, Daily basis la class podunga , its very useful . Thank u lot

  • @thulasidharanj1878
    @thulasidharanj1878 9 месяцев назад

    don't lose hope by seeing the views or likes u r really doing the great job......... and in the up comming vidious pls make use of live examples where we use the concepts what we learn that is more important bro
    🏳🏳🏳🏳🏳🏳🏳

  • @wastedmadan1717
    @wastedmadan1717 10 месяцев назад

    Bro Don't loose Hope Beginner ro Advanced Level Podunga Broo EMC ah vida Nalla solli tharringa bro