JS variables


#1

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


#2

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
console.log(random);
// this will show 23 in the end
random = 25
console.log(random);
//this should show as 25

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


#3

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

Thanks for your help!


#4

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.


#5

Great, thanks for your help !


#6

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.


#7

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