Reputation: 276
This is basically a theoretical question on the way the decoding of a JSON script takes place. I am new to JSON and JavaScript, so was taking a tutorial. It gave me a few example codes to work on. I found this out because of a mistake I committed. The example code was this--
<html>
<body>
<h2>Create Object from JSON String</h3>
<p>First Name: <span id="fname"></span></p>
<p>Last Name: <span id="lname"></span></p>
<script type="text/javascript">
var employees = [
{ "firstName" : "John" , "lastName" : "Doe" },
{ "firstName" : "Anna" , "lastName" : "Smith" },
{ "firstName" : "Peter" , "lastName" : "Jones" }, ];
employees[1].firstName="Jonatan";
employees[2].lastName="Holla";
document.getElementById("fname").innerHTML=employees[1].firstName;
document.getElementById("lname").innerHTML=employees[2].lastName;
</script>
</body>
</html>
I would get the following output--
Create Object from JSON String
First Name: Jonatan
Last Name: Holla
But I accidentally committed a mistake by modifying line 14 of the code. Instead of "lname", I had typed "fname" again.
document.getElementById("fname").innerHTML=employees[2].lastName;
It gave the following output--
Create Object from JSON String
First Name: Holla
Last Name:
Why did this happen? Agreed that calling getElementId on fname second time resulted in output of "Holla" in "First Name" field. But how did that statement negate any effect by the preceding statement? (ie, line 13)?
Upvotes: 1
Views: 1737
Reputation: 32269
It doesn't negate it, it overwrites it.
You first say: write "Jonatan" in fname. Then you say write "Holla" in fname. So you see at the end only "Holla".
And lname is empty because you don't set it anymore - instead you set fname 2 times.
Upvotes: 2