Variables and Constants in JavaScript
In this article we'll dive into what variables are, how to use them, and why they're important.
One of the most important concepts in JavaScript is the use of variables and constants. These are essential for storing and managing data within your programs. In this article we'll dive into what they are, how to use them, and why they're important.
If JavaScript isn't your first programming language, this will be easy for you because you already understand the concept of variables.
What Is a Variable?
A variable is like a container that holds data which can change over time. Think of it as a box where you can store different types of items, and you can replace the item in the box whenever you need to.
You can also think of a variable as a name given to a value. Instead of writing the value every time you need it, you can use the variable. This makes your code cleaner and easier to understand.
Variables in JavaScript are quite similar to variables in math. In algebra, variables represent numbers with letters. For example:
a = b + 2
In this equation:
a
andb
are variables.They represent values that can change.
If b
is 3, then a
would be 5
because a = 3 + 2
.
In JavaScript, you can write this equation as:
let b = 3;
let a = b + 2;
console.log(a); // Output: 5
Here, a
and b
are variables. You can change the value of b
whenever you want, and a
will be updated accordingly.
Declaring Variables
To use a variable in JavaScript, you first need to declare it. There are three keywords you can use to declare a variable: var
, let
, and const
.
var
This is the oldest way to declare a variable.
It has a function scope, meaning it is only available within the function it is declared.
var
is not recommended for declaring variables as there are a lot of nuances associated with it. You should never usevar
unless you need to.
In the example below, we have declared a variable name
.
var name;
let
Introduced in ES6 (ECMAScript 2015).
It has a block scope, which means it is only available within the block (like inside an
if
statement or a loop) it is declared. Don't worry if you don't understand what a loop or if statement is.
In the example below, we have declared a variable age
.
let age;
const
Also introduced in ES6.
- It declares a constant variable, meaning its value cannot be changed once assigned. Unlike
let
andvar
, the value of a variable declared withconst
cannot be changed.
- It declares a constant variable, meaning its value cannot be changed once assigned. Unlike
It also has a block scope.
In the example below, we have declared a variable date.
const date;
Assigning Values to Variables
We've learned how to declare variables, so let's look at how to assign values to a variable.
To assign a value to a variable that has been declared (using either var
, const
, or let
), we write down the variable. In front of the variable we place an equal-to sign and then place the value to be assigned after the equal-to sign.
The example below shows the string Ahmad
being assigned to the variable name
that we declared earlier. Now whenever we need the string 'Ahmad', we just call the variable name
. The output of console logging name
would be 'Ahmad'. You can try this in your browser console.
var name;
name = 'Ahmad';
console.log(name); // output: Ahmad
We can also assign a value to the age
and date
variable that were declared earlier.
let age;
age = 18;
const date;
date = '13 July, 2024';
console.log(age); //output: 18
console.log(date); //output: 13 July, 2024
Declaring and Assigning Variables
We can declare a variable and assign it a value in one step. This is the ideal way to declare a variable. The examples below show how to declare a variable and assign it a value in one line.
var name = 'Ahmad';
let age = 18;
const date = '13 July, 2024';
console.log(name); // output: Ahmad
console.log(age); //output: 18
console.log(date); //output: 13 July, 2024
Types of Variables
Variables can hold different types of data, such as:
String: Text data.
let greeting = "Hello, world!";
Number: Numeric data.
let score = 100;
Boolean: True or false values.
let isValid = true;
Array: A list of items.
let fruits = ["apple", "banana", "cherry"];
Object: A collection of key-value pairs.
let person = { name: "Alice", age: 30 };
If some of these data types look unfamiliar to you, don't worry. You'll learn more about them in the next article.
Reassigning Variables
With var
and let
, you can change the value of a variable after it is declared.
let mood = "happy";
mood = "sad";
console.log(mood); // Output: sad
Constants in JavaScript
Constants are used for values that should not change throughout the execution of your program. Once you set a value to a constant, you cannot reassign it.
Declaring Constants
You declare a constant using the const
keyword.
If we try to change the value of birthYear
, it will cause an error. You can try this in your browser console.
const birthYear = 1990;
console.log(birthYear); // Output: 1990
// birthYear = 1991; // This will cause an error
Benefits of Constants
Readability: Using constants makes your code easier to read and understand because it is clear that the value should not change.
Safety: Prevents accidental changes to the values that are critical to your program.
Scope of Variables and Constants
Scope determines where in your code a variable or constant is accessible.
Global Scope: Variables declared outside any function or block. They can be accessed from anywhere in the code.
var globalVar = "I'm global"; console.log(globalVar); // Output: I'm global
Function Scope: Variables declared inside a function. They can only be accessed within that function.
function showMessage() { var message = "Hello, function scope!"; console.log(message); // Output: Hello, function scope! } // console.log(message); // This will cause an error
Block Scope: Variables declared inside a block (e.g., inside
{}
of anif
statement or a loop). Only accessible within that block.if (true) { let blockVar = "I'm block scoped"; console.log(blockVar); // Output: I'm block scoped } // console.log(blockVar); // This will cause an error
Understanding variables and constants is crucial for writing effective JavaScript code.
In summary, variables (var
, let
) are used when you need to store data that might change, while constants (const
) are used for values that should stay the same. Remember the scope rules to avoid common pitfalls. With these basics in hand, you're well on your way to becoming proficient in JavaScript. That's a wrap, see you in the next one!