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 38

Thread: if(variable)

  1. #1
    New Coder
    Join Date
    Nov 2008
    Posts
    54
    Thanks
    2
    Thanked 0 Times in 0 Posts

    if(variable)

    hi guys
    if(variable) is not returning either true or false.
    what's up with that?
    i thought it should return falsy (undefined) if i haven't declared it.
    i set up an alert but nothing is being alerted. what gives?
    cheers

  • #2
    Regular Coder
    Join Date
    Aug 2010
    Posts
    972
    Thanks
    19
    Thanked 212 Times in 210 Posts
    if you use a variable that
    has not been defined ...
    if(a){}// throws error a is undefined
    the result is an error
    But this is OK ...
    a = undefined;
    alert(a)//alerts undefined
    if(a){}
    go figure ?

  • #3
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,677
    Thanks
    6
    Thanked 1,008 Times in 981 Posts
    You need to check if(typeof a !== 'undefined') {…} if you’re not sure whether or not the variable is declared.

  • #4
    Regular Coder
    Join Date
    Aug 2010
    Posts
    972
    Thanks
    19
    Thanked 212 Times in 210 Posts
    a = undefined;
    alert(typeof a)// alerts(undefined)


    a is declared


    //a = undefined;
    alert(typeof a)// alerts(undefined)


    a is undeclared

  • #5
    New Coder
    Join Date
    Nov 2008
    Posts
    54
    Thanks
    2
    Thanked 0 Times in 0 Posts
    yeah, go figure. seems like all programming languages have these weird twirks and quirks when you get down and dirty to the core.
    anyways, yeah, so i need to read up a bit more on the basics about undefined but i found a solution which use in window to check if the variable if undefined. it works ok, except in functions. if i pass an undefined variable through a funtion's argument, the in window method that worked outside the function stops working.
    any ideas why? here is what ive coded so far
    PHP Code:

    function isPopulated(variable){

        if(
    "variable" in window) { // Checks for undefined
        
            
    if(variable != null) { // This difers from !== for some reason
                
                // Replaces all empty characters with nothing, then checks if variable has any other characters
                
    var whiteSpaceRemoved variable.replace(/s+/g'');
                if(
    whiteSpaceRemoved != ''){
                    
                    return 
    true;
                    
                } else { return 
    false; }
            } else { return 
    false; }
        } else { return 
    false; }
        

    the in window way of checking the undefined variable does not work inside the function.
    any ideas why? is it the argument variable name / 'stringed' variable name next to in that is throwing it off? how do i test the variable passed in the argument in that case?
    regards

  • #6
    New Coder
    Join Date
    Nov 2008
    Posts
    54
    Thanks
    2
    Thanked 0 Times in 0 Posts
    the above example are well and dandy. they work outside a function. my problem is inside a function. i thought i could use just if(variable) but apparently i cant do that either.

    regarding the use of typeof, in my case i am going with what mozilla developer page recommends, which is the use of in window

    link
    https://developer.mozilla.org/en-US/...ects/undefined

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    If you add "use strict"; to the top of your code then the browser will tell you if there are any undeclared 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.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,553
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    This is useless code:
    Code:
    function isPopulated(variable){
        if("variable" in window) { // Checks for undefined
    The line in red there checks if the *GLOBAL* variable named "variable" is undefined or not.

    That has NOTHING WHATSOEVER to do with whether the function argument named "variable" is defined. Function arguments are LOCAL to the function, so you can't possibly use the in window trick to check them.

    And in any case, your code for checking for content other than all white space only works if the variable is a string or can be converted to a string. It's pretty meaningless if, for example, the variable is an object that has no toString() method. I guess it still works, but you will then be testing something like (example only) [object HTMLSpanElement].

    Finally, if you *DO* call your function passing a truly undeclared and undefined variable, you will get an error ON THE CALL. You will never actually get into the function.

    What is wrong with simply:
    Code:
    function isPopulated(something)
    {
        return something != null 
               && /\S/.test( String(something) );
    }
    Though that will still say true if you do something such as:
    Code:
    <span onclick="alert(isPopulated(this));">test</span>
    Because, of course, something is then a reference to the <span> and String(something) is indeed "[object HTMLSpanElement]".
    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.

  • #9
    New Coder
    Join Date
    Nov 2008
    Posts
    54
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Code:
    function isPopulated(variable){
        if("variable" in window) { // Checks for undefined
    The line in red there checks if the *GLOBAL* variable named "variable" is undefined or not.
    but that's what i want.


    good point with passing objects. but the function is to be used only in specific contexts.


    still, regarding checking if a variable is truly undefined (undeclared), can it be done? can i check, from within a function is the variable being passed to the function is undefined in the global scope (or other scope other than the function, for that matter) ?
    Last edited by ricmetal; 08-09-2013 at 01:23 AM.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,553
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    Simply put: No.

    Read what I wrote again.

    If you call (for example) isPopulated( zamboni ) and you have NEVER EVEN DECLARED the variable zamboni (that is, you don't even have var zamboni; at global scope), then the function WILL NOT BE CALLED!

    You WILL get an error at the point of the call!

    Now, *IF* you have at least declared the variable--at least done var zamboni;, *THEN* the function I showed will work. The parameter variable (something in my code) will be undefined and so the something != null will return false (and then the regex test() will not be called).

    Minor note: The /\S/.test() call is much "cheaper" than doing the call to replace you were doing as no actual string manipulation has to take place; no new string will need to be allocated as is the case with replace().
    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:

    ricmetal (08-09-2013)

  • #11
    New Coder
    Join Date
    Nov 2008
    Posts
    54
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    If you call (for example) isPopulated( zamboni ) and you have NEVER EVEN DECLARED the variable zamboni (that is, you don't even have var zamboni; at global scope), then the function WILL NOT BE CALLED!

    You WILL get an error at the point of the call!
    that's bull****. what's wrong with allowing a function to test for undefined global variables if i can make the call on the global scope?

    anyways, thanks.

    and thanks for the test() thing. i will give a look into that. thanks

  • #12
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    You should NOT be defining global variables in the first place. ALL JavaScript variables should be defined local to your script so as to ensure that they don't clash with the same variable used for a different purpose by a different script.
    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.

  • #13
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,553
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    Quote Originally Posted by ricmetal View Post
    that's bull****. what's wrong with allowing a function to test for undefined global variables if i can make the call on the global scope?
    One more time: Your function is *NOT* testing whether or not a variable is defined at GLOBAL scope.

    If you want to test *THAT* then *DO NOT PASS THE VARIABLE* to the function:
    Code:
    function isGlobalDefined( )
    {
        return ( "zamboni" in window )
               && /\S/.test( window["zamboni"] );
    }
    If don't know *WHAT* global variable you will be testing, then pass the *NAME* of the variable in:
    Code:
    function isGlobalDefined( name )
    {
        return ( name in window )
               && /\S/.test( window[name] );
    }
    
    // invoked by
    if ( isGlobalDefined("zamboni") ) ...
    ************

    But now read what Felgall has to say: *GOOD* JavaScript code will have zero (or at most a handful as in the case of the jQuery library) global variables defined. It's bad practice, in any case, to pollute the global namespace with tons of variables.
    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,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by Old Pedant View Post
    or at most a handful as in the case of the jQuery library
    jQuery needs exactly ONE global variable - jQuery

    Code:
    jQuery.noconflict(true);
    (function($) {
    // put all your JQuery code here and use $ to reference it
    })(jQuery);
    You might need additional global variables if you use jQuery add-ons that are badly written but you don't need a second global variable to use jQuery itself - once you turn off the $ alias.
    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
    New Coder
    Join Date
    Nov 2008
    Posts
    54
    Thanks
    2
    Thanked 0 Times in 0 Posts
    okay, so i CANT pass an undefined variable to a function and have it (the function) check if it (the variable) is defined in the global scope...

    Code:
    // var something = "data";
    if ( isGlobalDefined(something) ) ...
    is there any way around this? it feels like javascript is failing short to provide us a little bit of flexibility in that matter

    regarding the global pollution - i am aware of it. thanks.
    Last edited by ricmetal; 08-09-2013 at 01:05 PM.


  •  
    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
    •