ES6++: 2-Var, Let and Const
Tags: javascript, es6, esnext
Published: 2022-11-16 07:38:13

---
title: ES6++: 2-Var, Let and Const
published: true
description: 
series: es6++
tags: javascript, es6, esnext
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o5wfp3sx9luz1pse5kgp.png
# Use a ratio of 100:42 for best results.
# published_at: 2022-10-25 09:51 +0000
---

## Introduction

In this article we will talk about the `let` and `const` keywords, we will talk about the differences between them and how to use them.

## `var` keyword

Let's first get started with the `var` keyword, the `var` keyword is the old way of declaring variables in javascript, it was introduced in `ES5` and it is still supported in `ES6` and above.

> Being in 2022, or probably 2023, i don't think that you will/should use the `var` keyword in your code, but it is still good to know about it.

`var` keyword is a global scoped variable, it means that you can access it from anywhere in your code, even if it is declared inside a function.

```js
var name = "Hasan";

function sayName() {
  console.log(name);
}

sayName(); // Hasan
```

In the example above we declared a variable called `name` and we assigned it the value `Hasan`, then we declared a function called `sayName` and inside it we logged the value of `name` to the console, and when we called the function `sayName` it logged `Hasan` to the console.

Also variables declared with `var` can be used before they are declared, this is called `hoisting`.

```js
console.log(name); // undefined

var name = "Hasan";
```

In the example above we logged the value of `name` to the console before we declared it, and it logged `undefined` to the console, this is because of `hoisting`.

On the other hand, `let` and `const` can be only used after their initialization, we'll see that in a moment.

## `let` keyword

The `let` keyword is used to declare a variable that can be changed later in the code, it is similar to the `var` keyword but it has some differences.

### Differences between `let` and `var`

* `let` is block scoped, while `var` is function scoped.
* `let` can't be redeclared in the same scope, while `var` can be redeclared.
* `let` can't be used before it is declared, while `var` can be used before it is declared.

What to use? `let` or `var`? `let` of course.

### Examples

Let's see some examples to understand the differences between `let` and `var`.

Can not be declared twice in the same scope:

```js
// can not be redeclared
let x = 10;
let x = 20; // SyntaxError: Identifier 'x' has already been declared
```

But can be updated

```js
// valid 
let x = 10;
x = 20; // No error
```

Can not be used before it is initialized:

```js
// can no
console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 10;
```

But `var` can be used before it is initialized:

```js
console.log(x); // undefined
var x = 10;
```

## `const` keyword

`const` stands for `constant`, so it means that the variable can't be changed.

The `const` keyword is used to declare a variable that can't be changed later in the code, it is similar to the `let` keyword but it has some differences.

Let's see an example:

```js
const x = 10;

x = 20; // TypeError: Assignment to constant variable.
```

Const is also block scoped, so it can't be accessed outside the block.

```js

for (let i = 0; i < 10; i++) {
  const x = 10;
}

console.log(x); // ReferenceError: x is not defined
```

Let's understand now what is meant by block scopes.

## Let And Const Scopes

`let` and `const` are block scoped, so they can't be accessed outside the block they are declared in.

```js
{
  let x = 10;
}
```

What scopes we're talking about? literally any block of code between `{}` is considered a block, so the following are all blocks:

* `if` statement
* `for` loop
* `while` loop
* `switch` statement
* `try` statement
* `catch` statement
* `finally` statement
* `do` statement
* `function` statement
* `class method` statement

In that sense, let's see an example of how this works when using a function and an if statement inside it.

```js
function test() {
  if (true) {
    let x = 10;
  }
  console.log(x); // ReferenceError: x is not defined
}
```

Any variables defined inside a function can't be accessed outside that function, but if a function has a nested function, that nested function can access the variables defined in the parent function.

```js
function test() {
  let x = 10;
  function test2() {
    console.log(x); // 10
  }
  test2();
}
```

In that sense, children scopes has access to the variables defined in the parent scope, but the parent scope doesn't have access to the variables defined in the children scopes.

```js
function test() {
  let x = 10;
  if (true) {
    let y = 20;
  }
  console.log(y); // ReferenceError: y is not defined
}
```

## Reinitialized let/const Inside Nested Scopes

If a `let` or `const` variable is declared in a scope, it can be declared again in a nested scope with a new initialization, however, that variable/const inside that nested scope can't be accessed outside that nested scope.

```js

for (let i = 0; i < 10; i++) {
  const x = 10;
  console.log(x); // 10

  if (x === 10) {
    const x = 20;
    console.log(x); // 20
  }

  console.log(x); // 10
}
```

> Please note that if you're working with esm modules, the parent scope is the file that you're working on, so if you declared any const/let variable in that file, you can't access it in another file but you can access it in any nested scope in that file.

## When to use let and when to use const?

> Best Practices

As long as the variable is not going to change, use `const`, otherwise use `let`.

So your base is `const` unless you need to change the value of the variable.

## Conclusion

In this article we talked about the `let` and `const` keywords, we talked about the differences between them and how to use them.

We also talked about the scopes of `let` and `const` and how they work, also talked about nested scopes.

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) to get help and support (Node Js 2023 Channel).

## 📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

* [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
* [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
* [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

* [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
* [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
* [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

* [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

* [Node Js 2023 Course: Node With Typescript, The Ultimate Guide](https://dev.to/hassanzohdy/nodejs-course-2023-introduction-to-nodejs-3n4e)
* [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)