Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to determine if variable is undefined [duplicate]

in another question on SO, I was determining how to toggle off a function, and the working solution is this:

I place var disabledFlag = true; in the head section of my page and before calling shell.js, then in shell.js I have:

/*******************************/
/*  TOGGLE BUTTON
/*******************************/
var toggleBlock = function() {
    console.log(disabledFlag);
    if(!disabledFlag){
      var windowsize = $(window).width(),
      isDesktop = windowsize > 765;
      $("#quicksearch").toggleClass("collapse in", isDesktop);
      $("#quicksearch").toggleClass("collapse out", !isDesktop);
      $("#sidebar").toggleClass("collapse in", isDesktop);
      $("#sidebar").toggleClass("collapse out", !isDesktop);
    }
    else {
      $("#quicksearch").addClass("collapse out");
      $("#sidebar").addClass("collapse out");  
    }
}
$(document).ready(toggleBlock);
$(window).on("resize.showContent", toggleBlock);
toggleBlock();

shell.js is an common file that is shared with other sites and may not have the variable defined. how do I check if the variable is defined, and if not assign it to false and then execute the code above?

like image 478
TEN Design Avatar asked Feb 16 '14 00:02

TEN Design


3 Answers

try

if (typeof disabledFlag === 'undefined')
    disabledFlag = false;
like image 141
Dwza Avatar answered Sep 20 '22 00:09

Dwza


There are easier ways to do it than using ternaries or if else statements.

As far as your specific function goes, you could do something like this:

var toggleBlock = function() {
    var disabledFlag = disabledFlag||false;

    if(!disabledFlag){
    //etc.

undefined is falsy, so it works with the logical || operator. That || operator makes the new var disabledFlag be set to disabledFlag (if it exists), and if not, it will set the var to false

This same concept is used in many different contexts. For example:

Situation 1 -

var obj = {hello: 'world'};

function fn(object) {
    var object = object || {foo: 'bar'};

    return object;
}

fn(obj)  //  ==> {hello: 'world'}

Situation 2 -

function fn(object) {
    var object = object || {foo: 'bar'};

    return object;
}

fn(objectThatDoesntExist); //  ==> {foo: 'bar'}

In JavaScript libraries and module-pattern projects, this concept is used quite frequently in many different ways.

like image 43
Josh Beam Avatar answered Sep 18 '22 00:09

Josh Beam


You don't need typeof

if (window.disabledFlag === undefined) window.disabledFlag = false;
like image 37
citizenslave Avatar answered Sep 20 '22 00:09

citizenslave