JavaScript Var, Let, and Const
Tags: javascript, codenewbie, beginners, html
Published: 2021-01-19 22:50:10

{% youtube bNAUPeXaAqY %}

---
To declare a variable in JavaScript either `var`, `let` or `const` is used. 

Let's see the differences between the three below.

---
### *var* and *let*
#### Block Scope 
A Block scope contains a group of code within curly braces `{}`.

A variable created with the `let` keyword in a block scope is only available within it. 

```js
let greeting = "Hi John!!!"; // Global Variable

if (true) {
    let greeting = "Hello Bello!!!"; // Local Variable
    console.log(greeting);// Hello Bello!!!
}
console.log(greeting) // "Hi John!!!"
```

`let` creates either a global or a local variable. If it is out of scope, it's globally scoped else it is locally scoped if in scope.

While;

`var` always creates global variables.

```js
if (true) {
    var greeting = "Hello Bello!!!";
}
console.log(greeting) // "Hello Bello!!!"

if (true) {
    let hello = "Hello Bello!!!";
}
console.log(hello) // ReferenceError: hello is not defined
```

#### Update and redeclaration
Variables declared with either `var` or `let` can get updated at any time in a program.

```js
var name = 'Mary';
name = 'Nadia';
console.log(name); // Nadia

let myName = 'Bob';
myName = 'Richard';
console.log(myName); // Richard
```

Both `var` and `let` can be updated as shown above, but only `var` can be redeclared.

```js
var firstName = 'John';
var firstName = 'Osagie';
console.log(firstName); // John

let lastName = 'Bello';
let lastName = 'Bob';
console.log(firstName); 
// SyntaxError: Identifier 'lastName' has already been declared
```

---
[![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1613668162316/G1zfmhxQd.png)](https://www.cssigniter.com/members/aff/go/belloosagienoah)

---
#### Hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top. 

A variable may get to be declared after it has been used. It's only peculiar to the `var` keyword.

```js
console.log('My name is ' + name); // My name is Michael

var name = 'Michael';
```

The below example shows how the JavaScript engine will interpret the above code when `var` keyword is used for declaration.

```js
var name = 'Michael';
console.log('My name is ' + name); // My name is Michael
```

> JavaScript in strict mode (`'use strict'`) does not allow a variable to be used if not declared first.

See the example below:

```js
'use strict';
console.log(name);

var name = 'Jerry'; // no output, no error
```

When `let` is used, it is impossible to use a variable before it has been declared.

```js
console.log('My name is ' + name); // ReferenceError: Cannot access 'name' before initialization

let name = 'Michael';
```

---
### *const*
#### Block scope 
`const` has the same feature as `let` because it also maintains its scope.

```js
const greeting = "Hi John!!!"; // Global Variable

if (true) {
    const greeting = "Hello Bello!!!"; // Local Variable
    console.log(greeting);// Hello Bello!!!
}
console.log(greeting) // "Hi John!!!"
```


#### Update and redeclaration
The `const` keyword is also used to create a variable but can not be updated unlike `let` and `var`.

```js
const birthday = '01/20/2020';
birthday = '01/19/2020';
console.log(birthday); // TypeError: Assignment to constant variable.
```

It is, of course, impossible to update someone's birthday. So use `const` only when a value will not be updated or changed.

```js
const birthday = '01/20/2020';
console.log(birthday); // 01/20/2020
```
Since it can not be updated, it can not be redeclared.

```js
const birthday = '01/20/2020';
const birthday = '01/10/2020';
console.log(birthday); // SyntaxError: Identifier 'birthday' has already been declared
```

#### Undefined
A `const` variable must be initialized to a value. If a constant variable is undefined, it leads to an error.

```js
const name; // undefined variable
name = 'Jack';
console.log(name); // SyntaxError: Missing initializer in const declaration
```

If you plan to undefined a constant variable, use the value `undefined`.

```js
const name = undefined;

function myName() {
  if (!name) {
  return 'Jack';
}

return name;
}
console.log( myName() ); // Jack
```

#### Hosting
`const` has another similarity with `let` in terms of hoisting a variable. That is it also doesn't support hoisting.

---
### Conclusion
- It is advisable to use `let` and not `var` has it is the modern way to create a variable in JavaScript.

- Use `const` only when a value is constant (immutable variable).

- It is advisable to always declare all variables at the beginning of every scope with  `let` when necessary to avoid bugs (errors).

**Happy Coding!!!**

---
[![Buy me a Coffee](https://res.cloudinary.com/bizstak/image/upload/v1610317510/ko-fi-trans_fr3su4.png)](https://www.buymeacoffee.com/techstackmedia)

---
### TechStack Media | Bluehost
- Get a website with a free domain name for 1st year and a free **SSL** certificate.
- 1-click WordPress install and 24/7 support.
- Starting at $3.95/month.
-  30-Day Money-Back Guarantee.

<a href="https://www.bluehost.com/track/belloosagienoah/" target="_blank"> <img border="0" src="https://bluehost-cdn.com/media/partner/images/belloosagienoah/430x288/430x288PW.png"> </a>