6

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.

2 Answers 2

14

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
}
Sign up to request clarification or add additional context in comments.

7 Comments

first solution worked properly, but im still having trouble to achive what i want. Basicly i execute a function on the window scroll event and it should set me a variable and if this variable is set i check for it and change it to true in the "if".
@StefanHövelmanns - added something to the answer, is that what you're trying to do ?
why not var moving = moving || false ?. I'm asking, @adeneo, I'd like to find out the difference with your solution
@steo - for this example, or any that's using a boolean only, it's the same thing, but for more complicated values there's a big difference in how bitwise and logical operators work, so I used a logical ternary condition here as it equals the logical if condition, and won't cause issues if other data types are used.
That said, I often use the bitwise OR myself, but you have to know what you're working with, and wether or not it will work as planned with bitwise operators.
|
4
if( typeof moving === 'undefined' )
{
    var moving;

    moving = false;
}

Will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.