DEV Community

RedouaneSarouf
RedouaneSarouf

Posted on

JavaScript var keyword usage

JavaScript var keyword: Usage and Best Practices
In JavaScript, variables are used to store data values. The 'var' keyword is used declare a variables of any type without initializing them and it stands for variable.
here is an example of declaring a variable using 'var':
var [variable name];
In this blog post we will discuss the usage and how it differs from other type of variable declaration.
Difference between var, let and const. let is used in situation where you may want to reassign the variable again.

let dog = "Bella";
dog = "Tracy" //reassigning the dog value

const is used to declare variables that can not be changed once declared similar to final keyword in java language.

const cat = "Brent";
cat = "jay"// error;

Both keywords let and const can not escape block scope. On the other hand, 'var' can escape block scope but can not escape function block.
here is an example of var escaping:

for(var i = 0; i < 4; i++){
console.log(i);// 0 1 2 3
}
console.log(i) // the value of i is 4;

Best practices is to avoid creating global variables and use let and const instead of var. var can cause issues with naming conflict and make your code difficult to read.

Top comments (0)