variables javascript best-practices javascript-tutorial javascript-variables var let const data-storage javascript-syntax
Section 2.1: Syntax and Basics
Tutorial 2.1.2: Variables and Constants
Variables and Constants in JavaScript
In JavaScript, variables and constants are used to store data that your program can use and manipulate. This tutorial explains how to declare, initialize, and use variables and constants effectively.
Declaring Variables
Variables in JavaScript can be declared using three keywords: var
, let
, and const
.
var
(Legacy):
- Used in older JavaScript versions but largely replaced by
let
andconst
. - Example:
var message = "Hello, World!";
console.log(message);
let
(Modern):
- Preferred for declaring variables that can change value.
- Example:
let age = 25;
age = 26; // Allowed
console.log(age); // 26
const
(Constants):
- Used for variables whose value should not change.
- Example:
const PI = 3.14;
console.log(PI); // 3.14
Rules for Naming Variables
- Must start with a letter, underscore (
_
), or dollar sign ($
).
- Valid:
name
,_age
,$price
- Invalid:
1name
,@value
- Case-sensitive:
age
andAge
are different.
- Avoid JavaScript reserved keywords (e.g.,
let
,const
,var
).
Variable Initialization
Variables can be declared without assigning a value. Uninitialized variables are undefined
.
Example:
let greeting;
console.log(greeting); // undefined
Using `let` and `const` in Practice
- When to Use
let
:
- Use
let
for variables whose value may change. - Example:
let score = 10;
score += 5; // score is now 15
- When to Use
const
:
- Use
const
for constants or variables that should remain unchanged. - Example:
const API_KEY = "12345";
// API_KEY = "67890"; // Error: Assignment to constant variable
Scope of Variables
- Block Scope (
let
andconst
):
- Variables are accessible only within the block they are declared in.
- Example:
{
let x = 10;
console.log(x); // 10
}
console.log(x); // Error: x is not defined
- Function Scope (
var
):
- Variables are accessible within the entire function they are declared in.
- Example:
function test() {
var y = 20;
console.log(y); // 20
}
console.log(y); // Error: y is not defined
Best Practices
- Use
const
by default; switch tolet
if the value needs to change. - Avoid using
var
in modern JavaScript. - Use meaningful names for variables.
Exercise
- Declare a variable
name
usinglet
and assign it your name. Log it to the console. - Declare a constant
BIRTH_YEAR
with your birth year. Try to change its value and note the error.
Example:
let name = "Alice";
console.log(name);
const BIRTH_YEAR = 1990;
// BIRTH_YEAR = 2000; // Error: Assignment to constant variable
Comments
Please log in to leave a comment.