Introduction to Variables in JavaScript
One of the fundamental concepts in JavaScript (and in programming in general) is the use of variables. A variable is a way to store a value or a reference to a value in the computer's memory so that it can be accessed and used later in the program.
The Box Analogy
A widely spread, real-world analogy is that a variable in JavaScript can be thought of as a "box" for data, with a uniquely-named label on it. Just like a physical box can hold different things, a variable can hold different values of different types, such as numbers, strings, and booleans.
let message = "Hello!";
message = "World!";
console.log(message); // "World!"
Just like you can remove things from a physical box, you can also remove the value from a variable by reassigning it to a new value.
let message = "Hello";
message = null;
console.log(message); // null
You can also imagine copying data from one variable to another, just like you can move the content of one box to another.
let hello = "Hello world!";
let message;
message = hello;
console.log(hello); // "Hello world!"
console.log(message); // "Hello world!"
Keep in mind that variables should be declared only once. Declaring the same variable multiple times will cause an error.
let message = "This";
let message = "That"; // error: "message" has already been declared
Declaring a Variable
Declaring a variable in JavaScript involves using the keyword var
, let
, or const
and giving the variable a name, followed by the assignment operator (=) and the value you want to assign to it.
For example, to declare a variable called age
and assign it the value 30
, you would write:
let age = 30;
We should note that the var
keyword is somewhat legacy, and let
and const
are recommended for modern JavaScript. let
is used for variables whose value can be reassigned and const
is used for variables whose value should not be reassigned once it is set.
var
The var keyword is used to declare a variable and is the oldest way of declaring variables in JavaScript. Variables declared with var have function scope, meaning they can be accessed within the function in which they were declared, as well as within any nested functions. Variables declared with var are also hoisted or "raised" to the top of their scope. In turn, this can lead to unexpected behavior and that's why it's recommended not to use var
in modern JavaScript.
var x = "I am a global variable";
function myFunction() {
var y = "I am a local variable";
console.log(x); // "I am a global variable"
console.log(y); // "I am a local variable"
}
let
let
is introduced in ECMAScript 6 (ES6). It's block-scoped, meaning that the variable can only be accessed within the block in which it was declared. Variables declared with let
are not hoisted to the top of their scope, which can prevent unexpected behavior.
let x = "I am a global variable";
function myFunction() {
let y = "I am a local variable";
console.log(x); // "I am a global variable"
console.log(y); // "I am a local variable"
}
const
const
is also introduced in ECMAScript 6 (ES6). We use it to declare a variable that cannot be reassigned after it's been declared. A const variable must be assigned a value when it's declared, and that value cannot be changed later. Just like let
, const
is also block-scoped.
Variable scope
Variable scope refers to the parts of a program where a variable can be accessed. In JavaScript, there are two types of variable scope: global and local.
A global variable is declared outside of any function and can be accessed from anywhere in the program. For example:
let globalVar = "I am a global variable";
function myFunction() {
console.log(globalVar); // "I am a global variable"
}
A local variable, on the other hand, is declared inside a function and can only be accessed within that function. For example:
function myFunction() {
let localVar = "I am a local variable";
console.log(localVar); // "I am a local variable"
}
console.log(localVar); // ReferenceError: localVar is not defined
Hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top. Hoisting can cause some confusion and unexpected behavior, especially when it comes to variable declarations. In JavaScript, variable declarations are hoisted to the top of their scope, but the assignments are not.
For example:
console.log(x); // undefined
var x = 5;
The JavaScript interpreter treats this code as if it were written like this:
var x;
console.log(x); // undefined
x = 5;
So, hoisting is a mechanism of JavaScript that moves the declaration of variables and functions to the top of their scope. This means that you can use variables and functions before they are declared. However, their assignments are not hoisted and they are initialized with the value undefined
.
Best Practices for Naming Variables
Following naming conventions makes your code more readable and maintainable. Here are a few important practices for naming variables in JavaScript:
Variables are case-sensitive, so myVariable and myvariable are different variables.
Use lowerCamelCase for variable names. This means that the first word of the variable name should be in lowercase, and any subsequent words should start with a capital letter, with no underscores or hyphens. For example:
myVariable
orcounter
.Use descriptive names. Variable names should be self-explanatory and describe the value they contain. For example, use
counter
instead ofc
.Avoid using single-letter variable names. Single-letter variable names are often used in simple examples and mathematical notation, but they can be difficult to understand in larger programs.
Names cannot start with a number and cannot contain spaces or special characters other than the dollar sign( $ ) and underscore ( _ )
JavaScript is a loosely typed language which means you don't need to specify the type of variable while declaring. The variable's type can change depending on the value it's assigned.
Don't use reserved keywords as variable names. Certain words in JavaScript are reserved for specific purposes, and using them as variable names will result in an error.
Examples of Using Variables
Once a variable is declared, you can use it in various ways in your program.
Variables in Expressions
You can use it in an expression:
let a = 2;
let b = 3;
let c = a + b; // c is now 5
Storing Results of a Function Call
You can also use a variable to store the result of a function call:
let d = Math.random(); // d is now a random number between 0 and 1
Variables as Arguments
You can also use a variable as an argument when calling a function:
function greet(name) {
console.log("Hello, " + name + "!");
}
let e = "Bob";
greet(e); // prints "Hello, Bob!"
Summary
Variables are an essential concept in JavaScript, allowing us to store and manipulate data. By understanding the basics of how to declare variables using and following best practices for naming conventions, you're on your way to writing more readable and maintainable code.
However, this is just the tip of the iceberg. It's natural to encounter more advanced concepts and nuanced cases that will help you write more powerful and efficient code. Keep an eye out for future articles, as we'll be diving deeper into these and other topics to help you become a more proficient JavaScript user.