JS · Lesson 2

Declaration

Comments, variables and kinds of data

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.

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.

Welcome 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.

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).

The label is the variable's name, and what's inside is its value. The = sign puts the value in the jar.

A 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

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:

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".

Let'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.

Step 1: Start with comments

Your code
// Front Page Bytes: today's numbers/* The lines below keep facts   about today's paper. */
What you see

Console

    Nothing here yet. console.log() writes here.

    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.

    Step 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);
    What you see

    Console

      Nothing here yet. console.log() writes here.

      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".

      Step 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);
      What you see

      Console

        Nothing here yet. console.log() writes here.

        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.

        Step 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);
        What you see

        Console

          Nothing here yet. console.log() writes here.

          The site's name won't change, so it gets const. The editor's name uses the older var, which works like let here.

          console.log can show more than one value. Put commas between them, and the console puts a space between each one.

          Step 5: Check the kind of data

          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;console.log(typeof siteName, typeof readers, typeof isOpen);
          What you see

          Console

            Nothing here yet. console.log() writes here.

            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.

            Step 6: Keep a list in an array

            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;console.log(typeof siteName, typeof readers, typeof isOpen);const topics = ["Phones", "Games", "Apps"];console.log(topics);console.log(topics[0]);
            What you see

            Console

              Nothing here yet. console.log() writes here.

              Square brackets make an array: a list of values with commas between them. The console shows the whole list, then topics[0], the first item: Phones.

              Step 7: Show the values on the page

              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;console.log(typeof siteName, typeof readers, typeof isOpen);const topics = ["Phones", "Games", "Apps"];console.log(topics);console.log(topics[0]);document.getElementById("output").innerHTML = siteName + " has " + readers + " readers today.";
              What you see

              Console

                Nothing here yet. console.log() writes here.

                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.

                Quick notes

                // and /* */ Comments
                // This line is skipped.

                How to use

                • // text A 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

                1. Explain what a line does.

                  // Count the visitorslet visitors = 0;
                2. Turn off a line for now, without deleting it.

                  // console.log("testing");
                3. A short note at the top of your code.

                  /* Weather page   Made by Ana */
                let A 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

                1. A score that goes up.

                  let score = 0;score = 10;
                2. A message that changes.

                  let status = "Loading";status = "Done";
                const A 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

                1. A name that stays the same.

                  const schoolName = "Rizal High";
                2. A fixed price.

                  const price = 25;
                var The 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

                1. Older code you may see online.

                  var count = 5;
                String Text
                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 " + name The + joins strings together.

                Examples

                1. A greeting.

                  const greeting = "Good morning!";
                2. Joining text and a variable.

                  const name = "Ana";console.log("Hi " + name);
                Number Numbers
                let readers = 150;

                How to use

                • 42 A whole number.
                • 3.5 A number with a decimal point.
                • -10 A number below zero.
                • Numbers have no quotes. "42" in quotes is a string.

                Examples

                1. The number of students.

                  let students = 40;
                2. A temperature.

                  let temperature = 31.5;
                Boolean True or false
                let isOpen = true;

                How to use

                • true Yes, on, correct.
                • false No, off, wrong.
                • No quotes. true and false are words JavaScript already knows.

                Examples

                1. Is the store open?

                  let isOpen = true;
                2. Did the player win?

                  let hasWon = false;
                Array A 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.length How many items the list has.

                Examples

                1. Days of the school week.

                  const days = ["Mon", "Tue", "Wed", "Thu", "Fri"];
                2. Get the first and last day.

                  console.log(days[0]);console.log(days[4]);
                3. Test scores.

                  const scores = [85, 90, 78];

                Common mistakes

                These are mistakes many beginners make. Each mini browser shows what really happens, and the console shows the message the browser gives.

                Changing a const

                The mistake
                const readers = 120;console.log(readers);readers = 150;console.log(readers);
                What you see

                Console

                  Nothing here yet. console.log() writes here.

                  readers was made with const, so it can't get a new value. Line 3 stops the code with Assignment to constant variable, and line 4 never runs.

                  Tip: Use let for values that will change. Keep const for values that stay the same.

                  Forgetting the quotes around text

                  The mistake
                  const siteName = Front Page Bytes;console.log(siteName);
                  What you see

                  Console

                    Nothing here yet. console.log() writes here.

                    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.

                    Tip: Put text inside quotes: "Front Page Bytes". Names of variables go without quotes.

                    Counting from 1 instead of 0

                    The mistake
                    const topics = ["Phones", "Games", "Apps"];console.log("First topic:", topics[1]);console.log("Third topic:", topics[3]);
                    What you see

                    Console

                      Nothing here yet. console.log() writes here.

                      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.

                      Tip: The first item is at index 0. The last item is at index length - 1.

                      Test 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.

                      No clicking needed. Each goal gets a check mark by itself once your code does it.

                      1. Write a comment with // or /* */. not done yet
                      2. Make a variable with let and give it a number. not done yet
                      3. Make a const that holds text in quotes. not done yet
                      4. Make an array with at least three items. not done yet
                      5. Show one of your variables on the page in #card, using innerHTML. not done yet
                      Your code
                      What you see

                      Console

                        Nothing here yet. console.log() writes here.

                        Try an exercise

                        Recap

                        • // and /* */ make comments, which are notes that JavaScript skips.
                        • let makes a variable you can change, const makes one that stays the same, and var is the older way. = puts a value in.
                        • Strings are text in quotes, numbers have no quotes, booleans are true or false, and arrays are lists in [ ] that count from 0.

                        References

                        Lesson content prepared by the WebCore F.E. team for beginner learners. The following references were used in preparing this lesson.

                        • ECMA International. ECMAScript Language Specification (official specification). Open reference