1

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

2
  • 1
    The way I see it line 13 first sets First Name to "Jonathan" and your mistaken line 14 overwrites this with "Holla". Last Name is left empty because span#lname is never changed. To me this makes perfect sense. Commented Feb 17, 2012 at 17:58
  • 1
    I don't see any JSON in your code. Only JavaScript objects and arrays. Commented Feb 17, 2012 at 18:00

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Okay, so when the script is run, before the output appears on the screen, all the .innerHTML methods will have been evaluated. Am I right?
yes, this script is executed immediatly and what you see is the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.