Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jun 2014
    Thanked 0 Times in 0 Posts

    Problem in a global variable inside of a function


    I've always thought that variable inside of a function are always local,but recently, I've discovered that Variable can be global inside of a function if we don't use the keyword "var". Anyway, I've tried this JS code but it didn't work. Normally, it should work if we follow the previous rule. Here's the code:
    Function x()
    a = 5;

    I can't figure out what's wrong :/

  2. #2
    Master Coder sunfighter's Avatar
    Join Date
    Jan 2011
    Thanked 789 Times in 787 Posts
    First JS is case sensitive so Function x(){} won't run, but function x() will.

    Next when the page loads the alert('a'); will run and make an alert, but alert(a); will not run cause a is not a variable. NOTICE THE QUOTES.
    And it will not run when the function is called because the function ends at the '}' and nothing after that will run.

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <button onclick="x();">PUSH</button>
    <button onclick="y();">PUSH Again</button>
    function x(){
    	a = 5;  // set the global variable
    function y(){
    	alert(a);  // now the alert will work because the variable is set
    If you push buttons in sequence you will get an alert, but after reloading this and hitting 'PUSH Again' you will get nothing because you haven't set the variable.
    Last edited by sunfighter; 06-07-2014 at 06:55 PM.
    Evolution - The non-random survival of random variants.

    Because I love FLEXBOX and tired of waiting: http://davidwalsh.name/goodbye-vendor-prefixes


Posting Permissions

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