Creating Variables
Declaration of a Variable
Before using a variable in JavaScript, it must be declared. Variables are declared using the keyword var followed by the variable name, as shown in the example below.
<script type="text/javascript">
var firstVariable;
var secondVariable;
</script>
It's also possible to declare multiple variables using the same var keyword.
<script type="text/javascript">
var firstVariable, secondVariable;
</script>
Initialization of a Variable
Storing a value in a variable is called initializing the variable. A variable can be initialized at the time of declaration or later when the variable is needed.
In the example below, the variable "name" is initialized to the value "Marko" during the declaration, while the variable "yearOfBirth" is initialized after the declaration.
<script type="text/javascript">
var name = "Marko";
var yearOfBirth;
yearOfBirth = 1988;
</script>
Use the keyword var only for declaration or initialization once in the lifetime of a variable in a document. You should not declare a variable multiple times.
JavaScript is an untyped or dynamic programming language, which means that variables can contain any data type. Unlike many other languages, JavaScript does not need to specify the data type of a variable at the time of declaration. JavaScript can automatically change the data type of a variable during script execution.
var variable = 20; // Variable is now a Number var variable = "Text"; // Variable is now a String var variable = true; // Variable is now a Boolean
Variable scope
The scope of a variable is the region of the script in which the variable is defined and within which it can be used. JavaScript variables can be of only two types:
- Global Variables - Global variables have global scope, which means they can be defined anywhere within the JavaScript code.
- Local Variables - Local variables have local scope and are visible only within the function in which they are defined. Function parameters are always local only to that function.
Within the body of a function, local variables take precedence over identically named global variables. If a local variable or function parameter is declared with the same name as a global variable, the global variable will be "hidden".
<html>
<body onload="checkVariableScope();">
<script type="text/javascript">
// Declaration and initialization of a global variable
var myVariable = "Global variable";
function checkVariableScope ( ) {
// Declaration and initialization of a local variable
var myVariable = "Local variable";
document.write(myVariable);
}
</script>
</body>
</html>
The example contains a function checkVariableScope() that outputs the value of a variable. The function is called on the onLoad method of the <body> element. After executing the code, the text "Local variable" will be printed as it will override the global one.
In addition to the var keyword, JavaScript ES6 introduced two more ways to declare variables, using the let and const keywords. They offer more control over variable scope and mutability.
Let keyword
The let keyword allows you to declare variables that are limited in scope to the block, statement, or expression in which they are used, unlike var variables which are globally scoped or function/locally scoped. This is known as block scope.
if (true) {
let x = 12;
console.log(x); // Output: 12
}
console.log(x); // Error: x is not defined
In the above example, x is only available within the if block, so attempting to log x outside of the block results in an error.
Const keyword
The const keyword allows you to declare variables whose values are never intended to change. The variable is constant, meaning if you try to change its value later in the code, the JavaScript interpreter will throw an error.
const PI = 3.14; PI = 3.1415; // Error: assignment to constant variable.
In the above example, trying to change the value of PI results in an error.
Key differences between var, let, and const:
- var is function scoped while let and const are block scoped.
- var variables can be updated and re-declared within its scope. let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.
- While var and let can be declared without being initialized, const must be initialized during declaration.
var varVariable; let letVariable; const constVariable; // Error: Missing initializer in const declaration
In the above example, while varVariable and letVariable are valid declarations, constVariable results in an error because it's not initialized at the time of declaration.
Difference between var, let and const
Scope:
- var: Variables declared with var have function scope, which means they are function-scoped or globally scoped, depending on whether they are declared inside a function or outside of any function.
- let: Variables declared with let have block scope, which means they are limited in scope to the block (e.g., within curly braces { }) where they are declared. This includes loops, conditionals, and functions.
- const: Like let, variables declared with const also have block scope. However, const variables cannot be reassigned after declaration.
Hoisting:
- var: Variables declared with var are hoisted to the top of their function or global scope. This means that they are available throughout the function or global context even before they are declared. However, only the declaration (not the initialization) is hoisted.
- let and const: Variables declared with let and const are also hoisted, but they are not initialized. If you try to access them before declaration, you'll get a "ReferenceError."
Reassignment:
- var: Variables declared with var can be reassigned, even in a different scope.
- let: Variables declared with let can be reassigned within the same block scope, but not in a different scope.
- const: Variables declared with const cannot be reassigned after they are initialized. They are considered constants.
Temporal Dead Zone (TDZ):
- var: var variables are not affected by the TDZ, as they are hoisted with an undefined value.
- let and const: let and const variables are affected by the TDZ. Accessing them before declaration results in a ReferenceError.
Global Object Property:
- var: Variables declared with var become properties of the global object (window in a browser), which can lead to unintended global variable declarations.
- let and const: Variables declared with let and const do not become properties of the global object, reducing the risk of unintentional global variable collisions.
In modern JavaScript, it is recommended to use let for variables that need to be reassigned and const for variables that should not be reassigned. var should generally be avoided due to its hoisting behavior and global scope implications. These changes were introduced in ES6 (ECMAScript 2015) to address some of the issues associated with var.
JavaScript Variable Names
Naming variables in JavaScript should follow these rules:
- Names can contain letters, numbers, underscores, and dollar signs ($)
- Names must start with a letter, underscore, or dollar sign ($)
- Names should not start with a number (0-9)
- Names are case-sensitive (variableName and VariableName are two different variables)
- Reserved words are not allowed to be used
Reserved words
A list of all reserved words in JavaScript is given in the next table. They should not be used for names of variables, functions, objects, and similar.
|
Abstract boolean break byte case catch char class const continue debugger default delete do double |
else enum export extends false final finally float for function goto if implements import in |
instanceof int interface long native new null package private protected public return short static super |
switch synchronized this throw throws transient true try typeof var void volatile while with |