4.changing a variable value


#1


I am not able to understand why i keep on getting the output for set up morning alarm as the second defined variable,whatsoever value i set for morning alarm in second var defined the output changes according to that ?
looking forward for relpy soon


#2

That's the point of variables, you can change them!


#3

But why does it give th same second variable value everytime i run it even
if i change different time ?


#4

Hi @giganinja23003,

It follows the last assigned value for the same variable.

Examples:

var morningAlarm = '6am';
var morningAlarm = '7am'; // <===
console.log(morningAlarm);

prints 7am

var morningAlarm = '6am';
var morningAlarm = '7am';
var morningAlarm = '6am'; //<===
console.log(morningAlarm);

prints 6am

var morningAlarm = '6am';
var morningAlarm = '7am';
var morningAlarm = '9am'; // <===
console.log(morningAlarm);

prints 9am

var morningAlarm = '6am';
var morningAlarm = '7am';
var morningAlarm = '6am';
var morningAlarm = 'I hope this example helps'; // <===
console.log(morningAlarm);

prints I hope this example helps

:slight_smile:


#5

Then that means we cannot use the previous declard variables.
So what is the requirement of declaring variables which are not in end if
we cannot even get them as output?


#6

"Then that means we cannot use the previous declard variables."

Yes.
But we can still use the first variable if we don't change the value of it before outputting it (I'll admit that sentence is kinda confusing, which is why I included a example):

var example = 5;
console.log(example); // The output is 5 and using the first value of example
example = 6;
console.log(6) // The output is 6 and using the second value of example

When is it useful to change a variable's number? When you learn about functions (if you haven't already), it's vital to be able to change a variable's value. Below is a quick example of when it might be somewhat practical to change a variable's value.

var add1 = 3
var add2 = 3;
add1 = add1 + add2;
console.log(add1);  // The output is 6.

I hope this clears some stuff up!


#7

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