1
//Set the number of spaces in front of text
numSpaces = 20;
//
spaces = "&nbsp";
//
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!

8
  • It's not really clear what you want to do. Can you post some pseudo code for what you are trying to accomplish? Also, what should document.write(nameofloop + importantMessage) print out? Commented Feb 23, 2012 at 1:41
  • 1
    Are you teaching yourself with any material, like a tutorial? Commented Feb 23, 2012 at 1:45
  • @SimpleCoder nameofloop is what I am trying to define a loop. Currently, if I use the code as the poster below, I still get an undefined before the first word. "document.write(writeSpaces(10) + importantMessage)" is what I am using. Commented Feb 23, 2012 at 2:02
  • @ Dave Newton - Nope, just learning as I go. Commented Feb 23, 2012 at 2:02
  • 1
    Consider a tutorial, book, etc. Commented Feb 23, 2012 at 2:08

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I still get an undefined before my first word in "importantMessage."
document.write(writeSpaces(10) + importantMessage)
@user1227249 writeSpaces(10); document.write(importantMessage);

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.