In JavaScript, variables are used to store data values that can be referenced and manipulated in a program. Variables can store different types of data and are a fundamental part of writing JavaScript code.
1. Declaring Variables
JavaScript provides three ways to declare variables: var
, let
, and const
.
1.1 var
- The oldest way to declare variables.
- Function-scoped or globally-scoped.
- Can be re-declared and updated.
- Hoisted to the top of their scope.Example:
var x = 5; var x = 10; // Re-declaration allowed
1.2 let
- Introduced in ES6 (ES2015).
- Block-scoped (limited to the block where it is declared).
- Can be updated but not re-declared in the same scope.Example:
let y = 10; y = 20; // Update allowed
1.3 const
- Introduced in ES6 (ES2015).
- Block-scoped.
- Cannot be updated or re-declared (used for constants).Example:
const z = 30; // z = 40; // Error: Assignment to constant variable
2. Variable Naming Rules
- Must begin with a letter, underscore (
_
), or dollar sign ($
). - Subsequent characters can include letters, numbers, underscores, and dollar signs.
- Case-sensitive (
myVariable
andMyVariable
are different). - Cannot be a reserved keyword (e.g.,
let
,const
,if
).Example:let myVariable = 100; let _privateVar = "private";
3. Variable Scope
- Global Scope: Variables declared outside any function or block are in the global scope and accessible from anywhere.
- Function Scope: Variables declared inside a function are local to that function.
- Block Scope: Variables declared with
let
andconst
inside a block{}
are limited to that block.Example:function testFunction() { var localVar = "I am local"; console.log(localVar); // Accessible here } // console.log(localVar); // Error: localVar is not defined
4. Hoisting
- Variables declared with
var
are hoisted to the top of their scope but not initialized. let
andconst
are also hoisted but remain uninitialized until their declaration is encountered in the code (Temporal Dead Zone).Example:console.log(a); // undefined var a = 5; // console.log(b); // Error: Cannot access 'b' before initialization let b = 10;
5. Best Practices
- Use
let
andconst
instead ofvar
for block-level scoping. - Use
const
when the variable should not be reassigned. - Use meaningful variable names for readability.
- Initialize variables when you declare them to avoid
undefined
.
Summary
Variables are a fundamental part of JavaScript, allowing you to store and manipulate data. Understanding the differences between var
, let
, and const
, along with scoping and hoisting, is essential for writing effective and error-free JavaScript code.