Table of contents
No headings in the article.
In JavaScript, users can declare a variable using 3 keywords that are var, let, and const. In this article, we will see the differences between the var, let, and const keywords. We will discuss the scope and other required concepts about each keyword.
Hello guy's I am Deepti again here with another blog.
- var- It can be declared without initialization.
- let - It can be declared without initialization. we mostly use let because it has worked as global one.
- Const - It cannot be declared without initialization.
these are the basic difference among three.
var keyword in JavaScript: The var is the oldest keyword to declare a variable in JavaScript.
Scope: Global scoped or function scoped. The scope of the var keyword is the global or function scope. It means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function.
Example 1: Variable ‘a’ is declared globally. So, the scope of the variable ‘a’ is global, and it can be accessible everywhere in the program.
<script>
var a = 10
function f(){
console.log(a)
}
f();
console.log(a);
</script>
Output:
10 10
let keyword in JavaScript: The let keyword is an improved version of the var keyword.
Scope: block scoped: The scope of a let variable is only block scoped. It can’t be accessible outside the particular block ({block}). Let’s see the below example.
<script>
let a = 10;
function f() {
let b = 9
console.log(b);
console.log(a);
}
f();
</script>
Output:
9 10
const keyword in JavaScript: The const keyword has all the properties that are the same as the let keyword, except the user cannot update it.
Scope: block scoped: When users declare a const variable, they need to initialize it, otherwise, it returns an error. The user cannot update the const variable once it is declared.
<script>
const a = 10;
function f() {
a = 9
console.log(a)
}
f();
</script>
Output: a=9 TypeError:Assignment to constant variable.