Skip to main content
Practice

Variable Declaration Keyword - var

What is var?

var is a keyword used in JavaScript to declare variables.

A variable is a named storage space that can hold data which can be referenced or changed later.

var allocates a space that can store specific values and be accessed when necessary.


Basic Usage

To declare a variable, use the var keyword, specify the variable name, and then assign a value to it.

For example:

Declaring a var variable
var studentName = 'John';

Here, studentName is the name of the variable, and "John" is the value stored in that variable.


Characteristics of var

Reassignable: A var variable can be reassigned to a different value after it has been declared.

Reassigning a variable
var number = 10;
number = 20; // The value of the variable number is changed to 20.

Function-level scope: var has a function-level scope (the scope within which the value of var is effective).

This means that a var variable declared inside a function can only be used within that function.

However, a var variable declared outside of any function becomes a global variable, accessible from anywhere.

For example:

var variable declared inside a function
function myFunction() {
var insideFunction = 'Hello!';
}

// The insideFunction variable cannot be used here.

Other Variable Declaration Keywords

Since 2015, JavaScript introduced additional variable declaration keywords let and const besides var.

The let keyword is used for declaring reassignable variables, while the const keyword is used for declaring variables that cannot be reassigned.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.