JS Variables

JavaScript Variables: Storing and Managing Data

Most of the time, a JavaScript application needs to work with information. Here are two examples:

Variables are used to store this information.

What is a Variable?

A variable is a “named storage” for data. We can use variables to store goodies, visitors, and other data.

To create a variable in JavaScript, use the let keyword.

The statement below creates (in other words: declares) a variable with the name “message”. You can then assign data to it using the assignment operator =.

Declaring and Assigning a Variable

// 1. Declare a variable
let message;

// 2. Assign a value to it message = 'Hello, IntricateDevo!';

// 3. Access the value console.log(message); // Outputs: Hello, IntricateDevo!

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

Combined Declaration and Assignment

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

We can also declare multiple variables in one line:

Multiple Variables in One Line

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

console.log(user); // John console.log(age); // 25

That might seem shorter, but we don’t recommend it. For the sake of better readability, it's best to use a single line per variable.

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

Single Line Per Variable (Recommended)

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

console.log(message); // Hello

Some people also define multiple variables in this multiline style:

Multiline Style

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

…Or even in the “comma-first” style:

"Comma-First" Style

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

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

var instead of let

In older scripts, you may also find another keyword: var instead of let:

`var` Declaration

var message = 'Hello';
console.log(message); // Hello

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 are not important for now. We’ll cover them in detail in a later chapter.

A Real-Life Analogy

We can easily grasp the concept of a “variable” if we imagine it as a “box” for data, with a uniquely-named sticker on it.

For instance, the variable message can be imagined as a box labelled "message" with the value "Hello!" in it.

We can put any value in the box. We can also change it as many times as we want:

Changing a Variable's Value

let message;
message = 'Hello!';
console.log(message); // Hello!

message = 'World!'; // value changed console.log(message); // World!

When the value is changed, the old data is removed from the variable.

We can also declare two variables and copy data from one into the other.

Copying Data Between Variables

let hello = 'Hello world!';
let message;

// copy 'Hello world' from hello into message message = hello;

// now two variables hold the same data console.log(hello); // Hello world! console.log(message); // Hello world!

Declaring Twice Triggers an Error

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

Redeclaration Error

let message = "This";

// repeated 'let' leads to an error // let message = "That"; // SyntaxError: 'message' has already been declared

So, we should declare a variable once and then refer to it without the let keyword.

A Note on Functional Languages

It’s interesting to note that there exist so-called pure functional programming languages, such as Haskell, that forbid changing variable values.

In such languages, once the value is stored “in the box”, it’s there forever. If we need to store something else, the language forces us to create a new box (declare a new variable). We can’t reuse the old one.

Though it may seem a little odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits.

Variable Naming Rules

There are two main limitations on variable names in JavaScript:

  1. The name must contain only letters, digits, or the symbols $ and _.
  2. The first character must not be a digit.

Examples of valid names:

Valid Variable Names

let userName;
let test123;
let _private;
let $element;

When a name contains multiple words, camelCase is commonly used. That is: words go one after another, with each word except the first starting with a capital letter, like myVeryLongName.

Interestingly, the dollar sign $ and the underscore _ can also be used in names. They are regular symbols, just like letters, without any special meaning.

These names are valid:

Using `$` and `_` in Names

let $ = 1;
let _ = 2;

console.log($ + _); // 3

Examples of incorrect variable names:

Incorrect Variable Names

// let 1a; // cannot start with a digit
// let my-name; // hyphens '-' aren't allowed in the name

Case Matters

Variable names are case-sensitive. Variables named apple and APPLE are two different variables.

Non-Latin Letters

It is possible to use any language for variable names, including Cyrillic letters or Chinese logograms:

Non-Latin Variable Names

let имя = 'Akash';
let 我 = 'IntricateDevo';
console.log(имя); // Akash

Technically, there is no error here. Such names are allowed, but there is an international convention to use English in variable names. Even if we’re writing a small script, it may have a long life ahead. People from other countries may need to read it someday.

Reserved Names

There is a list of reserved words, which cannot be used as variable names because they are used by the language itself.

For example: let, class, return, and function are reserved.

The code below gives a syntax error:

Reserved Names Error

