Programs remember things: a score, a name, a list of stories. In this lesson you'll give values a name so your code can use them again and again.
flag
What you'll learn
How to write comments that JavaScript skips.
How to keep values in variables with let, const and var.
The four kinds of data you will use most: strings, numbers, booleans and arrays.
waving_handWelcome to variables
A variable is a name that holds a value. Making a variable is called declaring it.
Once a value has a name, you can use the name anywhere in your code, and you can sometimes change what it holds.
You also met const in JS Lesson 1, when you named a new list item story. This lesson explains how that works.
storefront
Think of the jars in a sari-sari store. Each jar has a label (the variable's name) and holds something (its value).
Some jars have a lid you can open, so you can swap what's inside (let).
Some are sealed, so what's inside stays the same (const).
And a few are an older kind of jar that still works (var).
inventory_2An open jar: candiesHolds 20. You can refill it to 35.let candies = 20;candies = 35;
lockA sealed jar: storeNameHolds the store's name, which stays the same.const storeName = "Aling Nena's Store";
historyAn older jar: ownerWorks the same way, just an older kind.var owner = "Aling Nena";
Now let's see the code ↓
inventory_2An open jar: candiesHolds 20. You can refill it to 35.let candies = 20;candies = 35;
lockA sealed jar: storeNameHolds the store's name, which stays the same.const storeName = "Aling Nena's Store";
historyAn older jar: ownerWorks the same way, just an older kind.var owner = "Aling Nena";
The label is the variable's name, and what's inside is its value. The = sign puts the value in the jar.
searchA closer look
Comments
A comment is a note for people. JavaScript skips it.
// starts a comment that lasts until the end of the line. /* and */ wrap a comment that can cover many lines.
Comments are handy for explaining what a part of your code does, or for turning a line off while you test something.
How a declaration is written
letkeyword (make a variable)
readersname (the label)
=put in
120value (what's inside)
;end
In JavaScript, = doesn't mean "is equal to". It means "put this value in". The value on the right goes into the name on the left.
Naming variables
A name can use letters, numbers, _ and $, but it can't start with a number or have spaces.
When a name has more than one word, the usual style is camelCase: the first word in small letters, and every next word starting with a capital, like siteName or isOpen.
Capital letters matter, so readers and Readers are two different variables.
let, const or var?
Use let when the value will change, like a score. Use const when it won't, like the name of the site.
A good habit is to start with const, and switch to let only when you need to change the value.
var is the older way. It still works, and you'll see it in older code online, but it follows extra rules that can surprise you, so new code mostly uses let and const.
Four kinds of data
Every value has a type. These are the four you'll use most:
sellA price tagWords and letters.String"Sale!"
tagA counterA number you can do math with.Number20
toggle_onAn Open signOnly two choices: yes or no.Booleantrue
view_weekA row of jarsMany values in order, numbered from 0.Array["Candy", "Chips", "Soda"]
Now let's see the types ↓
sellA price tagWords and letters.String"Sale!"
tagA counterA number you can do math with.Number20
toggle_onAn Open signOnly two choices: yes or no.Booleantrue
view_weekA row of jarsMany values in order, numbered from 0.Array["Candy", "Chips", "Soda"]
typeof tells you the type of a value. For example, typeof 20 gives "number". For an array, it gives "object", because arrays are a kind of object. You'll learn about objects in JS Lesson 6.
Counting from 0
Each item in an array has a number called its index. The first item is at index 0, the second at 1, and so on.
So in ["Phones", "Games", "Apps"], topics[0] is "Phones" and topics[2] is "Apps".
constructionLet's build it
Let's keep today's facts about Front Page Bytes in variables. The HTML and CSS stay the same in every step: a heading and an empty paragraph with id="output".
Most steps write to the console under the mini browser. The last step shows a sentence on the page.
1Step 1: Start with comments
Your code
// Front Page Bytes: today's numbers/* The lines below keep facts about today's paper. */
Line 1 is a one-line comment. Lines 2 and 3 are one comment that covers two lines.
The console is empty, and that's the point: JavaScript skipped all three lines.
2Step 2: Make a variable with let
Your code
// Front Page Bytes: today's numbers/* The lines below keep facts about today's paper. */let readers = 120;console.log(readers);
let readers = 120; makes a variable named readers and puts 120 in it.
console.log(readers); has no quotes around readers, so it shows the value inside the variable, 120, not the word "readers".
3Step 3: Change the value
Your code
// Front Page Bytes: today's numbers/* The lines below keep facts about today's paper. */let readers = 120;console.log(readers);readers = 150;console.log(readers);
readers = 150; puts a new value in the same variable. There's no let this time, because the variable already exists.
The console now shows 120, then 150.
4Step 4: Values that stay: const and var
Your code
// Front Page Bytes: today's numbers/* The lines below keep facts about today's paper. */let readers = 120;console.log(readers);readers = 150;console.log(readers);const siteName = "Front Page Bytes";var editor = "Ms. Cruz";console.log(siteName, editor);
let isOpen = true; makes a boolean. typeof tells you each value's type:
the site name is a string, the readers count is a number and isOpen is a boolean.
This line uses what you learned in JS Lesson 1. The + joins strings and variables into one sentence, and innerHTML puts it in the paragraph:
Front Page Bytes has 150 readers today. Notice the spaces inside the quotes, so the words don't run together.
sticky_note_2Quick notes
// and /* */Comments
// This line is skipped.
How to use
// textA comment until the end of the line.
/* text */A comment that can cover many lines.
JavaScript skips comments. They are notes for people reading the code.
Examples
Explain what a line does.
// Count the visitorslet visitors = 0;
Turn off a line for now, without deleting it.
// console.log("testing");
A short note at the top of your code.
/* Weather page Made by Ana */
letA value that can change
let readers = 120;
How to use
let name = value;Makes a new variable and puts a value in it.
name = newValue;Puts a new value in it later. No let this time.
let name;Makes it empty for now. Its value is undefined.
Examples
A score that goes up.
let score = 0;score = 10;
A message that changes.
let status = "Loading";status = "Done";
constA value that stays
const siteName = "Front Page Bytes";
How to use
const name = value;Makes a variable whose value stays the same.
A const needs its value right away, on the same line.
Giving it a new value later stops the code with an error.
Examples
A name that stays the same.
const schoolName = "Rizal High";
A fixed price.
const price = 25;
varThe older way
var editor = "Ms. Cruz";
How to use
var name = value;The older way to make a variable. It still works.
New code usually uses let or const, which follow simpler rules.
Examples
Older code you may see online.
var count = 5;
StringText
const siteName = "Front Page Bytes";
How to use
"Hello"A string: text inside double quotes.
'Hello'Single quotes work too. Use the same kind at both ends.
"Hi " + nameThe + joins strings together.
Examples
A greeting.
const greeting = "Good morning!";
Joining text and a variable.
const name = "Ana";console.log("Hi " + name);
NumberNumbers
let readers = 150;
How to use
42A whole number.
3.5A number with a decimal point.
-10A number below zero.
Numbers have no quotes. "42" in quotes is a string.
Examples
The number of students.
let students = 40;
A temperature.
let temperature = 31.5;
BooleanTrue or false
let isOpen = true;
How to use
trueYes, on, correct.
falseNo, off, wrong.
No quotes. true and false are words JavaScript already knows.
Examples
Is the store open?
let isOpen = true;
Did the player win?
let hasWon = false;
ArrayA list of values
const topics = ["Phones", "Games", "Apps"];
How to use
[a, b, c]A list of values, with commas between them.
list[0]The first item. Counting starts at 0.
list[2]The third item.
list.lengthHow many items the list has.
Examples
Days of the school week.
const days = ["Mon", "Tue", "Wed", "Thu", "Fri"];
Get the first and last day.
console.log(days[0]);console.log(days[4]);
Test scores.
const scores = [85, 90, 78];
reportCommon mistakes
These are mistakes many beginners make. Each mini browser shows what really happens, and the console shows the message the browser gives.
Without quotes, JavaScript reads Front, Page and Bytes as three names of variables in a row, which doesn't make sense to it.
The whole script stops before it starts, with a SyntaxError, so not even line 2 runs.
tips_and_updatesTip: Put text inside quotes: "Front Page Bytes". Names of variables go without quotes.
There's no error here, but the answers are wrong. topics[1] is the second item, Games.
The list has three items, at index 0, 1 and 2, so topics[3] doesn't exist and gives undefined.
tips_and_updatesTip: The first item is at index 0. The last item is at index length - 1.
quizTest your knowledge
Write JavaScript in the JS tab. Make a few variables about yourself, then show them on the page. The console and the mini browser update as you type, and each goal gets a check mark when it's done.
auto_awesomeNo clicking needed. Each goal gets a check mark by itself once your code does it.
Write a comment with // or /* */.not done yet
Make a variable with let and give it a number.not done yet
Make a const that holds text in quotes.not done yet
Make an array with at least three items.not done yet
Show one of your variables on the page in #card, using innerHTML.not done yet