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 jQuery Basics (2014) Creating a Simple Lightbox Perform: Part 4

Carlos Enrique Castañeda Gutiérrez
Carlos Enrique Castañeda Gutiérrez
13,886 Points

Is it ok to have several "var" declarations through the code?

Hello:

Is it normal in Javascript (or JQuery) world to have "var" declarations on any place (logic of ocurse). In other languages you usually declar variables at the beginning of code or functions, but if you do that in Javascript you might be calling something which is not existing yet.

Isn't this a little "spaghetti" code or is considered fine?

Thanks

2 Answers

Daan Schouten
Daan Schouten
14,454 Points

It is true you can run into errors when you declare a variable that references to an html element that hasn't been created yet. But you could circumvent this issue by either placing the script at the end of your html page so that the page is already loaded before the script is called, for example.

Personally, I like to wrap most of my code into a function, which includes the var declarations, and then call another function within the first function that actually uses these declared variables.

If you prefer running your Javascript when the page has loaded without including javascript in your html file, check out this thread. There are a few simple methods that ensure Javascript runs when the html is ready.

http://stackoverflow.com/questions/807878/javascript-that-executes-after-page-load

It depends on the context. Can you show me your code?