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 creates a space to store a specific value that can be retrieved and used when needed.


Basic Usage

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

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 Variables

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

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 where var's value is applicable).

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

However, a var variable declared outside of a function becomes a global variable and can be accessed anywhere.

Example:

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

// The insideFunction variable cannot be used here.

Other Variable Declaration Keywords

Since 2015, JavaScript has included let and const as additional variable declaration keywords.

The let keyword is used to declare variables that can be reassigned, and the const keyword is used to declare variables that cannot be reassigned.

Want to learn more?

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