Adding variables into a Javascript file (.js)

Discussion in 'JavaScript' started by chriswick, Mar 13, 2008.

  1. #1
    I want to add variables into a Javascript file, am I doing it the right way?

    
    <script type="text/javascript">
    <!--
    var something1 = "whatever1";
    var something2 = whatever2";
    // -->
    </script>
    <script type="text/javascript" src="http://www.domain.com/file.js"></script>
    
    HTML:
    Then do I call them inside the file with this method below?

    
    document.write("something1")
    document.write("something2")
    
    HTML:

    + Rep for someone that posts someting that works!
     
    chriswick, Mar 13, 2008 IP
  2. GreatMetro

    GreatMetro Peon

    Messages:
    117
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You have it correct. By using var to create your variables outside of a function, those variables are now global to the page, as well as to any loaded js files. Be very careful in using variables in the global namespace, as when you begin working on projects involving 3rd party scripts (moo-tools, dojo, etc...) you may get some clashing of the variables.

    As an example, if you have the global variable named total_users, and somewhere in your script or a 3rd party script a local variable (a variable created within a function to be used only within that function) named total_users is created, used, or modified, you're going to run into trouble.

    If you absolutely must use global variables, and there are plenty of times when you do need to, then use very specific and easy to identify names; instead of total_users, try gblVR_total_users. The chances of that variable being used anywhere are next to nil, and by using a standard naming convention, you can easily identify the purpose of that variable months later when you've forgotten about it.

    Hope this helps.

    Also try googling "javascript variable scope"
     
    GreatMetro, Mar 13, 2008 IP