Variables

Lesson 6
Author : Afrixi
Last Updated : March, 2023
Javascript - Program the Web
This course covers the basics of programming in Javascript.

In JavaScript, variables are used to store information that an application needs to work with. For example, in an online shop, variables may store information about the goods being sold and the shopping cart. In a chat application, variables may store information about users, messages, and much more.

A variable is a “named storage” for data. We can use variables to store goodies, visitors, and other data. In JavaScript, to create a variable, we use the let keyword.

For example, the statement below creates a variable with the name "message":

let message;

We can put some data into the variable by using the assignment operator =:

let message;

message = 'Hello'; // store the string 'Hello' in the variable named message

The string is now saved into the memory area associated with the variable. We can access it using the variable name:

let message;
message = 'Hello!';
alert(message); // shows the variable content

To be concise, we can combine the variable declaration and assignment into a single line:

let message = 'Hello!'; // define the variable and assign the value
alert(message); // Hello!

We can also declare multiple variables in one line, but we don’t recommend it for the sake of better readability:

let user = 'John', age = 25, message = 'Hello';

The multiline variant is a bit longer, but easier to read:

let user = 'John';
let age = 25;
let message = 'Hello';

Some people also define multiple variables in this multiline style:

let user = 'John',
  age = 25,
  message = 'Hello';

Technically, all these variants do the same thing. It’s a matter of personal taste and aesthetics.

In older scripts, you may also find another keyword: var instead of let. The var keyword is almost the same as let. It also declares a variable, but in a slightly different, “old-school” way. There are subtle differences between let and var, but they do not matter for us yet.

A variable can be imagined as a “box” for data, with a uniquely-named sticker on it. We can put any value in the box, and we can change it as many times as we want. When the value is changed, the old data is removed from the variable.

A variable should be declared only once. A repeated declaration of the same variable is an error:

let message = "This";
let message = "That"; // SyntaxError: 'message' has already been declared

In JavaScript, there are two limitations on variable names:

The name must contain only letters, digits, or the symbols $ and _. The first character must not be a digit. When the name contains multiple words, camelCase is commonly used, where words go one after another, each word except the first starting with a capital letter. Non-Latin letters are allowed, but not recommended.