Description

JavaScript Variables are used to store data, like strings, numbers, arrays, objects, functions, etc., within the code.

  • Variables must be defined using the keywords "var", "let", or "const".
  • Variables can be initialized using the assignment operator (=) along with their definition or set a new value after the definition.
  • Variables values can be set, updated, and retrieved any number of times.
  • Variables are the symbolic names for the values.
  • Variables can hold any type of data, like string, number, boolean, array, object, function, etc.,

Declare and Initialize

The below example declares and initializes a variable in a single statement.

// Declaring and initializing a variable.
var name = "Jack Sparrow";

Declare and Assign

The below example declares and assigns a variable in separate statements.

  • In Javascript, if a variable is declared but not assigned a value explicitly, then it contains undefined.
// Declaring a variable.
var name;

// Assigning a value to a variable.
name = "Jack Sparrow";

Declare Multiple Variables at Once

The below example defines multiple variables in a single statement.

// Declaring multiple variables.
var name = "Jack Sparrow", age = 25, isMarried = false;
 
/* Declaring multiple variables, one on each line.
var name = "Jack Sparrow",
age = 25,
isMarried = false;

Keywords var Vs let Vs const

Before ES6, we had only var keyword to declare a variable.

ES6 has introduced two new keywords let and const to declare variables in JavaScript.

  • The keyword var is used to declare function-scoped variables.
  • The keywords let and const are used to declare block-scoped variables, which means a new scope is created between a pair of curly braces.
  • The keyword let is used to declare a block-scoped variable, whose value keeps changing in the block of code.
  • The keyword const is used to declare a block-scoped variable, whose value remains constant throughout the block of code.

The below examples define and initialize variables using these keywords.

// Declaring a variable using "var" keyword.
var name = "Jack Sparrow";

// Declaring a variable using "let" keyword.
let name = "John Cena";

// Declaring a constant using "const" keyword.
const PI = 3.14;
// JavaScript throws an error, if we try to reassign a constant value.
PI = 10; // error

Overall

JavaScript variables are used to store and pass data within a program execution.

Related Links