Skip to main content

Variables in JavaScript

JavaScript variables are used to store data values.

They can hold various types of data, including numbers, strings, and boolean values.

For declaring a variable in JavaScript

use the var, let, or const keyword, followed by the variable name.

var myVariable;
let anotherVariable;
const constantVariable = "This value can't be changed";

What are Variables

In programming, a variable is a named container that can hold a value.

Variables are used to store and manipulate data within a program.

In most programming languages, including JavaScript, a variable is declared using a keyword (such as var, let, or const), followed by an identifier (the variable name), and optionally an initial value.

For example:

let myVariable = 42;

Explanation:

  • let is the keyword used to declare the variable,
  • myVariable is the identifier or name of the variable.
  • 42 is the initial value assigned to the variable.
note

Variables store different data types, such as numbers, strings, Booleans, arrays, objects, etc. and can be changed during program execution.

When to Use var

The var keyword is used to declare a variable.

It is an older way of declaring variables and has been replaced with let and const in modern JavaScript. However, var can still be useful in certain situations.

Guidelines for using var:

  • Use var to declare variables in the global scope.
  • Use var to declare variables within a function.
  • Avoid using var to declare variables within a block of code; use let or const instead.
  • Use const for variables that won't be reassigned and let for variables that may be reassigned.
Avoid var

Although var can be helpful in specific cases, it's generally recommended to use let or const in modern JavaScript.

When to Use const

The const keyword is used to declare a constant variable.

A constant variable is a variable whose value cannot be re-assigned once it has been set.

Some guidelines for using const:

  • Use const to declare a variable when you know its value will not change.
  • Use const to declare a variable that should not be reassigned.
  • Use const to declare a variable that you want to be immutable.
  • Use const for better code readability and robustness.

When to Use let

The let keyword is used to declare a block-scoped variable.

A block-scoped variable is a variable whose scope is limited to the block of code in which it is declared. This means that a variable declared with let is only accessible within the block of code in which it is declared.

Some guidelines for using let:

  • Use let to declare a variable when you know its value will change.
  • Use let to declare a variable that may be reassigned.
  • Use let to declare a variable that you want to be mutable.

Comparison of var, let, and const:

KeywordScopeHoistingMutableReassignableOrigins
varFunctionYesYesYesES5
letBlockNoYesYesES6
constBlockNoNoNoES6

JavaScript Identifiers

An identifier is a name given to a variable, function, or object.

Identifiers are used to refer to these program elements within your code.

Guidelines for naming identifiers in JavaScript:

  • Identifiers can only contain letters (a-z, A-Z), digits (0-9), underscores (_), and dollar signs ($).
  • Identifiers must begin with a letter, underscore, or dollar sign (not a digit).
  • Identifiers are case sensitive. For example, myVariable and myvariable are two different identifiers.
  • JavaScript has a number of reserved words that cannot be used as identifiers, (such as if, else, and for)
  • Identifiers should be descriptive and meaningful, so that they make sense in the context of your code.

Examples of valid identifiers:

let myVariable = 42;
function myFunction() {
/* ... */
}
const MY_CONST = "Hello, world!";
let _privateVariable = "This variable is private";
let $specialVariable = "This variable is special";

Examples of invalid identifiers:

let 1variable = 42; // Identifiers cannot begin with a digit
let my-variable = "Hello"; // Hyphens are not allowed in identifiers
let for = 42; // 'for' is a reserved word in JavaScript

tip

Descriptive and meaningful identifiers are recommended to improve code clarity and context.

The Assignment Operator

The assignment operator = is used to assign a value to a variable. The variable on the left-hand side of the = operator is assigned the value on the right-hand side.

Example:

let x = 42; // assigns the value 42 to the variable x
let y = "Hello, world!"; // assigns the string "Hello, world!" to the variable y

You can also use the assignment operator in combination with arithmetic operators, such as +, -, *, and /, to perform calculations and assign the result to a variable:

let a = 5;
let b = 10;
let c = a + b; // assigns the value 15 to the variable c
note

The assignment operator first evaluates the right-hand side expression and assigns the result to the left-hand side variable. This enables chaining of assignment operators.

JavaScript Data Types

JavaScript is a dynamically-typed language, which means that the type of a value is determined at runtime, based on the value itself.

JavaScript has several built-in data types, including:

  • Number: Represents numeric values, including integers and floating-point numbers. As an example: 42, 3.14.

  • String: Represents a sequence of characters. Strings are enclosed in either single quotes ('...') or double quotes ("..."). As an example: 'Hello, world!', "JavaScript is fun!".

  • Boolean: Represents a logical value that is either true or false.

  • Undefined: Represents a variable that has been declared, but not assigned a value.

  • Null: Represents a deliberate non-value or empty value.

  • Object: Represents a collection of properties, which can be other data types, such as other objects, arrays, or functions.

  • Symbol: Represents a unique identifier, which can be used as a property key in an object.

  • NaN: Represents a value that is "Not a Number". This can occur when you try to perform a mathematical operation on a non-numeric value.

  • Infinity: Represents a value that is greater than any other number. This can occur when you perform a mathematical operation that results in a value that is too large to represent.

note

JavaScript is a dynamically-typed language, allowing a variable to hold a value of any data type and the data type to change at runtime. For instance:

let x = 42; // x is a number
x = "Hello, world!"; // x is now a string

One Statement, Many Variables

In JavaScript, you can declare and initialize multiple variables in a single statement, using a comma-separated list of variable names and values.

This can be a useful shorthand when you want to declare several variables at once.

As an example:

let x = 42, y = "Hello, world!", z = true;

Explanation:

  • This statement declares three variables (x, y, and z) and initializes them with the values 42, "Hello, world!", and true, respectively.

In addition, if you need to declare multiple variables with the same initial value, you can use the following syntax:

let x = y = z = 42;

JavaScript dollar sign ($)

The dollar sign ($) is a valid identifier character in JavaScript. It can be used in variable names, function names, and property names.

Examples:

let $variable = 42;
function $myFunction() {
/* ... */
}
const $myObject = {
$property: "Hello, world!"
};

Using the $ in Template Literals

Template literals are enclosed in backticks () instead of single or double quotes. They allow you to embed expressions within a string, using the ${...}` syntax.

Example:

let x = 42;
let y = "Hello, world!";
let z = true;
let myString = `x = ${x}, y = ${y}, z = ${z}`;
console.log(myString); // prints "x = 42, y = Hello, world!, z = true"

JavaScript Underscore (_)

The underscore (_) is a valid identifier character in JavaScript. It can be used in variable names, function names, and property names.

Examples:

let _variable = 42;
function _myFunction() {
/* ... */
}
const _myObject = {
_property: "Hello, world!"
};