JavaScriptLesson 2 of 10Jump to practice

Variables

Store values with let and const, and learn the basic types of value JavaScript works with.

A variable is a name that holds a value, so you can use it later.

let score = 10;
const playerName = "Marcus";

let or const?

Keyword Can the value change later? Use it for
const No Most things. Start with this
let Yes Counters, totals, anything that updates

Run this, then try changing city on the last line to see the error const gives you.

let and const
Open in editor
<script>
let count = 1;
count = count + 1;
console.log("count is", count);

const city = "Chicago";
console.log("city is", city);

// Remove the two slashes on the next line, then Run:
// city = "Houston";
</script>
Result

Types of values

Type Examples
Number 42, 3.14, -7
String (text) "hello", 'Texas'
Boolean true, false
Array (a list) ["red", "green", "blue"]
Object (named values) { name: "Emma", age: 21 }
Working with values
Open in editor
<script>
const price = 12;
const quantity = 3;
console.log("Total:", price * quantity);

const firstName = "Emma";
console.log("Hello, " + firstName + "!");

const colors = ["red", "green", "blue"];
console.log("First color:", colors[0]);
console.log("How many:", colors.length);

const student = { name: "Emma", age: 21 };
console.log(student.name, "is", student.age);
</script>
Result

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Create a variable name that will never change.

     name = "Sofia";

  2. Exercise 2

    Create a variable score that will change later.

     score = 0;
    score = score + 10;

  3. Exercise 3

    Print the first item of the array.

    const fruits = ["apple", "pineapple", "banana"];
    console.log(fruits[]);

Quiz: 4 questions

1. Which keyword should you use by default?
2. What type is "42" (with quotes)?
3. What does ["a", "b", "c"].length give?
4. Which is a valid variable name?

Finish the practice to complete this lesson.