DEV Community

Ticha Godwill Nji
Ticha Godwill Nji

Posted on

1 1 1 1 1

Var, Let and Const

var, let, and const are all used to declare variables in JavaScript, but they have some differences in terms of scope, reassignment, and initialization:

var

  • var declarations are globally scoped or function scoped.
  • They can be reassigned and re-declared within their scope.
  • var variables are hoisted to the top of their scope and initialized with undefined.
var x = 10;
console.log(x); // Output: 10

{
    var x = 20;
    console.log(x); // Output: 20
}

console.log(x); // Output: 20

Enter fullscreen mode Exit fullscreen mode

let

  • let declarations are block scoped.
  • They can be reassigned but not re-declared within their scope.
  • let variables are not hoisted; they are only accessible after they are declared.
let y = 10;
console.log(y); // Output: 10

{
    let y = 20;
    console.log(y); // Output: 20
}

console.log(y); // Output: 10

Enter fullscreen mode Exit fullscreen mode

const

  • const declarations are block scoped.
  • They cannot be reassigned or re-declared within their scope.
  • const variables must be initialized during declaration and cannot be left uninitialized.
const z = 10;
console.log(z); // Output: 10

{
    const z = 20;
    console.log(z); // Output: 20
}

console.log(z); // Output: 10

Enter fullscreen mode Exit fullscreen mode

In summary, var has function scope, let and const have block scope. let allows reassignment, while const does not. const requires initialization and cannot be re-declared or reassigned.

Explore more on my Youtube channel
Follow me on Linkedln

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay