Interactive online courses HTML Academy
2026-03-09 14:07 Diff

When you create a variable like that:

var someName;

The program simply remembers the name of the new variable, someName, but doesn’t write any data to it. If you output this variable to the console, you will see the following result:

LOG: undefined (undefined)

Remember, you can create or declare a variable, but not save any data to it. Sometimes it’s done to reserve a variable name for the future.

Of course, you will mostly be creating non-empty variables. To do that, you need to assign a value to it in addition to just declaring it.

Use the equals sign for value assignment:

var milkInGrams; // Declare variable console.log(milkInGrams); // Logs undefined milkInGrams = 20; // Assign one value console.log(milkInGrams); // Logs 20 milkInGrams = 'forty grams'; // Assign an entirely different value console.log(milkInGrams); // Logs the “forty grams” string

Note these two peculiarities.

First, the var command is used only once to create each variable. You will then address the variable by its name, without the var prefix.

Secondly, if you re-assign the value of the variable, as in the example above, when you wrote milkInGrams = 'forty grams';, you change the value of the variable. That is, it no longer contains number 20, now it contains string 'forty grams'. This is called overriding the value of a variable.

You can assign a value to a variable in parallel with its declaration. The value can be returned from a different command. Here are some examples:

var milkCalories = 42; var dryFeedCalories = muffin.ask('How many calories are there in dry food?'); var dailyMealInGrams = 50 + 80 + 120;

Let us now collect unknown data, save it to a variable and output it to the console.