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.
Page 1 of 3 123 LastLast
Results 1 to 15 of 31
  1. #1
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    JavaScript Syntax and the ;

    as i understand it JavaScript only requires a ; when you call multiple functions during a single event in which case the ; is placed between each function i always add a space also but im not sure if that's required or just improves readability

    now i dont do much web development of any kind but when i need to do any what i usually do is find a reference for the language im using and an example or a tutorial that is doing something similar to what i want to do

    like if i want to change the property's of a division when i click something il find an example that does that most of the time the property's that they are changing are not the ones im going to change but all i want it for is a guide to make sure i use the correct syntax for the language im using everything else i get from the reference

    but i noticed that lots of examples that come from sources that focus more heavily on css use lots of ; in there JavaScript code they will have one after each task in the <script></script> tag they declare a variable they put a ; they change a value of a variable they put a ; they call a function they put a ;

    however i noticed that when the examples are from a source that is more heavily focused on JavaScript they usually don't use ; in any of them places only to separate multiple function calls in one event

    so what i want to know is does JavaScript syntax change when its working with css or is this just a case of some one that has developed a sort of accent to there syntax from using css or some other language and JavaScript just happens to still understand it any way

    as opposed to some languages where if you mess up the syntax at all things tend to just not work which is actually the reason that i try to find an example that does something slimier but different to use as a guide so i dont make a mistake with the syntax on a language i have not used recently or often

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,028
    Thanks
    75
    Thanked 4,325 Times in 4,291 Posts
    however i noticed that when the examples are from a source that is more heavily focused on JavaScript they usually don't use ; ...
    Then as soon as you see such a site, stop visiting it.

    There only a handful of places where semicolons will make any difference in JavaScript.

    BUT...

    It's a truly bad habit to get into, omitting *ANY* semicolons.

    Most experienced (and/or good!) JavaScript writers will indeed put a semicolon after every statement.

    In my personal opinion, the idiot who made them optional in JavaScript, in the first place, should be forced to write "Always use a semicolon" ten thousand times on a white board in the middle of Grand Central Station in New York. Or something equally humiliating.

    Anyway, look at some of the posts from those who post here the most often. See how very very few of them omit any semicolons. These are *GOOD* role models, not like those crap sites you have apparently visited in the past.
    Last edited by Old Pedant; 02-21-2013 at 12:11 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,028
    Thanks
    75
    Thanked 4,325 Times in 4,291 Posts
    Here, look at these *GOOD* examples:
    http://javascriptexample.net/

    From "Felgall", one of our more pedantic (even more than I) members. Try to find any missing semicolons in his code.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    namelis (02-21-2013)

  • #4
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts
    thanks i like that site it actually explains the basics which i need since i have not done any kind of web programming since like 2003 so everything i remember is years out of date though most of it will still probably still work id rather do things the most current way cause then i can expect them to stay working longer

    the examples will work for getting the syntax right most of the concepts i already understand but having the basics explained is the best part as far as im concerned since all i plan to do is get my dads site working the way he wants it then write a program off line that he can run that will ask him questions and use his responses to make his changes so he can update it when ever he wants by himself without him ever having to look at the code just putting stuff up and in some cases overwriting what's already there

    so once i have that done i probably wont do any other web programming for years so all i really need is that site and maybe one that gives some more modern css basics cause im not sure what all has changed with that but im going to be using even less of that then i am JavaScript so its probably not going to be an issue worst case scenario ill just use trial and error to determine what still works and what does not adaptability is something im good at in any case

    and if i get stuck i can always ask somewhere like here with that ; thing it was very confusing seeing it used some places and not in others for the same task now i know that while not using it may still work it's not a good idea cause then im making the computer think more and make decisions rather then giving clear instructions that all it has to do is fallow

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,898
    Thanks
    203
    Thanked 2,530 Times in 2,508 Posts
    It is recommended that you place the opening brace following the function, if, else, for, while, do, switch, and try statements on the same line and not on the following line. Apart from that every Javascript statement should be followed by a semi-colon (. It is quite possible to disregard this advice, but if you do one day it will rise up and bite you in the undercarriage.

    In other words, if you omit semi-colons one day you will find your script fails for an obscrure reason called automatic semi-colon insertion. That is more likely to occur if you disregard the first part of the advice.


    All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #6
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,277
    Thanks
    10
    Thanked 581 Times in 562 Posts
    Quote Originally Posted by Philip M View Post
    It is recommended that you place the opening brace following the function, if, else, for, while, do, switch, and try statements on the same line and not on the following line. Apart from that every Javascript statement should be followed by a semi-colon (.
    [/COLOR]
    but not the function statement! that's my pet peeve!
    semis go after function expressions, but not function statements.

    danml.com/slim has features to both "Strip semis" and "Rebuild Semis", so you can double-check that your semi's are in the right place, or simply use it to automagically add them in the right place. It's not 100% perfect if you use eval wrongly and a few other minor exceptions, but if it can't fix the code, it will error out: it NEVER produces invalid code, so it's trustworthy.


    also, firefox will insert semis when you view a function as a string. i mimic that (FF's) semi-insertion patterns on the rebuild-semi function. I get semi-colon counts very close to FF in chrome using the rebuild command...
    Last edited by rnd me; 02-21-2013 at 07:42 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,592
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by rnd me View Post
    but not the function statement! that's my pet peeve!
    semis go after function expressions, but not function statements.
    Given the limitations on function statements compared to the far more powerful function expressions there is no reason for using function statements in JavaScript at all.

    If you do use function statements then you can still use a ; after it but it counts as a separate empty statement.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,277
    Thanks
    10
    Thanked 581 Times in 562 Posts
    Quote Originally Posted by felgall View Post
    Given the limitations on function statements compared to the far more powerful function expressions there is no reason for using function statements in JavaScript at all.
    far more powerful? lol, that's a good one. they are almost the same thing...

    personally, i think using statements yields cleaner code and allows more fexibility in placement. They allow me to put my "guts" up top and "boilerplate/lib" functions below, which means i can get to the meat of a function/modules with less scrolling.

    you can also get better real-world performance in some situations using statements than expressions, due to the way JIT and even some interpreters caches functions. You can code in such a way that expressions (var fn) are optimizable like that, but that tacks another closure on the activation envelope.

    it's hard to put one's finger on any of the invisible actions behind the curtain, and everything changes often with new developments in the engines, but i have seen a difference in benchmarks before.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,028
    Thanks
    75
    Thanked 4,325 Times in 4,291 Posts
    but not the function statement! that's my pet peeve!
    semis go after function expressions, but not function statements.
    But I see that as CONSISTENT!!

    After all, you don't put a semicolon after the } after an if/while/etc.:
    Code:
    if ( a < b ) { doSomething( ); } ; // that last semicolon is bogus
    The right brace denotes the end of a block of code. Simple as that.

    So
    Code:
    if ( a < b )
    {
        statement;
        statement;
        statement;
    }
    feels no different to me than
    Code:
    function foo( a, b )
    {
        statement;
        statement;
        statement;
    }
    whereas I see an ASSIGNMENT as always needing the semicolon:
    Code:
    var obj = 
        {
             a : "whatever",
             b : "something"
        };  // semicolon to end the assignment!
    feels the same to me as
    Code:
    var func = function() 
        {
            statement;
            statement;
        };  // semicolon to end the assignment!
    I really don't feel, at all, the inconsistency you are complaining about.

    ********

    SIDE NOTE:

    You can see that I disagree with Philip--and many others--about the placement of the left braces.

    I *MUCH prefer my left braces and right braces to line up, so that it's easy to see where the code blocks begin and end.

    Of course, I also *ALWAYS* indent my code, which Philip does not do. Quite probably if I didn't indent, I might follow his lead.

    Yes I even do this with code such as:
    Code:
    if ( a < b )
    {
         somelongvariablename = someLongExpressionToGetValue;
    }
    The exception I make is when the code is short enough to fit all on one line and it makes logical sense to do it. Thus:
    Code:
    if ( a < b ) { c = 37; }
    Last edited by Old Pedant; 02-21-2013 at 11:22 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #10
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,592
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by rnd me View Post
    far more powerful? lol, that's a good one. they are almost the same thing...
    No they are not. Also it has nothing to do with performance and everything to do with all the intermediate to advanced JavaScript code that requires the use of function expressions and which simply can't be done without requiring a lot more code if you avoid function expressions. In fact a lot of function expressions produce code that is way more efficient than any possible function statement equivalent in terms of the amount of code to be run. Even if statements were to be called 5% faster than expressions the statement would still run slower if it needs 500% more code to achieve the same end result.

    Consider:

    Code:
    addEvent = function(ob, type, fn ) {
    if (window.addEventListener)
    addEvent = function(ob, type, fn ) {
      ob.addEventListener(type, fn, false );
    };
    else if (document.attachEvent)
    addEvent = function(ob, type, fn ) {
      var eProp = type + fn;
      ob['e'+eProp] = fn;
      ob[eProp] = function(){ob['e'+eProp]( window.event );};
      ob.attachEvent( 'on'+type, ob[eProp]);
    };
    addEvent(ob, type, fn );
    }
    Provide a function statement equivalent to that simple function expression that I use in almost all of my scripts is NOT possible because function statements do not allow several of the things that occur in that function - for example - defining functions inside if statements and defining several functions with the same name.

    I think that well over half of the things that can be done using functions in JavaScript will only work if you use function expressions. You are missing out on many of the more advanced features of JavaScript if you limit yourself to the far less powerful function statements.

    I teach function expressions in my JavaScript beginners class because function expressions can do everything function statements can do as well as many things that they can't. That way the students only need to learn one way to write their functions and don't need to learn the other way when they move on to learning intermediate JavaScript.
    Last edited by felgall; 02-21-2013 at 09:39 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #11
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,277
    Thanks
    10
    Thanked 581 Times in 562 Posts
    Quote Originally Posted by felgall View Post
    Consider:

    Code:
    addEvent = function(ob, type, fn ) {
    if (window.addEventListener)
    addEvent = function(ob, type, fn ) {
      ob.addEventListener(type, fn, false );
    };
    else if (document.attachEvent)
    addEvent = function(ob, type, fn ) {
      var eProp = type + fn;
      ob['e'+eProp] = fn;
      ob[eProp] = function(){ob['e'+eProp]( window.event );};
      ob.attachEvent( 'on'+type, ob[eProp]);
    };
    addEvent(ob, type, fn );
    }
    Provide a function statement equivalent to that simple function expression that I use in almost all of my scripts is NOT possible because function statements do not allow several of the things that occur in that function - for example - defining functions inside if statements and defining several functions with the same name.

    you really don't want several functions having the same name, that makes debugging hader. it's better to give each function a unique local name (instead of anon), if only for the debugger stacks alone.


    here is a version based on your core routine that has one less closure and uses debug-friendly function statements:
    (i don't think this constitutes 500% more code than your example)

    Code:
    function addEvent(ob, type, fn) {
    
    	return (document.attachEvent ? addEventIE : addEventW3)(ob, type, fn);
    
    	function addEventW3(ob, type, fn) {
    		ob.addEventListener(type, fn, false);
    	}; /* end addEventW3 */
    
    	function addEventIE(ob, type, fn) {
    		var eProp = type + fn;
    		ob['e' + eProp] = fn;
    		ob[eProp] = function IEEventHandler() {
    			ob['e' + eProp](window.event);
    		};
    		ob.attachEvent('on' + type, ob[eProp]);
    	}; /* end addEventIE() */
    
    } /* end addEvent() */
    by giving each function a name, our exception stack looks like

    click()>IEEventHandler()>function() , instead of
    click()>function()>function();

    which would you rather debug?

    ideally, i would prevent the additional closure and pre-build the routine to a specific browser. It seems rather poor practice to say "are you IE?" every time an event is added. adding click, are you IE? adding keypress, are you IE? yuck. the one good thing about the code is that i can compact it easily, whereas pre-building could throw away the IE branch if i compressed in-browser using closure, uglify, or even packer.

    if you are going to use it as an expression, then you can go ahead and do the specific flavor addEvent(), which is going to be faster, produce less garbage each execution, and avoids a fork each addEvent call:



    Code:
    var addEvent= 	document.attachEvent ?  
    
    	function addEventIE(ob, type, fn) {
    		var eProp = type + fn;
    		ob['e' + eProp] = fn;
    		ob[eProp] = function IEEventHandler() {
    			ob['e' + eProp](window.event);
    		};
    		ob.attachEvent('on' + type, ob[eProp]);
    	}; /* end addEventIE() */
      :
    	function addEventW3(ob, type, fn) {
    		ob.addEventListener(type, fn, false);
    	} /* end addEventW3 */
    
    ; /* end addEvent() */

    as you can imagine, this version is a lot lighter and faster, but is only possible to use after it appears in source-order.

    lastly, even if you use function expressions, you should give them an internal name for two reasons:
    1. the aforementioned debug stack
    2. arguments.callee is deprecated, so a name is the only way to properly recurse a function expression.
    2.5 it just reads easier and even helps some IDEs provide better context.
    Last edited by rnd me; 02-21-2013 at 11:20 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,898
    Thanks
    203
    Thanked 2,530 Times in 2,508 Posts
    Quote Originally Posted by Old Pedant View Post
    You can see that I disagree with Philip--and many others--about the placement of the left braces.

    I *MUCH prefer my left braces and right braces to line up, so that it's easy to see where the code blocks begin and end.

    Of course, I also *ALWAYS* indent my code, which Philip does not do. Quite probably if I didn't indent, I might follow his lead.
    I see these just as personal preferences. I say "tomahto", you say "tomayto". Nothing to make a fuss about.

    But for myself I would never, ever, assign the same name to multiple functions, or multiple variables, even if they were all local to their functions, unless they represented exactly the same thing.
    Last edited by Philip M; 02-21-2013 at 11:00 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #13
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,028
    Thanks
    75
    Thanked 4,325 Times in 4,291 Posts
    Well, you notice that I acknowledged that you don't stand alone on your position re the left brace. Heck, MS's Visual Studio puts them where you want them automatically when writing JavaScript code, but also C# and C++ code.

    It's just a habit I got into in my Linux days, when the only editor I had worth anything was "vi", and the one thing (almost only thing) it had going for it was that it would find your matching braces (or parens or brackets) and it was much easier to see on the (limited) screen if they were at same indent level.

    It's hard to teach an old dog (or old pedant) new tricks.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #14
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,592
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by rnd me View Post
    here is a version based on your core routine that has one less closure and uses debug-friendly function statements:
    (i don't think this constitutes 500% more code than your example)
    That's a good example of really inefficient code when compared to my version. Every time your code adds a function to an event it stops to test it the browser is now a different browser from the browser that it was the last time you added a function to an event.

    With your processing you effectively have:

    Code:
    if browser is IE8 or earlier  /* perhaps it is this time */
       add function 1 to event 1 using attachEvent 
    else 
       add function 1 to event 1 using addEventListener
    if browser is now IE8 or earlier /* and now it has been upgraded to chrome */
       add function 2 to event 2 using attachEvent 
    else 
       add function 2 to event 2 using addEventListener
    if browser is now  or earlier /* but they didn't like chrome so reverted back to IE7 */
       add function 3 to event 3 using attachEvent 
    else 
       add function 3 to event 3 using addEventListener
    if browser is now IE8 or earlier /* and have now upgraded to IE9 instead */
       add function 4 to event 4 using attachEvent 
    else 
       add function 4 to event 4 using addEventListener
    and so on testing if the browser is suddenly a different one to the one it was on the last call EACH and EVERY time you call a function. How many times do you expect the browser to change from IE8 to Chrome to IE7 to IE9 and so on during a single execution of the script?

    With my code the assumption is that the browser doesn't change. It gets tested ONCE and once only when the function is called the first time. If my code adds 1000 different functions to 1000 different events it still only tests what browser it is once. Now I personally have never seen a browser suddenly change into a different browser mid script so I can't see any point in testing for if the browser has changed every time you do something that different browsers handle differently. Obviously you haver come across such browsers since your code is written to assume that while the browser might be IE8 while adding the first function to the first event that the person might have managed to upgrade their browser to Chrome by the time you add the second function to the second event.

    Given that the addEventListener code only needs a single statement your code is running twice as many statements as mine for every call to the function from most browsers.

    So instead of making your code 500% more complex you have instead halved the efficiency of the code by doubling the number of statements that need to be run. That's even worse than using a lot more code as the small amount of extra code you added gets run lots of times instead of once.
    Last edited by felgall; 02-22-2013 at 07:45 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #15
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,898
    Thanks
    203
    Thanked 2,530 Times in 2,508 Posts
    Quote Originally Posted by Old Pedant View Post
    Well, you notice that I acknowledged that you don't stand alone on your position re the left brace. Heck, MS's Visual Studio puts them where you want them automatically when writing JavaScript code, but also C# and C++ code.

    It's just a habit I got into in my Linux days, when the only editor I had worth anything was "vi", and the one thing (almost only thing) it had going for it was that it would find your matching braces (or parens or brackets) and it was much easier to see on the (limited) screen if they were at same indent level.

    It's hard to teach an old dog (or old pedant) new tricks.
    I guess the reason that I do not indent is that in the early days of Algol, BASIC, Databus and so on, every space counted as a byte, and bytes were too precious to be wasted! I can't remember the capacity of cassette tapes, but it was pretty small. The first floppy disks were (I think) 160K capacity. Young Turks like Airblader have no notion of the days of such primitive computing. He probably thinks of us as old farts. But in truth we are sadly no longer young enough to know everything.
    Attached Thumbnails Attached Thumbnails JavaScript Syntax and the ;-olddog.jpg   JavaScript Syntax and the ;-old-dog-new-tricks.jpg  
    Last edited by Philip M; 02-22-2013 at 08:41 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  
    Page 1 of 3 123 LastLast

    Tags for this Thread

    Posting Permissions

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