DEV Community

Cover image for Javascript: Var vs Const vs Let 👍💯
w6
w6

Posted on

Javascript: Var vs Const vs Let 👍💯

A lot of shiny new features came out with ES2015 (ES6). And now, since it's 2022, it's assumed that a lot of JavaScript developers have become familiar with and have started using these features.

Var: Pros & Cons

A var (short for variable) is a global variable that can be accessed from anywhere, it is also able to be assigned different values.

var hello = "Hi!";
Enter fullscreen mode Exit fullscreen mode

Pros:

  • It can be re-declared and updated
  • It's globally scoped (can be accessed from anywhere)

Cons:

  • It can be a pain to have to re-define other variables since it's globally scoped.

Const: Pros & Cons

Variables declared with the const maintain constant values. const declarations share some similarities with let declarations.

Const declarations are block scoped

Like let declarations, const declarations can only be accessed within the block they were declared.

Const cannot be re-declared or updated

This means the value set for a const will always stay the same and cannot be updated.

Pros:

  • It is block scoped
  • You can assign sub-variables like: const.message = "Hello" without issues.

Cons:

  • It cannot be re-declared or updated
const hello = "Hi!";
hello = "Ciao!" // Const cannot be updated.
Enter fullscreen mode Exit fullscreen mode

Let: Pros & Cons

let is now preferred for variable declaration. It's no surprise as it comes as an improvement to var declarations. It also solves the problem with var that we just covered. Let's consider why this is so.

let is block scoped

So a variable declared in a block with let is only available for use within that block. Let me explain this with an example:

function test1() {
  let test = "ee";
  console.log(test); // returns "ee"
}

function test2() {
  let test = "ff";
  console.log(test); // returns "ff"
}
Enter fullscreen mode Exit fullscreen mode

it can be updated but not re-declared

For example, this would return an error:

let test = "Hello!";
let test = "Robot."; // Error ❌
Enter fullscreen mode Exit fullscreen mode

However, a let variable can be re-declared in different blocks. For example, a function and another function could use the same variable name without issue.

This makes let the primary choice for developers in 2022 since it's so easy-to-use and has a ton of upsides.

Pros:

  • Can be re-declared in different blocks
  • let is the modern version of var with a ton of improvements.

Cons:

  • It can be updated but it cannot be re-declared
  • Not much downsides since let is a great choice.

Thanks for reading 👋

If you like my content, please leave a ❤️ or even a Comment 💬

Top comments (0)