0
0
Javascriptprogramming~5 mins

Variable declaration using var in Javascript

Choose your learning style9 modes available
Introduction

We use var to create a named container that holds a value we can use later in our program.

When you want to store a value like a number or text to use later.
When you need to change the value stored in a variable during the program.
When you want to give a name to a value to make your code easier to read.
When you are working with older JavaScript code that uses <code>var</code>.
When you want a variable that is function-scoped rather than block-scoped.
Syntax
Javascript
var variableName = value;

The var keyword declares a variable.

You can assign a value right away or leave it undefined.

Examples
This creates a variable named age and stores the number 25 in it.
Javascript
var age = 25;
This creates a variable named name and stores the text "Alice".
Javascript
var name = "Alice";
This creates a variable named isStudent without giving it a value yet.
Javascript
var isStudent;
You can change the value stored in a var variable anytime.
Javascript
var score = 10;
score = 15;
Sample Program

This program creates two variables and prints a greeting message using them.

Javascript
var greeting = "Hello";
var name = "Bob";
console.log(greeting + ", " + name + "!");
OutputSuccess
Important Notes

var variables are function-scoped, which means they are visible throughout the function they are declared in.

Unlike let and const, var allows redeclaration of the same variable name in the same scope.

Modern JavaScript prefers let and const for clearer scoping rules, but var is still important to understand.

Summary

var creates a variable to store data.

Variables declared with var can be changed and redeclared.

var variables are function-scoped, not block-scoped.