JavaScript Basics #6: Variables

JavaScript Basics #6: Variables
Jan Zavrel
Jan Zavrel Follow June 22, 2021

Imagine a container where you store a value. In programming, this kind of container is called a variable.

Computer stores data in memory cells. Each cell has its own address so the computer can access it to either store or retrieve values from it. However, the address of the memory cell is quite hard to remember for humans because it looks like this: 0x6dfed4

That’s why variables provide a way of labeling data with a descriptive name, so humans can understand it more clearly.

In short, variables (1) label and (2) store data in memory. Here are things you can do with variables:

  1. Create a variable with a descriptive name (label).
  2. Store data in a variable.
  3. Update data in a variable (unless it’s forbidden).
  4. Retrieve or reference data stored in a variable.

Remember that variables are not values. They contain values and represent them with a label.

Creating a variable

Let’s learn how to use the var, let, and const keywords to create variables.

Since ES6 (a standardized version of JavaScript introduced in 2015 as ECMAScript), we have three ways to declare a variable.

The original var keyword is kept in the language for the backward compatibility with old programs but should not be used anymore.

The let keyword is for creating a variable which content can vary. This is the true variable.

The const keyword is for creating a variable which is actually a constant. This means that its content can’t be changed once the initial value is assigned to it.

If you’re familiar with Swift, don’t get confused now, because in Swift, the let keyword is used for declaring constants and the var keyword is used for declaring variables.

Let’s take a look at this example to understand what’s going on:

let myName = 'Jan';  
// This will print Jan to the console
  1. We declared a variable (let)
  2. We gave labeled it (myName)
  3. We used the assignment operator (=) to assign it a value ('Jan')
  4. We printed the value of the variable to the console

Naming conventions

There are a few general rules for naming variables:

  1. A name cannot start with a number.
  2. Names are case sensitive, that means myName is different from myname, but it’s not a good practice to create two variables that have the same name with different cases.
  3. Names cannot be the same as keywords like var or let. For a full list of JavaScript keywords, refer to this documentation.

Follow me on Medium, Twitter, Facebook and YouTube.

Jan Zavrel
Written by

Jan Zavrel Follow

Developer, Author, Teacher, Evernote Certified Consultant.