0

Im reading the tutorials here.

I am getting confused trying to understand some of this example, why is the variable declared as nothing and what does the ,i indicate

var x="",i;

and also why do you use

 x=x

at the beginning of the line?

<!DOCTYPE html>
<html>
<body>

<p>Click the button to loop from 1 to 6, to make HTML headings.</p>
<button onclick="myFunction()">Try it</button>
<div id="demo"></div>

<script>
function myFunction()
{
var x="",i;
for (i=1; i<=6; i++)
{
 x=x + "<h" + i + ">Heading " + i + "</h" + i + ">";
}
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>
4
  • x = x + i; means take the current value of x, append i to it, then assign that back to x. It's building the string up during the loop. Commented Dec 19, 2013 at 2:39
  • Oh that's a bumber they seem to have a large collection of knowledge that I was excited to go through. Do you have any recommendations on simulare sites with more creditable information that I can learn from? Commented Dec 19, 2013 at 2:40
  • Oh thank you Evan that clears that up. Commented Dec 19, 2013 at 2:41
  • I always recommend the book Object-Oriented JavaScript by Stoyan Stefanov, it does a great job of teaching modern JavaScript. Eloquent Javascript is a pretty good, free book. MDN is also a great resource. Commented Dec 19, 2013 at 4:32

2 Answers 2

1

var x="",i;

This translates as

var x = "";
var i;

which simply declares those variables within the current scope.

x=x + ...

This means replace the value of x with the value of the expression to the right of the = sign. In this case, you are concatenating a string to the end of the current value of x.

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

Comments

0
var x="",i;

is the same as

var x = "";
var i;

Declare variables in the form of

var a=1,
    b=2,
    c=3;

is common and make the code style looking clear and easy to read.

4 Comments

So whats the differance between var x; and var x="";
var x = "" make x an empty string, then x is now really containing somthing, while var x will just declare the existence of x and the x now is undefined and it is ready to be set value for x later
It's always a good habit in JS to use var to declare an variable first no matter by var x or var x = 'blabla', otherwise, x will become global and that is not a good pattern in JS
If you want to start learning javascript, the book javascript definitive guide is something you can start with. This is the best javascript book to start.

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.