How to check if a variable exists in jQuery?

exists, jquery, variables

Solution

Did you try

if (typeof moving == 'undefined') var moving = false;

In some cases I use

var moving = typeof moving == 'undefined' ? false : moving;

which is basically the same, but for me it's more readable in some cases to see that the variable is set, either to it's original value, or `false` if it's undeclared, but the first version is more common.

EDIT:

Here's how to detect scroll

var scrolled = false;

$(window).on('scroll', function() {
    scrolled = true;
});

//later

if (scrolled) {
    // do stuff
}

Problem

Is there a way to create a variable in jQuery / JavaScript if it not exists? I've tried: ``` if (moving.length<0) { moving=false; } if (moving=='undefined') { moving=false; } ``` But logically it all failes because the initial check on the variable is already undefined. Hope you guys can help :) EDIT First answer worked properly but my problems with this continue. ``` $.fn.animation = function() { if (typeof moving == 'undefined') {var moving = false;}; if(moving===false){ var moving=true; console.log('test'); }; }; $(window).scroll(function(){ if($(window).scrollTop() < scrollpos){ elm.animation(); } scrollpos=$(window).scrollTop(); }); ``` In this setup 'test' gets constantly logged even if I log moving which is set to true the if still gets ignored. So what I want to archive is that every time I scroll the element get checked if its already animated. If so, don't do the animation. Basically a queue.

Original source