Hassan Zia Hassan Zia - 9 months ago 27
Javascript Question

variable behavior in javascript, old values doesn't get overridden when using += operator

Well i'm afraid that my title doesn't explain it. I'm unable to understand the behavior of variables when they store some values.
i'll try to explain what i'm saying,

My Code

<! DOCTYPE html>
<html>
<head>
<title>Current Date and Time</title>
<style>
p { font: 14px normal arial, verdana, helvetica; }
</style>
<script>
function telltime() {
var out = "";
var now = new Date() ;
out += "<br />Date: " + now.getDate() ;
out += "<br />Month: " + now.getMonth() ;
out += "<br />Year: " + now.getFullYear() ;
out += "<br />Hours: " + now.getHours() ;
out += "<br />Minutes: " + now.getMinutes() ;
out += "<br />Seconds: " + now.getSeconds() ;
document.getElementById("div1").innerHTML = out;
}
</script>
</head>
<body>
The current date and time are: <br/>
<div id="div1"></div>
<script>
telltime() ;
</script>
<input type="button" onclick="location.reload() " value="Refresh" />
</body>




it outputs as below:

First Output

but if i change:

out += "<br />Date: " + now.getDate() ;
out += "<br />Month: " + now.getMonth() ;
out += "<br />Year: " + now.getFullYear() ;
out += "<br />Hours: " + now.getHours() ;
out += "<br />Minutes: " + now.getMinutes() ;
out += "<br />Seconds: " + now.getSeconds() ;


with this:

but if i change:

out = "<br />Date: " + now.getDate() ;
out = "<br />Month: " + now.getMonth() ;
out = "<br />Year: " + now.getFullYear() ;
out = "<br />Hours: " + now.getHours() ;
out = "<br />Minutes: " + now.getMinutes() ;
out = "<br />Seconds: " + now.getSeconds() ;


then output would be like this:

2nd Output

I'm quiet unable to understand this behavior. up to my understandings a value stored in a variable will always get overridden if we store a new value in that particular variable, no matters the way to store the value, but in case described above,
out
stores all the values which get written when script runs. But if we change
+=
with
=
then
out
only holds the last value which describe current seconds.

Answer Source

This is because

out += <br />Date: " + now.getDate()

means out = out + "<br />Date: " + now.getDate()

where as

out = "<br />Date: " + now.getDate()

assigns (and overwrites) output.

Update:

I think I now understand where you are getting stuck.

out = out + <br />Date: " + now.getDate() means out gets a new value which is equal to previous value of out + some new value, so is it not supposed to overwrite the previous value?

If you are asking why doesn't the second instance of out also get overwritten, then let me explain:

out = out + "<br />Date: " + now.getDate()

The out after the = is going to be replaced with out's value at the current time and then assigned to out.