// let let = 5; // can't name a variable "let", error!
// let return = 5; // also can't name it "return", error!

An Assignment Without use strict

Note: The following behavior is for non-strict mode and is considered bad practice.

Normally, we need to define a variable before using it. But in older versions of JavaScript, it was possible to create a variable by just assigning a value to it, without using let. This still works if you don't use "use strict" in your scripts.

Assignment without Declaration (Bad Practice)

// note: no "use strict" in this example
num = 5; // the variable "num" is created if it didn't exist
console.log(num); // 5

This is bad practice and will cause an error in strict mode:

Strict Mode Error

"use strict";

// num = 5; // error: num is not defined

Constants: Unchanging Variables

To declare a constant (unchanging) variable, use const instead of let:

Declaring a Constant

const myBirthday = '18.04.1982';
console.log(myBirthday); // 18.04.1982

Variables declared using const are called “constants”. They cannot be reassigned. An attempt to do so will cause an error:

Reassigning `const` Error

const myBirthday = '18.04.1982';

// myBirthday = '01.01.2001'; // error, can't reassign the constant!

When a programmer is sure that a variable will never change, they can declare it with const to guarantee and communicate that fact to everyone.

Uppercase Constants

There is a widespread practice to use constants as aliases for difficult-to-remember values that are known before execution.

Such constants are named using capital letters and underscores.

For instance, let’s make constants for colors in so-called “web” (hexadecimal) format:

Uppercase Constants for Hard-Coded Values

const COLOR_RED = "#F00";
const COLOR_ORANGE = "#FF7F00";

let color = COLOR_ORANGE; console.log(color); // #FF7F00

Benefits of this approach:

When should we use capitals for a constant and when should we name it normally? Let’s make that clear.

Being a “constant” just means that a variable’s value never changes. But some constants are known before execution (like a hexadecimal value for red) and some constants are calculated in run-time but do not change after their initial assignment.

For instance:

Calculated Constant

// The value is calculated at run-time, but doesn't change after.
const pageLoadTime = window.performance.now();
console.log(`Page loaded in ${pageLoadTime}ms`);

The value of pageLoadTime is not known before the page load, so it’s named normally. But it’s still a constant because it doesn’t change after assignment.

In other words, capital-named constants are used as aliases for “hard-coded” values.

Name Things Right: A Key to Good Code

A variable name should have a clean, obvious meaning, describing the data that it stores. This is one of the most important and complex skills in programming.

In a real project, most of the time is spent modifying and extending an existing code base. When we return to code after a break, it’s much easier to understand code that is well-labelled, with good variable names.

Please spend time thinking about the right name for a variable before declaring it. Doing so will repay you handsomely.

Some good-to-follow rules are:

Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is not. Go for it.

Reuse or Create?

Some lazy programmers, instead of declaring new variables, tend to reuse existing ones. Their variables become like boxes where people throw different things without changing the sticker. What’s inside the box now? Who knows?

Such programmers save a little on variable declaration but lose ten times more on debugging.

An extra variable is good, not evil.

Modern JavaScript minifiers and browsers optimize code well enough, so using more variables won’t create performance issues. Using different variables for different values can even help the engine optimize your code.

Summary

Tasks to Practice

Task 1: Working with variables

Importance: 2

  1. Declare two variables: admin and name.
  2. Assign the value "John" to name.
  3. Copy the value from name to admin.
  4. Show the value of admin using alert() (must output “John”).

Solution

Task 2: Giving the right name

Importance: 3

  1. Create a variable with the name of our planet. How would you name such a variable?
  2. Create a variable to store the name of a current visitor to a website. How would you name that variable?

Solution

Task 3: Uppercase const?

Importance: 4

Examine the following code:

const birthday = '18.04.1982';
const age = someCode(birthday);

Here we have a constant birthday for the date, and also the age constant.

The age is calculated from birthday using someCode(), which is a function call. The details don’t matter here; the point is that age is calculated somehow based on birthday.

Would it be right to use upper case for birthday? For age? Or even for both?

const BIRTHDAY = '18.04.1982'; // make birthday uppercase?
const AGE = someCode(BIRTHDAY); // make age uppercase?

Solution