JavaScript Variables
JavaScript variables are used to store data that can be changed later on. These variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it.
- Using the ‘var’ keyword.
- Using the ‘let’ keyword.
- Using the ‘const’ keyword.
VAR
var is the traditional way of declaring variables in JavaScript, but it has some quirks, such as function-scoped (instead of block-scoped), and can lead to issues in large codebases.
It is generally considered less preferred now in favor of let and const.
var color;var x = 5;var name = 'John';x = 10; // You can change the value of a variable declared with 'var'.LET
let was introduced in ES6 (ECMAScript 2015) and is block-scoped, meaning it’s only accessible within the block (e.g., inside a loop or a conditional).
It is useful when the variable’s value is expected to change.
let x = 5;let name = 'John';x = 10; // You can change the value of a variable declared with 'let'.CONST
const is also block-scoped and is used for variables that should not be reassigned once they are initialized. If the variable holds an object or an array,
you can still modify the contents of the object/array, but you cannot reassign the variable itself to a new object or array.
const pi = 3.14159;pi = 3.14; // This will throw an error because 'pi' cannot be reassigned.
const person = { name: 'John', age: 30 };person.age = 31; // This is allowed, because we're modifying the object, not the variable itself.Variable Naming Rules:
- Variables must start with a letter, underscore (_), or dollar sign ($).
- The rest of the variable name can include letters, numbers, underscores, or dollar signs.
- Variable names are case-sensitive (e.g., myVar and myvar are different).
- You cannot use JavaScript reserved keywords (e.g., let, const, function, class, etc.) as variable names.
Re-declaration and Re-assignment
- var: Can be redeclared and reassigned within the same scope.
- let: Can be reassigned but cannot be redeclared in the same block scope.
- const: Cannot be reassigned or redeclared.
Variable Hoisting:
Variables declared using var are hoisted to the top of their scope, meaning you can reference them before their actual declaration, though their value will be undefined until the assignment is executed.
In contrast, variables declared with let and const are also hoisted, but they cannot be accessed before their declaration due to the “temporal dead zone” (TDZ).
console.log(x); // undefinedvar x = 5;console.log(x); // 5
console.log(y); // ReferenceError: Cannot access 'x' before initializationlet y = 5;