Reputation: 474
//Set the number of spaces in front of text
numSpaces = 20;
//
spaces = " ";
//
importantMessage = "This is a variable message that I will define";
for (var i = 0; i < numSpaces; i++)
{
//here is the output on screen
document.write(spaces)
}
//printing the full message
document.write(importantMessage);
I'm currently teaching myself javascript. I'm so confused if this is breaking a law in JS land, but how do I define a loop with a name? I would like to give the whole section from for (var...to write(spaces)} a name, so then I can do document.write(nameofloop + importantMessage) which of course will print out what I need. When I do define a name, somehow the loop says "undefined" before the "important message."
Unless there is a better way to loop some html code that is user defined. I want to be able to make a number of spaces before the message on my crawler message and it could vary depending on the user.
I'm confused on multiple { { } } as I will eventually make an if statement once I get this working. Thanks!
Upvotes: 1
Views: 70
Reputation: 26228
If you're wanting to "name" chunks of code for use, you're probably under-using functions. The best approach is to wrap the loop into a function:
function writeSpaces(numSpaces) {
for (var i = 0; i < numSpaces; i++) {
document.write(spaces);
}
}
Then call it like
writeSpaces(10);
Upvotes: 2