
Variables: More examples (JavaScript debugging)

Upgrade for more content
True or false? "age1 is not defined" means that the variable "age1" is not created when used.
Lina has written a program, and this is her pseudocode: The program should note name and age for two users. Then calculate the age difference between them and output the result. Here the pseudocode is translated to JavaScript code. Let’s test the code. Oh.
We got an error message! The program has an error on row six. It says SyntaxError. It is a syntax error. Syntax errors occur when a program is not written according to the programming language rules.
Let’s look for row six, where it told us the error is. Let’s go carefully through the instruction. Is the instruction spelled correctly? c, o, n, s, o, l, e, dot l, o, g. Yes, that’s right.
Are both parentheses in place? Yes. And is there a semicolon at the end? Yes, everything seems okay. So let’s look at what we have written inside the parentheses. "n1" is a variable containing the first person's name.
On row one we have declared "n1" and asked the user to assign it a value. There doesn’t seem to be anything wrong. Then we have used a plus sign to add a word or a variable. We added the word "is" and used quotation marks around it. That seems to be okay too.
Then we used a plus sign for... No, we didn't do that. There should be a plus sign between the word "is" and the variable result, but there isn’t. We’ve found the error! Let’s add the plus sign that's missing and test our code again.
And now we can note name and age of two people. The problem on row six is solved. Good! But we’ve received a new error message! ReferenceError: age1 is not defined "age1" is not defined.
So it’s telling us that the “age1” variable does not exist when used for the instruction in row five. But we definitely declared the variable ”age1” up here in the code! Oh, there is a slight difference. Do you see? When we declared the variable, we wrote a capital ‘A’, but here we tried to use a variable with a small ‘a’.
And in JavaScript it matters if we use upper or lower case letters when we give names to variables. Here is the error! We tried to use a variable that doesn’t exist. Let’s change it to a lowercase "a" and test the code again. Input names and ages, as we did before.
Lina 16 Maria 15 Lina is one years older than Maria. Good, now it works without any error messages at all! Searching and solving errors is an important part of the work in programming. There are many, many different error messages. You can learn what they look like by deliberately entering errors in your code.