JavaScript Variables
Variables are containers for storing data (values). In JavaScript, you can use the var
, let
, or const
keyword to declare a variable.
1. Declaring Variables
You can declare a variable using var
, let
, or const
. The let
and const
keywords were introduced in ES6 (2015).
Example:
// Using var
var x = 5;
var y = 6;
var z = x + y;
// Using let
let a = 10;
let b = 20;
let c = a + b;
// Using const
const pi = 3.14;
const radius = 5;
const area = pi * radius * radius;
2. Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript has two types of scope: global and local.
- Global Scope: A variable declared outside a function becomes global.
- Local Scope: A variable declared within a function is local to that function.
Example:
// Global variable
var globalVar = "I am a global variable";
function myFunction() {
// Local variable
var localVar = "I am a local variable";
console.log(localVar);
}
myFunction();
console.log(globalVar);
// console.log(localVar); // This will cause an error
3. Variable Hoisting
In JavaScript, variable declarations are hoisted (lifted) to the top of their scope. However, the initialization is not hoisted.
Example:
console.log(hoistedVar); // Output: undefined
var hoistedVar = "This variable is hoisted";
// let and const are not hoisted
// console.log(notHoistedVar); // This will cause an error
let notHoistedVar = "This variable is not hoisted";
4. Re-declaring Variables
Variables declared with var
can be re-declared. Variables declared with let
and const
cannot be re-declared in the same scope.
Example:
// var can be re-declared
var redeclareVar = "First declaration";
var redeclareVar = "Second declaration";
// let and const cannot be re-declared
let redeclareLet = "First declaration";
// let redeclareLet = "Second declaration"; // This will cause an error
const redeclareConst = "First declaration";
// const redeclareConst = "Second declaration"; // This will cause an error
5. Constants
Variables declared with const
are read-only. They cannot be reassigned, but their properties can be changed if they are objects.
Example:
const constantVar = "I am constant";
// constantVar = "Trying to change"; // This will cause an error
const person = {
name: "John",
age: 30
};
// You can change properties of a constant object
person.age = 31; // This is allowed
console.log(person);
6. Best Practices
- Use
let
andconst
instead ofvar
to avoid hoisting issues and improve code readability. - Use
const
for variables that should not change. - Declare variables at the top of their scope to avoid confusion.
By following these guidelines, you can write cleaner, more maintainable JavaScript code.