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 37
  1. #1
    Regular Coder
    Join Date
    Apr 2012
    Posts
    104
    Thanks
    27
    Thanked 2 Times in 2 Posts

    Why is my JavaScript code WORKING?

    I havent even declared x,y and z as variables!

    Code:
    	x=10;
    	y=20;
    	z = x+y;
    	document.getElementById('good').innerHTML=z;
    I am getting so confused... since the time i started learning JS i thought declaring variables (var x,y,z was real important!
    Everything is simpler with jQuery!

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,303
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    The var keyword is technically optional (but it is strongly recommended that it should be used). If a variable is declared outside a function then it has global scope whether or not the var keyword is used. If the variable is declared within a function then if the var keyword is used then the variable is local to that function only, and is not available to other functions in the script. If the variable is declared within a function without the var keyword then it is global in scope. In general global variables should be avoided as far as possible. So yes, it is really important to use the var keyword.

    Code:
    <script type="text/javascript">
    
    var a = 10;  // global
    b = 12;  // also global
    
    function dosums() {
    var d = 35;  // local to this function only;
    c = 15; // global
    }
    
    dosums();  // to initiate c and d 
    
    alert (a);
    alert (b);
    alert (c);
    alert (d);
    
    </script>

    In theory, there isn't any difference between the theory and practice. In practice, there is.
    Last edited by Philip M; 05-17-2012 at 06:00 PM. Reason: typo

    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.

  • Users who have thanked Philip M for this post:

    Peeyush (05-18-2012)

  • #3
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,918
    Thanks
    6
    Thanked 1,040 Times in 1,013 Posts
    And note that JavaScript’s strict mode “global variables” defined without the var keyword are errors (i. e. they aren’t allowed to be declared like that).

  • Users who have thanked VIPStephan for this post:

    Peeyush (05-18-2012)

  • #4
    Regular Coder
    Join Date
    Apr 2012
    Posts
    104
    Thanks
    27
    Thanked 2 Times in 2 Posts
    Quote Originally Posted by Philip M View Post
    The var keyword is technically optional (but it is strongly recommended that it should be used). If a variable is declared outside a function then it has global scope whether or not the var keyword is used. If the variable is declared within a function then if the var keyword is used then the variable is local to that function only, and is not available to other functions in the script. If the variable is declared within a function without the var keyword then it is global in scope. In general global variables should be avoided as far as possible. So yes, it is really important to use the var keyword.

    Code:
    <script type="text/javascript">
    
    var a = 10;  // global
    b = 12;  // also global
    
    function dosums() {
    var d = 35;  // local to this function only;
    c = 15; // global
    }
    
    dosums();  // to initiate c and d 
    
    alert (a);
    alert (b);
    alert (c);
    alert (d);
    
    </script>

    In theory, there isn't any difference between the theory and practice. In practice, there is.
    Why do you, and many programmers on these forums suggest that global variables shall be avoided? sorry i am new to this level of programming....
    Everything is simpler with jQuery!

  • #5
    Regular Coder
    Join Date
    Apr 2012
    Posts
    104
    Thanks
    27
    Thanked 2 Times in 2 Posts
    And yeah, why avoid tables? i have heard this sooo many times - 'you must avoid tables'.. anything else i must avoid?
    Everything is simpler with jQuery!

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Peeyush View Post
    Why do you, and many programmers on these forums suggest that global variables shall be avoided? sorry i am new to this level of programming....
    About one in ten JavaScript questions I see is someone asking why adding two scripts to the same page means that one or both don't work properly while either one will worjk by itself. The reason is always that they are trying to use the same global for different purposes.

    By keeping the number of globals to a minimum you reduce the possibility of a conflict. For example the only thing that the latest version of my marquee script has that is global is one class name - you put that class name on each block element in the page you want to have scroll and the script does the rest. Only if you were to try to apply a different script that tried to interact with the same elements in a different way would you have a conflict.

    Provided that all of your JavaScript is together and not scattered through the HTML you can effectively set up a separate namespace for all the variables by wrapping the entire script inside an anonymous function.

    Code:
    (function() {
    // your javascript here
    })();
    The new strict version of JavaScript gives better control over what variables are local and which are global by requiring that all variables be declared. The old version of JavaScript makes a variable global if you use if without declaring it. The reason for this change is that it helps to enforce you deciding on which scope each variable is declared in instead of ending up with some accidentally global because you forgot to declare them (which is often the reason for conflicts).

    If you look at any of the JavaScript frameworks you will find that they generally have only one or two global variables - for example prototype only has $() in the global scope and jQuery only has jquery() and $() in the global scope (with one as an alias of the other and with the ability to turn off the alias if it conflicts - such as if you are silly enough to want to use prototype and jQuery in the same page).
    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.

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Peeyush View Post
    And yeah, why avoid tables? i have heard this sooo many times - 'you must avoid tables'.. anything else i must avoid?
    It isn't so much that you should avoid tables - instead it is a matter of using the right tags for what the content is. Using a table identifies the content as tabular data and so you should use a table when the content is tabular data and not use a table when it isn't - just as you use a paragraph tag when the content is a paragraph and don't use a paragraph tag when the content is a list or a heading.

    The easiest way to tell if the content really belongs in a table is to consider whether it will still lokk acceptable in those mobile browsers that always display a border around table cells regardless of what you specify in your page.

    If you want table like behaviour for the appearance then all current browsers except IE7 can provide that using display:table, display:table-row and display:table-cell in your CSS.

    As for other things to avoid - as far as JavaScript is concerned I have listed all the main ones (together with reasons why) at http://javascriptexample.net/badjs.php
    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.

  • Users who have thanked felgall for this post:

    Peeyush (05-18-2012)

  • #8
    Regular Coder
    Join Date
    Apr 2012
    Posts
    104
    Thanks
    27
    Thanked 2 Times in 2 Posts
    Hey thanks, here is a sample code, could you tell me which of the variables are global and which local? it will help me understand better:

    Code:
    var a,b,c;
    
    a = 1;
    
    var f = 10;
    
    function main()
    {
          var g;
          b=3;
          d=4;
          var e =5;
          var c = 6;
    }
    function other()
    {
        g = 60;
    }
    Everything is simpler with jQuery!

  • #9
    Regular Coder
    Join Date
    Apr 2012
    Posts
    104
    Thanks
    27
    Thanked 2 Times in 2 Posts
    your site says that JS in head is bad. am i doing things rightly?

    Code:
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    	<title>List Of</title>
    	<link href="stylef.css" rel="stylesheet" type="text/css" />
    	<script src="javaf.js" type="text/javascript" ></script>
        <link href="xmlf.xml" rel="alternate" type="application/rss+xml" />
    </head>
    Everything is simpler with jQuery!

  • #10
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Peeyush View Post
    Hey thanks, here is a sample code, could you tell me which of the variables are global and which local? it will help me understand better:

    Code:
    var a,b,c;
    
    a = 1;
    
    var f = 10;
    
    function main()
    {
          var g;
          b=3;
          d=4;
          var e =5;
          var c = 6;
    }
    function other()
    {
        g = 60;
    }
    There are global variables - a, b, c, d, f, and g.
    Variables local to main() are - c, e, g (note that the c and g are different variables from the global ones of the same name so the global ones would need to be accessed as window.c and window.g from within that function).
    The other() function has no local variables.
    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
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Peeyush View Post
    your site says that JS in head is bad. am i doing things rightly?

    Code:
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    	<title>List Of</title>
    	<link href="stylef.css" rel="stylesheet" type="text/css" />
    	<script src="javaf.js" type="text/javascript" ></script>
        <link href="xmlf.xml" rel="alternate" type="application/rss+xml" />
    </head>
    Browsers will delay rendering the page until any JavaScript files that have started downloading have finished - just in case they contain document.write statements. So by requesting JavaScript files early you slow the page showing up in the browser. Also if the script doesn't use document.write it will likely be referencing elements within the page and so you don't want the script to run before the elements it references are loaded. Also at the bottom of the page most scripts can run straight away instead of having to wait for all the other files in the page to finish loading.

    So placing the script at the bottom means the page renders faster and the script runs sooner.
    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.

  • #12
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,303
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Quote Originally Posted by felgall View Post
    About one in ten JavaScript questions I see is someone asking why adding two scripts to the same page means that one or both don't work properly while either one will worjk by itself. The reason is always that they are trying to use the same global for different purposes.
    There are in fact two reasons why two scripts may conflict:-

    a) duplicate global variable and/or function names (including loop counters etc.)
    b) multiple onload statements.

    The issue of conflicting global variables can be dealt with by assigning meaningful names to the variables rather than a, b and c. In other words, a descriptive name such as customerFirstName is less likely to conflict.
    Last edited by Philip M; 05-18-2012 at 08:31 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.

  • #13
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by iBall View Post
    Yes technically that is true, but the amount of javascript I write is small and users, even on slow dialup connections, would not notice the difference if my js was in the head or in the body.

    So I normally put the js in the head so I don't have to scroll down to the bottom of the page to get to it.
    All the JavaScript I now write consists of one or at most two script tags at the bottom of the HTML - with all the code in an external file. So there generally isn't a need to scroll the HTML, I just go straight to the js file. If you are working with JavaScript the only time you need to touch the HTML at all is to add the script tag.

    It is no harder to add the tag at the bottom than it is to add it at the top and so no reason not to get that the benefits even if they will be too small to notice - when two alternatives are equally easy then there's no reason for using the one that slows things down by even a microsecond. Anyway, it is most likely that you will need more JavaScript if you attach it at the top to get the script to wait for all the ids it references to load first so loading the script at the bottom can also make the amount of code you need to write less - making that the far easier option as well.

    The scripts I write would need to have extra code added if you put them at the top of the page as they are designed to interact with HTML elements already rendered in the page at the time the script loads.

    For example the latest version of my marquee script:

    Code:
    // Continuous Text Marquee
    // copyright 30th September 2009, 2nd May 2012 by Stephen Chapman
    // http://www.felgall.com
    // permission to use this Javascript on your web page is granted
    // provided that all of the code below in this script (including these
    // comments) is used without any alteration
    
    (function(speed,cl) {"use strict";var nodes, i, ii, mqr, objwidth, mq, mqRotate;mqr = [];if (!document.getElementsByClassName) document.getElementsByClassName = function(cl) {var retNode, myclass, elem, classes, i, ii;retnode = [];myclass = new RegExp('\\b'+cl+'\\b');elem = this.getElementsByTagName('*');for (i = 0, ii = elem.length; i < ii; i++) {classes = elem[i].className;if (myclass.test(classes)) retnode.push(elem[i]);}return retnode;};objWidth = function(obj) {return obj.offsetWidth || obj.clip.width;};mq = function(node){var wid, fulwid, txt, heit, maxw, s;this.mqo=node;txt = this.mqo.innerHTML;this.mqo.style.position = 'relative';this.mqo.style.overflow = 'hidden';s = document.createElement('span');  this.mqo.appendChild(s);this.mqo.getElementsByTagName('span')[0].style.whiteSpace = 'nowrap'; this.mqo.getElementsByTagName('span')[0].innerHTML = txt;wid = objWidth(this.mqo.getElementsByTagName('span')[0])+ 5;fulwid = objWidth(this.mqo);this.mqo.innerHTML = '';heit = this.mqo.style.height;this.mqo.onmouseout=function() {mqr[0].TO=setInterval(function() {mqRotate(mqr);},speed)};this.mqo.onmouseover=function() {clearInterval(mqr[0].TO);};this.mqo.ary=[];maxw = Math.ceil(fulwid/wid)+1;for (var i=0;i < maxw;i++){this.mqo.ary[i]=document.createElement('div');this.mqo.ary[i].innerHTML = txt;this.mqo.ary[i].style.position = 'absolute';this.mqo.ary[i].style.left = (wid*i)+'px';this.mqo.ary[i].style.width = wid+'px';this.mqo.ary[i].style.height = heit;this.mqo.appendChild(this.mqo.ary[i]);}return this.mqo;};mqRotate = function(mqr){   var j, i, x, y, z, maxa;for (j=mqr.length - 1; j > -1; j--) {maxa = mqr[j].ary.length;for (i=0;i<maxa;i++){x = mqr[j].ary[i].style;x.left=(parseInt(x.left,10)-1)+'px';}y = mqr[j].ary[0].style;if (parseInt(y.left,10)+parseInt(y.width,10)<0) {z = mqr[j].ary.shift();z.style.left = (parseInt(z.style.left,10) + parseInt(z.style.width,10)*maxa) + 'px';   mqr[j].ary.push(z);}}};nodes = document.getElementsByClassName(cl);for (i = 0, ii = nodes.length; i < ii; i++) {mqr.push(new mq(nodes[i]));};if (mqr.length>0)mqr[0].TO=setInterval(function() {mqRotate(mqr);},speed);
    })(50,'marquee');
    That will interact with any <div class="marquee"> tag that appears before the script tag that attaches the script but will ignore any <div class="marquee"> tag that comes after the <script> tag. To get it to work at the top of the page you'd need to add a delay until the HTML finishes loading (or the entire page for those browsers that don't recognise when the DOM finishes loading.
    Last edited by felgall; 05-18-2012 at 09:03 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.

  • #14
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,303
    Thanks
    203
    Thanked 2,562 Times in 2,540 Posts
    Take no notice of iBall! He only repeats what others have already contributed in order to increase his post count. His reputation has now progressed beyond "iBall can only hope to improve" to "iBall is infamous around these parts". How true. I think he holds the world's record for the number of times he has been banned from this forum.

    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.

  • #15
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by iBall View Post
    that's ok If you prefer to put all your js at the bottom that's fine by me.

    I prefer to put mine in the head normally for the reasons I posted before.
    It isn't a matter of preference - it is a matter of brevity of code and ease of maintenance. You didn't post any actual reason for placing your scripts in the head of the page other than personal preference and a total disregard for the visitors to your page.

    There are four points at which you might want to run JavaScript in a web page.

    1. As soon as possible before the page renders. Here you must place the script in the head. An example of such a script is:

    Code:
    if (top.location != self.location && uri.args) top.location = self.location;
    I am still looking for a second example of a script that needs to go in the head that isn't a variant of that script.

    2. As soon as possible after the element it interacts with has loaded. The point where such a script would run quickest is with the script tag immediately after that of the element it references. This would jumble the JavaScript with the HTML and the improved maintainability of attaching the script to the bottom rather than immediately after the element more than makes up for the microscopic time saving. If you put such a script in the head you need to make it a function triggered by a domready event (something not all browsers support) - anyway that means more code in the script than is needed if you put the script after the element it interacts with.

    3. After the entire page has loaded - unless your page has lots of huge images this will not be noticeably later than when the HTML finishes loading. So for most cases you can get away with simply including the script at the bottom and not bothering to test if all the images have loaded (if the script uses lots of images then you should consider using just in time loading where you load the images as the script runs). This means that by placing your script at the bottom of the page you get rid of almost all situations where a window onload = event handler is needed and in the rare situation where you really do need to wait you can use the slightly longer event listener equivalent and so avoid one of the JavaScript beginner's biggest conflict issues completely.

    4. In response to an event - with these scripts the page will have loaded long before the script is called so it doesn't matter where you attach it but the page will still load slightly faster with it at the bottom and with all your other scripts at the bottom it makes little sense to put it anywhere else.

    As I have found only one example of the first of these and no situations where the third applies and since the second saves a lot of code when the script is at the bottom there is no reason why you should place any script other than that one example I posted anywhere but at the bottom of your HTML. After all with the script in a separate file there will not be any reason to go to the script tag anyway - you'd make any changes to the JavaScript in the JavaScript file - not in the HTML file.

    With all the issues beginners have with clashes between multiple onloads where simply placing the scripts at the bottom does away with the need for onloads almost completely I am starting to consider adding onload to my list of the bad bits of JavaScript that should almost never be used. I really need to find an example of where it is needed though first so that I can give that as an example of where it should be used. I haven't come across a script that can't be rewritten to get rid of it though so I am still looking.
    Last edited by felgall; 05-18-2012 at 11:05 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.


  •  
    Page 1 of 3 123 LastLast

    Posting Permissions

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