Sample Video Frame

Created by Zed A. Shaw Updated 2024-11-15 13:50:32

04: Variables

A variable is a way to give some piece of data in your program a name. This bit gets more complex as you code, but in general you use variables to give data names. The computer really does not care what name you use, but other people care very much. There are many ways to create variables in JavaScript, but we will start with the most recent and easiest to use way. Other ways seem to cause lots of problems and bugs or are difficult to explain now.

With this exercise, keep in mind that you are not really expected to understand what a variable is if you're a beginner. You will, however, get plenty of practice with this concept later.

The Code

View Source file code.js Only

// let is the best way to make a variable
let name = 'Zed A. Shaw';
let age = 43;
let height = 74;

// PUZZLE: What happens if you use Math.round?
let feet = Math.floor(height / 12);
let inches = height - (feet * 12);

// you can use a variable as a parameter
console.log("Name:", name);
console.log("Age:", age);

// you can also embed variables in strings with ``
console.log(`Height ${feet} feet ${inches} inches.`);

console.log("Age * Height:", age * height);
// you can also put math in the ${} boundaries
console.log(`Age * Feet: ${age * feet}`);

In this code the only new thing is the lines at the top, where I use the word let to tell JavaScript I want to create a variable. You can read this as an English sentence, "Hey JavaScript, can you let the word age mean the number 43." This isn't an exact technical explanation of what's going on, but at this stage you don't have enough knowledge to actually understand the technical explanation. So you'll just have to trust me that wherever you use the word age in this JavaScript the number 43 will be put there instead.

Format Strings

This code also introduces a concept called "format strings". Every language has something like this because you typically have to put a variable inside a string when you want to print something to a person. In JavaScript you can use code like this:

`Height ${feet} feet ${inches} inches.`

Notice that I am using a weird "backquote" or "backtick" ` for this particular string. Then I put the variable I want to display inside ${} boundaries.

What You Should See

When you run this you should see the output just like mine.

Name: Zed A. Shaw
Age: 43
Height 6 feet 2 inches.
Age * Height: 3182
Age * Feet: 258
Previous Lesson Next Lesson

Register for Learn JavaScript the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.