2. Variables & Constants

1. Declare Variables Using var

Program 1: Basic var Declaration

				
					<!DOCTYPE html>
<html>
<body>
<script>
var name = "Boby";
document.write("Name: " + name);
</script>
</body>
</html>

				
			

Program 2: var Re-declaration Allowed

				
					<script>
var age = 20;
var age = 25;
document.write("Age: " + age);
</script>

				
			

2. Declare Variables Using let

Program 1: Basic let Declaration

				
					<script>
let city = "Delhi";
document.write("City: " + city);
</script>

				
			

Program 2: let Reassignment

				
					<script>
let score = 50;
score = 75;
document.write("Score: " + score);
</script>

				
			

3. Declare Constants Using const

Program 1: Basic const Example

				
					<script>
const country = "India";
document.write("Country: " + country);
</script>

				
			

Program 2: const with Object

				
					<script>
const student = { name: "Amit", age: 22 };
student.age = 23;   // allowed
document.write(student.name + " - " + student.age);
</script>

				
			

4. Difference Between var, let, and const

Program 1: Declaration & Reassignment

				
					<script>
var a = 10;
let b = 20;
const c = 30;

a = 15;
b = 25;
// c = 35; // Error: Assignment to constant variable

document.write(a + "<br>" + b + "<br>" + c);
</script>

				
			

Program 2: Re-declaration Test

				
					<script>
var x = 5;
var x = 10;   // allowed

let y = 5;
// let y = 10; // Error

document.write(x + "<br>" + y);
</script>

				
			

5. Variable Reassignment and Immutability

Program 1: Reassignment with var and let

				
					<script>
var a = 10;
a = 20;

let b = 30;
b = 40;

document.write(a + "<br>" + b);
</script>

				
			

Program 2: Custom Format (DD/MM/YYYY HH:MM)

				
					<script>
const pi = 3.14;
// pi = 3.1415; // Error
document.write("PI: " + pi);
</script>

				
			

Program 3: const Array Modification

				
					<script>
const numbers = [1, 2, 3];
numbers.push(4); // allowed
document.write(numbers);
</script>

				
			

6. Variable Scope (Global vs Block – Basic)

Program 1: Global Scope

				
					<script>
var message = "Global Variable";

function show() {
  document.write(message);
}

show();
</script>

				
			

Program 2: Block Scope with let

				
					<script>
if (true) {
  let x = 10;
  document.write(x);
}
// document.write(x); // Error: x is not defined
</script>

				
			

Program 3: var vs let Scope

				
					<script>
if (true) {
  var a = 5;
  let b = 10;
}

document.write(a); // works
// document.write(b); // Error
</script>