Home 05: let, var and const
Content
Cancel

05: let, var and const

There are several ways to define a variable in JavaScript. That means to assign a value to a named variable.

Define a variable with let

To define a variable in JavaScript, you use the keyword let. Next you give your variable a name, for example we want to use x as the name. Next, you use the so-called assignment operator to assign a value to the variable. The assignment operator in JavaScript is the single equal sign =, and we would like to assign the number 100 to our variable. That might sound confusing and complicated, but if you put it together, it is much easier.

1
let x = 100;

Definition of a variable Definition of a variable

Here is another example with a different name and a different value:

1
let numberOfMonsters = 42;

You see that the keyword and the assignment operator stay the same.

Define a variable with const

Besides the let keyword, you can also use const to define a variable in JavaScript. The difference is that a variable that you define using the keyword const is a so-called constant, and it cannot be changed during the runtime of your program.

You should use const if you are not planing to change the value during the runtime of your program, but you want to use the value in multiple places. We will talk in the following chapters more in detail about when to use const and when to use let.

Naming

There are some formal rules when it comes to naming variables in Javascript.

  • Variable names cannot contain spaces.
  • They must begin with a letter, an underscore (_) or a dollar sign ($).
  • They can only contain letters, numbers, underscores, and dollar signs.
  • They are case-sensitive, so upper- or lowercase matters.
  • You are not allowed to reuse keywords that JavaScript is using, like let, const and so on.

There are some more general rules that will make it easier for you to choose a good variable name.

  • First, don’t use names that are too short, select something descriptive that you and others can understand.
  • Your variable names should all be in English.
  • Start your names in lowercase.
  • You should consider using more than one word to name your variable.
  • Use the lowerCamelCase style to combine multiple words, that means start lowercase and add other words with the first letter uppercase. For example, awesomHamster or newMediaDesign.
  • Don’t override names that are already in use in your code, for example names that are used by p5.js like scale, rotate, rect, ellipse, and so on…

Here you can find some more guidelines for naming in JavaScript by Google.

var

In some older examples, you will often see the keyword var being used to define a variable. It works pretty similar to the let keyword, but has some drawbacks that we discuss in later chapters. In most cases, you can easily replace var with let and use the example.

This post is licensed under CC BY 4.0 by the author.
Contents