var KeywordThe var keyword is used to declare variables in JavaScript. It is the oldest way to define variables and has function-level scope instead of block-level scope.
var are scoped to functionsThe var keyword allows variable declaration before ES6. It does not respect block scope, which can sometimes lead to unexpected behavior.
// Declaring and using a var variable
var message = "Hello JavaScript";
console.log(message);
Unlike let, var allows you to re-declare the same variable name without throwing an error. Try it below.
var x = Hello JavaScript is printed to the console because the variable message stores the string value.
// Demonstrating function scope of var
function demo() {
var x = 10;
console.log(x);
}
demo();
var in modern JavaScriptlet or const for block scopingvar inside and outside a functionlet