Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    Regular Coder
    Join Date
    May 2004
    Location
    Minneapolis, MN, USA
    Posts
    904
    Thanks
    0
    Thanked 0 Times in 0 Posts

    syntax details: semicolon optional sometimes? and what's with var?

    I thought I learned at first that the semicolon was never optional to end a statement in JS, save for conditional blocks, but I've come to find that's not true? Is it also optional if the statement is the last in a conditional block, similar to CSS?

    Example:

    Code:
    var d = document;
    window.onload = function() {
    	var inputs = d.getElementsByTagName("input");
    	for (i=0; i<inputs.length; i++) {
    		var type = inputs[i].getAttribute("type");
    		if (type == "text") {
    			inputs[i].onfocus = function() {this.style.backgroundColor = "#EEE"}
    		} else if ((type == "submit")||(type == "reset")) {
    			inputs[i].onmouseover = function() {this.style.cursor = "pointer"}
    			inputs[i].onmouseout = function() {this.style.cursor = "default"}
    		}
    	}
    }
    Seems to work fine... is that a feature of JS or my browser making up for my "mistakes"?

    Also: what's the story on var? I see it used when first declaring a variable, but not always...
    Last edited by ]|V|[agnus; 01-05-2005 at 06:17 PM.

  • #2
    Regular Coder
    Join Date
    Jun 2002
    Posts
    626
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I believe the only time the semicolon is required is when you place more than one statement on the same line, such as:
    function_call();another_function_call();a="Hello";b="what";

    I would not recommend the above though.

    "var" is not required as far as I know. I used "var" when I first started, but not anymore.

  • #3
    Regular Coder
    Join Date
    Oct 2004
    Posts
    168
    Thanks
    0
    Thanked 5 Times in 5 Posts
    Ending a statement with a semi-colon is only mission-critical if there are further statements on the same line - like css. However, it is good practice to end single statement lines with a semi-colon.

    In many situations using var or not has no impact on the functionality of the code however you should consider two points :

    1
    Using var to declare a variable from within a function makes that variable local to that function and, therefore, not available to other functions.
    Have a play:

    <html>
    <head>
    <title>var keyword</title>
    <script>
    function alertOne()
    {
    x=7;
    // var x=7 makes x local to this function
    alert(x);
    }

    function alertTwo()
    {
    alert(x);
    }
    </script>
    </head>
    <body>
    <button onClick="alertOne()">One</button>
    <button onClick="alertTwo()">Two</button>
    </body>
    </html>

    2
    variables cannot be deleted if they are declared with var.
    Play with this:

    x=7;
    var y=9;

    delete x;
    delete y;

    document.write(x);
    document.write(y);

    HTH

    PS
    Actually, I would add a third point, from a coding point of view it is usually best to localise your variables wherever possible, particularly if you are collaborating on a project.
    Last edited by Puffin the Erb; 01-05-2005 at 09:22 PM.

  • #4
    Regular Coder
    Join Date
    May 2004
    Location
    Minneapolis, MN, USA
    Posts
    904
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Ending a statement with a semi-colon is only mission-critical if there are further statements on the same line - like css.
    Not quite true. CSS requires the semicolon on all statements except the last one in a set.

    Thanks for the info, guys.

  • #5
    New to the CF scene
    Join Date
    Jan 2005
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Variable Scope.

    I don't believe it's nessesary to declare a varable. If, however, the varable is inside a fuction it will be used only locally if you use var.

    There is a decent description on this here

  • #6
    Senior Coder
    Join Date
    Jun 2002
    Location
    near Oswestry
    Posts
    4,508
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You should always declare a variable the first time you use it, but not again if re-using it. Where you declare it determines its scope.

    Semi-colon terminators are not always required for functionality, but you should always include them anyway - it's a good habit to get into, so you don't get problems if you ever want to concatenate your scripts to save filesize. And it makes code more consistent and easier to read.

    Remember that a function is a variable as well - it should also end in a semi-colon:
    Code:
    function something()
    {
    
    };
    
    foobar.onmouseover = function()
    {
    
    };
    Try coding with mozilla's JS console set to show warnings as well as errors; and this article by Alex may be useful: http://javascriptkit.com/javatutors/serror.shtml
    Last edited by brothercake; 01-06-2005 at 01:01 AM.
    "Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark

  • #7
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Well, JavaScript uses something called semicolon insertion. Essentially, it means that in most cases where two constructs are separated by one or more newlines and treating them as a single line doesn't make sense, the code is treated as if there were a semicolon in between. There are some special cases and some things to watch out for, though. First of all, there are a number of cases where semicolon insertion takes place even if it makes sense to treat several lines as one. These are for example the return-, continue-, break- and throw-statement; as well as the postfix (++ and --) expressions. Some other rules are also important. Semicolons are never inserted where they would mean the creation of an empty statement. They are also never inserted in such a manner that they become one of the two syntactical semicolons necessary for the for-statement. The relevant part of the ECMAScript spec (which is one of the least techno-babbly parts of the spec) reads like this:

    7.9 Automatic Semicolon Insertion
    Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must be terminated withsemicolons. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.



    7.9.1 Rules of Automatic Semicolon Insertion
    • When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
      1. The offending token is separated from the previous token by at least one LineTerminator.
      2. The offending token is }.
    • When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
    • When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation “[no LineTerminator here]” within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

    However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted automatically if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in the header of a for statement (section 12.6.3).

    NOTE These are the only restricted productions in the grammar:
    Code:
    PostfixExpression :
        LeftHandSideExpression [no LineTerminator here] ++
        LeftHandSideExpression [no LineTerminator here] --
    
    ContinueStatement :
        continue [no LineTerminator here] Identifieropt ;
    
    BreakStatement :
        break [no LineTerminator here] Identifieropt ;
    
    ReturnStatement :
        return [no LineTerminator here] Expressionopt ;
    
    ThrowStatement :
        throw [no LineTerminator here] Expression ;
    The practical effect of these restricted productions is as follows:
    • When a ++ or -- token is encountered where the parser would treat it as a postfix operator, and at least one LineTerminator occurred between the preceding token and the ++ or -- token, then a semicolon is automatically inserted before the ++ or -- token.
    • When a continue, break, return, or throw token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after the continue, break, return, or throw token.

    The resulting practical advice to ECMAScript programmers is:
    • A postfix ++ or -- operator should appear on the same line as its operand.
    • An Expression in a return or throw statement should start on the same line as the return or throw token.
    • A label in a break or continue statement should be on the same line as the break or continue token.




    7.9.2 Examples of Automatic Semicolon Insertion
    The source
    Code:
    { 1 2 } 3
    is not a valid sentence in the ECMAScript grammar, even with the automatic semicolon insertion rules. In contrast, the source
    Code:
    { 1
    2 } 3
    is also not a valid ECMAScript sentence, but is transformed by automatic semicolon insertion into the following:
    Code:
    { 1
    ;2 ;} 3;
    which is a valid ECMAScript sentence.
    The source
    Code:
    for (a; b
    )
    is not a valid ECMAScript sentence and is not altered by automatic semicolon insertion because the semicolon is needed for the header of a for statement. Automatic semicolon insertion never inserts one of the two semicolons in the header of a for statement.
    The source
    Code:
    return
    a + b
    is transformed by automatic semicolon insertion into the following:
    Code:
    return;
    a + b;
    NOTE The expression a + b is not treated as a value to be returned by the return statement, because a LineTerminator separates it from the token return.
    The source
    Code:
    a = b
    ++c
    is transformed by automatic semicolon insertion into the following:
    Code:
    a = b;
    ++c;
    NOTE The token ++ is not treated as a postfix operator applying to the variable b, because a LineTerminator occurs between b and ++.
    The source
    Code:
    if (a > b)
    else c = d
    is not a valid ECMAScript sentence and is not altered by automatic semicolon insertion before the else token, even though no production of the grammar applies at that point, because an automatically inserted semicolon would then be parsed as an empty statement.
    The source
    Code:
    a = b + c
    (d + e).print()
    is not transformed by automatic semicolon insertion, because the parenthesised expression that begins the second line can be interpreted as an argument list for a function call:
    Code:
    a = b + c(d + e).print()
    In the circumstance that an assignment statement must begin with a left parenthesis, it is a good idea for the programmer to provide an explicit semicolon at the end of the preceding statement rather than to rely on automatic semicolon insertion.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #8
    Regular Coder
    Join Date
    May 2004
    Location
    Minneapolis, MN, USA
    Posts
    904
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Much thanks, fellas.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •