Skip to main content

JavaScript Variables

In JavaScript, as in many other programming languages, variables act as containers to store data values. They are fundamental for storing, manipulating, and retrieving information in your code.

Variables are akin to boxes capable of holding various data types such as numbers, strings, booleans, etc. We will delve deeper into these data types later in the course.

To use a variable in JavaScript, you need to declare it.

Declaring a Variable

JavaScript is case-sensitive, meaning the variable name must precisely match the name you use in your code. You can declare a variable using the following syntax:

name = "John";

In this example, we declare a variable named name and assign it the value "John". Similarly, we can assign a number to the variable:

age = 20;

The = sign is the assignment operator, used to assign a value to a variable.

This is the simplest way to declare a variable in JavaScript. However, there are other ways, such as let, var, and const, which we'll explore later in the course.

Declaring Multiple Variables

You can declare multiple variables in a single line:

name = "John", age = 20;

While JavaScript allows this, it is not recommended due to difficulties in maintenance and debugging. We use keywords like let, const, and var for more structured variable declaration.

The var Keyword

The var keyword is traditionally used to declare a variable in JavaScript:

var name = "John";

However, using var has drawbacks:

  • Variables declared with var are global and function-scoped.
  • Variables declared with var are hoisted.

For these reasons, it's advisable to use let or const instead, which we'll cover later in the course.

Arithmetic Operations

Variables also allow us to perform arithmetic operations. For example:

var value = 2 + 13; // output: value = 15

If you print the value of value to the console, you will get 15.

Note: We discussed the console in the previous chapter. Learn more about it here

In the upcoming chapters, we'll explore more complex examples to deepen your understanding of variables in JavaScript.