JavaScript Introduction | Types | Variables

Declaring and Initializing Variables

A variable is a memory space that can store data, and its value can change. In JavaScript, variables are declared with the var keyword.

In JavaScript, an error occurs if you try to use or access a variable that has not been declared. However, if you initialize an undeclared variable, it is automatically declared first and then initialized.

var month; // Declare a variable named month
date = 25; // Implicitly declare a variable named date

A declared variable can be initialized later, or it can be initialized at the same time it is declared.

var month;     // Variable declaration
var date = 25; // Declaration and initialization at the same time
month = 12;    // Variable initialization

You can also declare or initialize multiple variables at the same time by using the comma operator.

var month, date;             // Declare multiple variables at once
var hours = 7, minutes = 15; // Declare and initialize multiple variables at the same time
month = 10, date = 5;        // Initialize multiple variables at once

Variable Types and Initial Values

JavaScript variables do not have fixed types, and values of different types can be assigned again to the same variable. Although different types of values can be assigned to a single variable multiple times, a variable that has already been declared cannot be redeclared.

var num = 10;        // Declare and initialize a variable
num = [10, 20, 30];  // Assign an array
var num;             // This redeclaration statement is ignored.

An array is a single collection made up of multiple values.

In JavaScript, a variable that has only been declared and not initialized has the value undefined.

var num;  // undefined
num = 10; // 10

Variable Names

In JavaScript, variables are identified by name, so a variable name is an identifier. A variable name consists only of letters, uppercase or lowercase, digits, underscores (_), or dollar signs ($). It also cannot start with a number, so that it can be quickly distinguished from numeric values. Variable names are case-sensitive, and keywords reserved by the JavaScript language cannot be used as names.