JS variables


Hi everyone, can someone tell me why do we add the second line of code to 10AM for example rather than changing the variable's value itself (i.e. the first line of code)?

var morningAlarm = '6:30AM';
morningAlarm = '10:00AM';
console.log('Morning alarm is set to: ', morningAlarm);


that's actually a pretty good question. I think it has something to do with ease. like if you have a large program, you might not want to go searching for where the original variable is. it ends up being usefull later on. you could just go back and change the original value but for the interactive lesson you just have to do what the instructions say. also I believe that if you use the variable at one point in the code and change it later and use it again then you will have two different values. here is an example.
var random = 23
// this will show 23 in the end
random = 25
//this should show as 25

so you would log 23 and then 25 to the console.
I think, I'm not sure though.


That does make sense - it could be difficult to find where the original variable is.

Thanks for your help!


ya no problem. it seems like its just extra work but when you get further into the course you will see that there is a lot of stuff that works like that. enjoy the class though because it is really fun.


Great, thanks for your help !


The var keyword declares the variable. This is valid JS:

var morningAlarm;

The variable is now recognized by the interpreter, so will not raise a TypeError if it is referred:

console.log(morningAlarm);    // undefined

We only ever declare a variable once in a program but can modify its value as often and however we wish during the session. Setting (assigning) a value to a variable is how we define it.

A variable cannot have multiple values. It will only ever have the last value assigned to it. Any values previous are forgotten.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.