0

@ http://jsfiddle.net/defencedog/rrKYW/

A recent observation has deeply embezzled my knowledge of js. Look at the code below:

var x = "";

function postbody() {
    for (i = 0; i < 5; i++) {
        x = x + "<sup>" + i + "</sup><br/>";
        document.getElementById("posti").innerHTML = x;
    }

}​

The above code's output is similar to that of the following & that is the thing vague to me

var x = "";

function postbody() {
    for (i = 0; i < 5; i++) {
        x = x + "<sup>" + i + "</sup><br/>";

    }
  document.getElementById("posti").innerHTML = x;
}​

the latter code must giv me a single (to be concise last value of x) output & not the whole iterated output?

2
  • if it were getElementByID('post'+i) then that would have different outcomes Commented Sep 4, 2012 at 19:06
  • 1
    i don't think "embezzled" means what you think it means. Commented Sep 4, 2012 at 19:07

4 Answers 4

1

Both snippets accomplish the same thing; The first snippet is just less performant as it overwrites the value 5 times as the string is built up instead of writing the final string once.

unrelated: i is an implicit global. use var.

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

Comments

0

both will cause a same result.

x = x + ...

Comments

0

Sure it does. You add new code to x in each iteration and then set it in the element. setting innerHTML overwrites the entire content of the element.

In the first loop, each iteration will overwrite the html of the element with a little larger html, but the final iteration is the one that overwrites it with the 'complete' value of x.

So the end results are the same, but the first one is quite a bit slower.

Comments

0

The two examples are identical because on the first the innerHTML is being overwritten on each iteration while the value of the variable x is being concatenated with the other strings. By the last iteration, the element's innerHTML will have x's total value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.