Jump to content

A Question


nutterz
 Share

Recommended Posts

I have been reading up in the tutorials a lot and slowly starting to understand javascript so I have a question. When writing a block of script does everything happen in the sequence it is written? For example below I quoted something from the try it editor thing on this site, and I was wondering why the 2 bold lines that are the same variable that appear to be able to change what they do instead of clash with the other varial like it would with html?

<html><body><script type="text/javascript">var firstname;firstname="Hege";document.write(firstname);document.write("<br />");firstname="Tove";document.write(firstname);</script><p>The script above declares a variable,assigns a value to it, displays the value, change the value,and displays the value again.</p></body></html>
EDIT: I was also wondering if it is possible to combined diferent statesment types in the one block od script? Edited by NuTTeRz
Link to comment
Share on other sites

Code runs from the top down, as you suspect. And it is possible to combine blocks of code between one set of script tags. Anything you don't put in a function will run when the page starts. The thing to bear in mind about the loading of the page from the top down is that if you try to reference an element in the body of a page with a script in the head, which is where they usually are, it may not exist yet and you'll get errors. I'm only new to JavaScript myself, but it seems like a pretty straightforward language so far.

Link to comment
Share on other sites

For the most part, code executes in the exact sequence in which you wrote it. You can create exceptions using the setInterval and setTimeout functions. Callback functions triggered by an AJAX request can also run asynchronously.In the example you quoted, a value is assigned to firstname, and that value is printed to the screen immediately. firstname is now available for another value. Recycling variables like this is actually good practice, since the environment does not have to allocate memory for a second (third, fourth, etc) variable.A more extreme example of that would be the use of a single variable inside a loop. Depending on your application, a variable could have its value reassigned 10,000 times before the loop is finished. That is much more efficient than creating 10,000 unique variables. Programs do this all the time, and as long as they are not using the kind of exceptions I mentioned above, no special care needs to be taken. The values will not clobber each other.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...