Difference between var, let and const

In this article you learn what is difference between var, let, const. You will learn what are they and how to use them.
var creates a variable in JavaScript. But some values are never changed of variables. They are constants.
But with ES6 (version of JavaScript) two new JavaScript keywords were introduced: let & const. let & const are different ways to create variables. var still works but it’s good to use let and const.

var

var creates a variable in JavaScript. You can also change the value of variables. You can learn more about variables from the following article:
Variables in JavaScript

Example:

var name = "John";
console.log(name);

name = "Jane";
console.log(name);

Output:

John
Jane

let

let is new var. We use it to store variable values. Use let to declare variables if that variable value will be changed.

Example:

let name = "John";
console.log(name);

name = "Jane";
console.log(name);

Output:

John
Jane

const

Use const if the variable value is constant and it will not be changed. const variable values cannot be changed.

Example:

const name = “John”;
console.log(name);

name = “Jane”;
console.log(name);

Output:

You will get the following error as const cannot be changed. So, use const only when you know that value is not going to change.

If you have any questions about this topic, you can ask me through the comment section.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments