Variables

Programs need to remember values: a user's name, a price, a score in a game. For that, they use variables. A variable is like a box with a label: it has a name, and it holds a value that you can use later.

You create a variable with the keyword let:

let city = "Prague";
console.log(city);

This prints:

Prague

Let's go through the first line:

  • let is a keyword, a word with a special meaning in JavaScript. It says that we are creating a new variable.
  • city is the name of the variable.
  • = stores the value on its right in the variable. In programming, it doesn't mean “equals” as in math; read it as “gets”: city gets the value "Prague".
  • "Prague" is the value.

To use the value, write the name of the variable without quotes. console.log(city) prints the value of the variable, Prague, while console.log("city") prints the text city.

A variable can also hold a number, and you can print it together with other values, separated by commas:

let temperature = 18;
console.log("It is", temperature, "degrees outside.");

This prints:

It is 18 degrees outside.

Rules for the names of variables:

  • A name can contain letters, digits and the characters _ and $, but it can't start with a digit: price2 is fine, 2price isn't.
  • A name can't contain spaces. If it has more words, write them together and start every word after the first one with a capital letter: firstName, priceOfChocolate. This style is called camelCase, because the capital letters stick up like the humps of a camel.
  • Uppercase and lowercase letters matter: age and Age are two different variables.
  • A name can't be a keyword, such as let.

Choose names that say what the variable holds: price tells you more than p or x.

Instructions

Create a variable firstName with the value "John".

On the next line, print the value of firstName.

Below, create a variable age with the value 25. It's a number, so no quotes.

Finally, print this sentence. Use the variables firstName and age, and separate the values with commas:

John is 25 years old.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

4/15

Next