Hackforge Academy

Category: javascript

var key word in JS

Published on 18 Feb 2026

Explanation


var is a keyword used to declare variables
in JavaScript. It was used before ES6 and
has function scope.

Code:

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

Explanation


Variables declared with var are scoped to the
entire function, not the block.

Code:

function test() {
  if (true) {
    var x = 10;
  }
  console.log(x); // Accessible here
}

test();

Explanation


var does not support block scope. Even if
declared inside a block, it is accessible outside
the block within the function.

Code:

if (true) {
  var a = 5;
}

console.log(a); // Works

Explanation


Variables declared with var can be reassigned with
new values.

Code:

var count = 1;
count = 2;
console.log(count);

Explanation


You can redeclare the same variable using var
in the same scope without error.

Code:

var age = 20;
var age = 30;
console.log(age);

Explanation


var variables are hoisted to the top of
their scope and initialized with undefined.

Code:

console.log(x); // undefined
var x = 10;
console.log(x);

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community