← Back to Chapters

JavaScript var Keyword

? JavaScript var Keyword

? Quick Overview

The 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.

? Key Concepts

  • Function Scoped Variables declared with var are scoped to functions
  • Hoisting Declarations are moved to the top of the scope
  • Re-declaration Same variable can be declared multiple times

? Syntax / Theory

The var keyword allows variable declaration before ES6. It does not respect block scope, which can sometimes lead to unexpected behavior.

? View Code Example
// Declaring and using a var variable
var message = "Hello JavaScript";
console.log(message);

? Interactive Laboratory: Re-declaration

Unlike let, var allows you to re-declare the same variable name without throwing an error. Try it below.

var x =
Memory: x ?
Waiting for input...

? Live Output / Explanation

Output

Hello JavaScript is printed to the console because the variable message stores the string value.

? View Code Example
// Demonstrating function scope of var
function demo() {
var x = 10;
console.log(x);
}
demo();

? Tips & Best Practices

  • Avoid using var in modern JavaScript
  • Prefer let or const for block scoping
  • Understand hoisting to prevent bugs

? Try It Yourself

  • Declare a variable using var inside and outside a function
  • Re-declare the same variable and observe the result
  • Compare behavior with let