In JavaScript, variables are used to store data values that can be used and manipulated later in the program. Think of a variable as a container that holds information.
Variable Naming Rules
- Names can contain letters, digits, underscores (
_
), and dollar signs ($
). - Must start with a letter,
$
, or_
. - Case-sensitive (e.g.,
myName
andmyname
are different). - Cannot use reserved keywords (like
let
,class
,if
, etc.).
Example:
let myName = "Alice";
let $price = 100;
let _value = 50;
Declaring Variables
JavaScript provides three keywords to declare variables:
var
: The old way (not commonly used anymore).let
: The modern way, allows variable re-assignment.const
: Used for variables that should not be re-assigned
1. Using var
- Can be re-declared and updated.
- Not recommended for modern coding because of its scope issues.
Example:
var name = "John";
console.log(name); // Output: John
name = "Doe";
console.log(name); // Output: Doe
2. Using let
- Can be updated but cannot be re-declared within the same scope.
- Block-scoped (only works inside the block it’s defined).
Example:
let age = 25;
console.log(age); // Output: 25
age = 30; // Updating the value
console.log(age); // Output: 30
3. Using const
- Cannot be updated or re-declared.
- Must be initialized when declared.
- Used for values that should stay constant (like
PI
or configurations).
Example:
const pi = 3.14;
console.log(pi); // Output: 3.14
// pi = 3.15; // Error: Assignment to constant variable.
Scope of Variables
- Global Scope: A variable declared outside functions is accessible everywhere.
- Function Scope: A variable declared inside a function is only accessible within that function.
- Block Scope: Variables declared with
let
andconst
are limited to the block{}
.
Example:
function testScope() {
let localVariable = "I exist only inside this function!";
console.log(localVariable);
}
// console.log(localVariable); // Error: localVariable is not defined
Best Practices
- Use
const
by default, and switch tolet
only when you need to reassign. - Avoid using
var
. - Use meaningful variable names that describe their purpose.
Code Example: Putting It All Together
// Using const for constant values
const pi = 3.14;
// Using let for variables that can change
let radius = 5;
let area = pi * radius * radius;
console.log("Area of the circle:", area); // Output: Area of the circle: 78.5
// Using var (not recommended)
var greeting = "Hello, JavaScript!";
console.log(greeting); // Output: Hello, JavaScript!
// Demonstrating scope
if (true) {
let scopedVar = "I am inside a block!";
console.log(scopedVar); // Output: I am inside a block!
}
// console.log(scopedVar); // Error: scopedVar is not defined