Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Declaring and assigning variables
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.
- script.js
Thanks! We’ll fix everything at once!
The code has changed, click “Run” or turn autorun on.
Result
- On the second line, declare variable
milkInGrams
. - On the next line, assign the value of the
muffin.ask
command to this variable with the question “Boss, how many grams of milk have you had?”. - On the next line, log the text hint “Brekkie-meter has received milk data: ” in the console.
- On the last line, output the variable to the console.
Comments