Results 1 to 20 of 20
  1.    #1  
    im starting to learn a little jsjsjs $and$ $i$ $want$ $to$ $understand$ $good$ $coding$ $practice$ $and$ $the$ $difference$ $between$ $these$ $examples$ $and$ $which$ $are$ $preferred$?


    1)
    Code:
    <script type="text/javascript">
    var firstname;
    firstname="Isaac";
    document.write(firstname);
    document.write("<br />");
    firstname="David";
    document.write(firstname);
    </script>
    1) in this example the var is declared and the value isnt until later in the script, where it also changes. as opposed to

    2)
    Code:
    <script type="text/javascript">
    var firstname="Isaac";
    </script>
    2) in the second example the declared var has an assigned value , but to my understanding i should be able to change the value later in the script by simply inputting new information for the value

    Code:
    firstname="George"

    3) Also why should i even formally delare a var if i can simply lose the tag and the var becomes declared anyway??

    Code:
    <script type="text/javascript">
    firstname="Isaac";
    </script>
    sorry for the no0b post , just curious as to best practices... thanks
  2. #2  
    You are correct in your assumptions for the most part. Best practice is to use the var keyword when declaring variables. It helps avoid issues with global variables amongst other things.
  3.    #3  
    Quote Originally Posted by semprance View Post
    You are correct in your assumptions for the most part. Best practice is to use the var keyword when declaring variables. It helps avoid issues with global variables amongst other things.
    thanks for your response..


    so this is best practice?

    Code:
    <script type="text/javascript">
    var firstname="Isaac";
    </script>
    or

    Code:
    <script type="text/javascript">
    var firstname;
    firstname="Isaac";
    </script>
    also im having trouble understanding the use of switch as opposed to if else and vice versa
  4. #4  
    Both are acceptable for basic best practices. Which you choose would be based more on reading preference and/or organizational guidelines.

    A switch allows you to evaluate an expression once and go straight to the intended execution. A switch can reduce cycles and it looks better then a giant If-Else statement of DOOM! You can also use a switch to jump to a point and fall-though successive steps if you don't include breaks, basically it would do what a simple set of nested if statements would be able to do in that case.
    Last edited by Orion Antares; 11/02/2010 at 05:46 PM.
  5. #5  
    Code:
    <script type="text/javascript">
    var firstname="Isaac";
    </script>
    This one.
  6. #6  
    Javascript handles memory allocation dynamically. If you're using a variable over and over for the same type of data (i.e. in a long loop) declare it then assign values as needed. If not, then IMHO it makes your code look a lot more concise and clean to assign the value on the same line( var whatever='whatever'; ) but doesn't really make any difference from the interpreters point of view one way or the other.

    As a note, to clarify what semprance said. If you don't put 'var' in there the first time you use a variable, then the javascript engine assumes it's a global variable. Basically, from the interpreter's standpoint these two snippets are the same(the second is still not considered good practice since it can make reading the code difficult and can lead to you confusing timelines in your code):
    Code:
    var someGlobal = 'I'm a Global Variable';
    function aFunction(){
      alert(someGlobal);
    }
    aFunction();
    alert(someGlobal);
    Code:
    function aFunction(){
    someGlobal = 'I'm a Global Variable';
    alert(someGlobal);
    }
    aFunction();
    alert(someGlobal);
    danNielson.com - Slalom - twitter - facebook
    A posted thanks dies with the thread. Clicking the button lasts until the admins get bored with this site and throw it in the recycling bin.
  7.    #7  
    thanks for all the clarifications ... i had a feeling this was the case.



    currently im just learning the basics and understanding of coding , hopefully ill be able to get these down so i can move onto the next step.. just there seems to be no consistency with jsjsjs .
  8. #8  
    It's a very flexible language. Although there are some conventions that are better than others functionality wise, a lot of the way you use the language is down to your preferred coding style.
  9. #9  
    Quote Originally Posted by sketch42 View Post
    .. just there seems to be no consistency with jsjsjs .
    What did you mean by this?
  10. #10  
    I typically declare a variable with var, and assign it a default value. This is in line with other languages that don't dynamically allocate memory and allow free use of variables. In languages such as C, you have to declare a variable and the type, and, without initializing it to some default, it could be anything. Setting the default also allows you to look back to the declaration later to see what kind of variable it is suppose to be, and potentially a sample value.

    But you will sometimes catch me not declaring a variable in JSJSJS, $especially$ $throw$ $away$ $ones$. $And$ $I$ $won$'$t$ $always$ $initialize$ $strings$ $to$ $empty$ $strings$ $in$ $JS$. $But$ $these$ $are$ $exceptions$ $to$ $my$ $rule$.

    I have noticed that some Javascript debuggers (like Firebug or Ares) will show variables declared with var as local variables, making them easy to find in the watch panels, while other variables that are not declared explicitly are not in the list of local variables.

    So, in general, declare your local variables with var, and initialize them if possible. This will be readable, easy to follow, and have advantages if you choose to port the code to another language. It's not much more work and might make your life easier in the long run.
  11.    #11  
    Quote Originally Posted by johncc View Post
    What did you mean by this?
    I mean that there are too many ways to do 1 thing... And not all are the best method.

    Meaning the fact that I can declare a var without declaring it seems more problematic for first timers

    -- Sent from my Palm Pre using Forums Beta
  12.    #12  
    Quote Originally Posted by jdiwnab View Post
    I typically declare a variable with var, and assign it a default value. This is in line with other languages that don't dynamically allocate memory and allow free use of variables. In languages such as C, you have to declare a variable and the type, and, without initializing it to some default, it could be anything. Setting the default also allows you to look back to the declaration later to see what kind of variable it is suppose to be, and potentially a sample value.

    But you will sometimes catch me not declaring a variable in JSJSJS, $especially$ $throw$ $away$ $ones$. $And$ $I$ $won$'$t$ $always$ $initialize$ $strings$ $to$ $empty$ $strings$ $in$ $JS$. $But$ $these$ $are$ $exceptions$ $to$ $my$ $rule$.

    I have noticed that some Javascript debuggers (like Firebug or Ares) will show variables declared with var as local variables, making them easy to find in the watch panels, while other variables that are not declared explicitly are not in the list of local variables.

    So, in general, declare your local variables with var, and initialize them if possible. This will be readable, easy to follow, and have advantages if you choose to port the code to another language. It's not much more work and might make your life easier in the long run.
    Oh , I get it now.. I like the method you just posted .. Of not declaring a var if it's a one use etc..

    Also generally do browsers respond better with external jsjsjs $files$ $or$ $embedded$ $in$ $the$ $html$..

    -- Sent from my Palm Pre using Forums Beta
  13. #13  
    Quote Originally Posted by sketch42 View Post
    I mean that there are too many ways to do 1 thing... And not all are the best method.

    Meaning the fact that I can declare a var without declaring it seems more problematic for first timers

    -- Sent from my Palm Pre using Forums Beta
    Not really inconsitent then. Maybe less rigid or too flexible.
  14. #14  
    Quote Originally Posted by sketch42 View Post
    Oh , I get it now.. I like the method you just posted .. Of not declaring a var if it's a one use etc..

    Also generally do browsers respond better with external jsjsjs $files$ $or$ $embedded$ $in$ $the$ $html$..

    -- Sent from my Palm Pre using Forums Beta
    I will say that not declaring a variable if it's a one time use is more due to laziness than an actual system.

    In a more traditional sense of a browser, the main HTML page loads first. The browser finds all the includes, requests them, then inserts them into those include locations. It then executes it.

    So, in a strict sense, there is a performance hit for not including it in your main page. However, this is offset by both browser caching and ease of maintenance. If a particular script is used in many places, putting it in an external file means the browser doesn't have to load the script multiple times, saving bandwidth and some time.
  15. #15  
    Quote Originally Posted by sketch42 View Post
    Oh , I get it now.. I like the method you just posted .. Of not declaring a var if it's a one use etc..

    Also generally do browsers respond better with external jsjsjs $files$ $or$ $embedded$ $in$ $the$ $html$..

    -- Sent from my Palm Pre using Forums Beta
    Yeah, with jsjsjs $you$ $can$ $have$ $a$ $typo$ $and$ $the$ $app$ $may$ $still$ $run$, $just$ $with$ $enexpected$ $results$.
  16. #16  
    Quote Originally Posted by sketch42 View Post
    Also generally do browsers respond better with external jsjsjs $files$ $or$ $embedded$ $in$ $the$ $html$..
    Again I suppose it's a preference, but I tend to have external. If you want to your HTML to be W3C-valid it will have to be in external jsjsjs $files$, $as$ $any$ $greater$-$than$ $or$ $smaller$-$than$ $characters$ $used$ $in$ $your$ $javascript$ $will$ $be$ $picked$ $up$ $by$ $the$ $W3C$ $Validator$ $as$ $being$ $tag$-$openers$/$closers$ $and$ $thus$ $will$ $crop$ $up$ $as$ $errors$.

    (Meaning you won't be able to put one of those ugly W3C 'Valid HTML' buttons on your page! Oh no!)
  17. #17  
    The only way to not have a global variable is to declare it inside a function with "var" as the declaration.

    Example:

    Code:
    // globals
    var helloWorld = "Hello World!";
    goodbyeWorld = "So long world!";
    function something() {
        iAmBackWorld = "I'm back!";
    }
    
    // local
    function anotherThing() {
        var iAmLocal = "I am a local variable";
    }
    Arthur Thornton

    Former webOS DevRel Engineer at Palm, HP, and LG
    Former webOS app developer (built Voice Memos, Sparrow, and several homebrew apps and patches)
    Former blogger for webOS Nation and webOS Roundup
  18.    #18  
    Quote Originally Posted by arthurthornton View Post
    The only way to not have a global variable is to declare it inside a function with "var" as the declaration.

    Example:

    Code:
    // globals
    var helloWorld = "Hello World!";
    goodbyeWorld = "So long world!";
    function something() {
        iAmBackWorld = "I'm back!";
    }
    
    // local
    function anotherThing() {
        var iAmLocal = "I am a local variable";
    }
    ok ... im still trying to get this.. .

    Edit: before i put my foot in my mouth , this is the way i understand global and local var

    Local:
    When a function is defined, certain variables are incorporated inside the function. These variables are used only inside these functions.

    Since functions are separate from the main code, variables included in them should be initialized only when the function is called and discarded when executed. They have no presence outside the function.

    Variables that exist throughout the script are called Global variables. Their values can be changed anytime in the code and even by other functions.

    But i was reading this as well
    The values of such Local variables cannot be changed by the main code or other functions.
    This results in easy code maintenance and is especially helpful if many programmers are working together on the same project.
    i thought i can change a var at anytime ... wheather it was a local or global by simply


    Code:
    // globals
    var helloWorld = "Hello World!";
    goodbyeWorld = "So long world!";
    function something() {
        iAmBackWorld = "I'm back!";
    
    document.write(goodbyeWorld) // here is where the var is executed and now i can setup to change the var since its been executed
    
    goodbyeWorld = "I can't Go"; // so here i changed the var of goodbyeWorld
    
    }
    
    // local
    function anotherThing() {
        var iAmLocal = "I am a local variable";
    }
    can i Not do the same with a local?
  19. #19  
    Yes, a local variable can be changed in it's own scope. That is, if a var is in a function like:

    Code:
    function anotherThing() {
        var iAmLocal = "I am a local variable";
    }
    Then the iAmLocal var is accessible ONLY between the curly brackets (meaning of course it's only accessible during execution of the method). It's then discarded once the method finishes execution, and is inacessible from that point on.

    For this:


    Code:
    function anotherThing() {
        iAmLocal = "I am a local variable";
    }
    the variable will live on after the function has finished executing.

    As for this:

    The values of such Local variables cannot be changed by the main code or other functions.
    This results in easy code maintenance and is especially helpful if many programmers are working together on the same project.
    It says that the local variables cannot be changed by the main code (eg. commands run outside of any functions and thus not in the same scope) or other functions (as the variable would not be local to them obviously).

    So the following applies:

    Code:
    function myFunc() {
        var myVar = 'blah';
    }
    
    myVar = 'blah'; //Ambiguous: This is not accessing the variable in myFunc, but instead is a whole new global variable.
    
    function myNextFunc() {
        myVar = 'blah'; //Again we're accessing the global variable.
    }

Posting Permissions