Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Perform: Traversing Elements with querySelector

Tomasz Sporys
Tomasz Sporys
11,258 Points

Are loops called automatically in javascript when DOM is being loaded?

Hi, guys. I'm coming with C# programming background and started learning JavaScript. There is a lot things that work different. The most recent question is : Like in the title- If I create a loop that that iterates through the UL that has been sacked form DOM by one of my variables or rather arrays:), Does it run automatically without any calling a function? I mean: Don't I have to put the loop inside the function then call it to iterate it? Hop you know what I mean:)

2 Answers

Hi Tomasz,

Yes, you can have a loop or any other code outside of any function and it will run when that particular script is loaded.

For example, this can be your entire script:

for (var i = 1; i <=100; i++) {
    console.log(i);
}

And it will log the numbers 1 to 100 to the console once that script is loaded.

Alan Kolić
Alan Kolić
8,384 Points

If you make a JavaScript file with some function like this

function myFunction (){
  // loops and actions
}

and link it to index.html, nothing will happen until you call it. You can do that from other JavaScript files or Chrome developer tools.

However, if you call the function inside the same JavaScript file it will be called as soon as it's loaded.

function myFunction (){
  // loops and actions
}

myFunction();
Tomasz Sporys
Tomasz Sporys
11,258 Points

Misunderstanding:) Not asking about function but loops. If I make a loop outside a function, will it perform? OK, doesn't matter. I will experiment heheh. Thanks, anyway:)