JavaScript Variables
Written by Avinash Malhotra
Updated on
Variables in JavaScript
A JavaScript variable is a name that refers to a value. For example, let score = 0 declares a variable named score and gives it the initial value 0.
JavaScript is dynamically typed. Values have types, and a variable declared with let or var can refer to values of different types over time. For example, after let result = 42, assigning result = "pending" changes the value from a number to a string. See JavaScript data types.
Variables can also refer to arrays, functions and other objects. Dynamic typing applies whether the engine interprets or compiles the code.
A declaration introduces a name. An initializer supplies its starting value. For example, let score; leaves score with the value undefined once the declaration runs. A later assignment such as score = 10 changes that value.
Use const when a name should keep the same value and let when you need to reassign it. You will also encounter var in older scripts. The comparison table shows how all three behave.
How to Declare Variables in JavaScript
Declare a variable at the top level of a script, inside a function or inside a block. The following examples show single declarations, multiple names in one declaration and a declaration without an initializer.
<script>
var x=7; // value of x is 7
let y=9; // value of y is 9
const pi=3.14; // value of pi is 3.14
let a=2, b=3, c=5; // multiple variables in single line
let u; // u is undefined
</script>
Change a Variable's Value
To reassign a variable declared with var or let, use its name followed by = and the new value.
var x="hello";
console.log(x); // "hello"
x="hola";
console.log(x); // "hola"
let y="world";
console.log(y); // "world"
y="mundo";
console.log(y); // "mundo"
Here, x changes from “hello” to “hola”, and y changes from “world” to “mundo”. Each name is declared once.
Variable Naming Convention in JavaScript
Choose a name that describes the value, such as userName or itemCount. JavaScript identifiers follow these rules.
- Reserved words such as
class,forandconstcannot serve as variable names. - Start a name with a letter, an underscore or a dollar sign. Digits can appear after the first character.
- Use camel case or underscores to separate words. For example,
userNameanduser_nameare valid. Spaces and hyphens are invalid in variable names. - Names are case-sensitive. For example,
x1andX1refer to different names.
Strict mode in JavaScript
ECMAScript 5 introduced strict mode. Assigning to a name that has no binding throws a ReferenceError in strict mode. You can declare variables with var, let or const.
Strict mode helps catch spelling mistakes. For example, if you declare let total = 0 and then assign to the undeclared name totla, the error identifies the unexpected name.
How to use strict mode?
To enable strict mode for a classic script, put "use strict"; before its first ordinary statement. You can also use the directive at the beginning of a function with a simple parameter list.
<script>
"use strict";
</script>
Strict mode vs. sloppy mode
Strict mode
var x=3;
var y=10;
- Assignment to an undeclared name throws an error
- Legacy octal literals such as
010are invalid. Use0o10for eight.
Sloppy mode
x=3;
y=010;
- An undeclared assignment can create a global property
- The legacy octal literal
010represents eight.
JavaScript modules always run in strict mode.
JavaScript Sloppy Mode
A classic script uses non-strict (sloppy) mode by default. In the example below, assigning to the undeclared name x2 creates a property on the global object.
<script>
var x1="tech altum"; // allowed
x2="javascript"; // also allowed
</script>
An accidental global can persist after a function returns and interfere with other scripts on the page.
Variable Hoisting
Hoisting describes the effect of setting up declarations before the statements in their scope run. A variable declared with var starts with the value undefined. Its initializer runs when execution reaches the declaration.
For example, reading x immediately before var x = 1 gives undefined. Reading it after that statement gives 1.
A let or const binding exists from the start of its scope. Reading it before initialization throws a ReferenceError. This interval is called the temporal dead zone.
In the script below, execution stops at the first error. To see the final three values, comment out both reads marked ReferenceError and run the script again.
<script>
console.log(x); // logs undefined
console.log(y); // throw ReferenceError
console.log(z); // throw ReferenceError
var x=1;
const y=2;
let z=4;
console.log(x); // logs 1
console.log(y); // logs 2
console.log(z); // logs 4
</script>
Why declare a variable?
The declaration tells JavaScript which scope owns the name. This matters when two scopes use the same name. For example, an inner let x hides an outer x throughout the inner block, including during the temporal dead zone.
Declare each variable before its first use so that readers can see where its value comes from.
JavaScript Scope: Local vs Global Variables
Scope determines where code can refer to a name. JavaScript has global, module, function and block scopes. An inner scope can read names from an enclosing scope unless it declares the same name.
Global Variables
At the top level of a classic browser script, var, let and const declare global bindings. A top-level var also creates a property on window. Top-level declarations in a module belong to that module.
Global Variables Example
1
2
var x=1; // global variable
var y=2; // global variable
function myFunction(){
console.log(x) // logs 1
console.log(y); // logs 2
}
myFunction();
Local Variables
A variable declared inside a function is local to that function or to a block within it. In the example, the function can read both variables. Outside the function, either lookup raises a ReferenceError when tested separately. An uncaught error stops the script.
Local Variables Example
local variable
local variable
Error
Error
function myFunction(){
var x="local variable";
var y="local variable";
console.log(x); // valid
console.log(y); // valid
}
myFunction()
console.log(x); // invalid
console.log(y); // invalid
Global variables inside a function
Run each example in a fresh classic script. The function can access the outer name y. After the function returns, reading its local x throws an error. Comment out that line to test the final read of y.
Declared global variable
local
global
Error
global
var y;
function myFunction(){
var x="local";
y="global ";
console.log(x); // valid
console.log(y); // valid
}
myFunction()
console.log(x); // invalid
console.log(y); // valid
Accidental global in sloppy mode
local
global
Error
global
function myFunction(){
var x="local";
y="global ";
console.log(x);// valid
console.log(y);// valid
}
myFunction()
console.log(x); // invalid
console.log(y); // valid
JavaScript Block Scope: let and const
ECMAScript 2015 (ES6) introduced let and const. When declared inside a block such as an if body, their names are accessible within that block and its nested scopes.
A var declaration inside an ordinary if block belongs to the surrounding function, script or module scope.
JavaScript let
Use let for a block-scoped variable that you intend to reassign. Two nested blocks can each declare a variable with the same name.
In the example, the name x is available only inside the braces. Reading it inside the block before the declaration would throw a ReferenceError.
<script>
{
let x="user"; // block scope
}
</script>let vs var
<script>
let i=2; // global scope
{
let i=3; // block scope
console.log(i); // 3
}
console.log(i); // 2
</script>
JavaScript const
A const declaration binds a name to a value and prevents reassignment. For example, const pi = Math.PI keeps the same numeric value. With const user = { name: "Avi" }, you can update user.name because the variable still refers to the same object.
<script>
const pi=Math.PI; // pi is a const
</script>
<script>
const user="avi";
user="xyz"; // throws TypeError
</script>
var vs let vs const
Choose a declaration by asking two questions. Where should the name be accessible, and will you assign a different value to it later? The table summarises the ECMAScript declaration rules.
| Property | var | let | const |
|---|---|---|---|
| Read before declaration | undefined | ReferenceError (temporal dead zone) | ReferenceError (temporal dead zone) |
| Repeat the same declaration in one scope | yes | no | no |
| Reassign the variable | yes | yes | no |
| Scope | Enclosing function, script or module | block | block |
| Creates a global property at the top level of a classic script | yes | no | no |
- Use strict mode in classic scripts to catch accidental global assignments.
- Modern browsers support both
letandconst. - Choose
letfor a counter that changes andconstfor a value you assign once.
Frequently Asked Questions
What is the difference between var, let, and const in JavaScript?
Inside a function, var is scoped to the function. let and const respect nested block boundaries. Both var and let allow reassignment. Use const when the binding should keep its initial value.
What is variable hoisting in JavaScript?
Hoisting describes how declarations affect their scope before execution reaches them. Reading a new var binding before its initializer gives undefined. Reading a let or const binding during its temporal dead zone throws a ReferenceError.
What is strict mode in JavaScript?
Strict mode applies additional language checks. For example, assigning to an undeclared name throws a ReferenceError. Start a classic script with "use strict"; to enable it. Modules use strict mode automatically.
What is the difference between local and global variables in JavaScript?
A global variable belongs to the global scope and is visible in nested scopes unless another declaration hides it. A local variable belongs to a function or block and can be accessed only within that scope and its nested scopes.