Valentin Despa
Valentin Despa

Reputation: 42622

Javascript / jQuery + length = problem

A small version of my script would be this:

var x = null;
for(var i=0; i<x.length; i++)
{
    //do stuff
}

I noticed (by doing some 'alert' debugs) that my script halts when evaluating x.length. Even when i try to print it in an alert, the script stops.

The idea is that somethimes my x variable is an array, sometimes is null.

Of course, I am a beginner, so probably i've done something stupid. No errors appear in my Firefox 6 error console.

Thanks a lot for any ideas!

Upvotes: 1

Views: 523

Answers (7)

Shreyas
Shreyas

Reputation: 1462

Another option here would be to initialize x to an object with the length property -

x = {
      length : 0
    };

instead of

x = null;

EDIT : pulsar's answer makes more sense!

Upvotes: 0

pulsar
pulsar

Reputation: 580

Why don't you initialize x with var x = [];? This way, you can make sure that it is always an array, yet the loop won't do anything if it's empty.

Upvotes: 1

Alex Richter
Alex Richter

Reputation: 25

var x = null;

if(x !== null){
    for(var i=0; i<x.length; i++)
    {

        //do stuff
    }
}

Seems to fix the problem

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69915

In your code x is null and you are trying to get the length property from a null value which will throw a javascript error. Please check your console you will definitely see an error.

In such situations you should always make sure you do null check before accessing any property of the object or variable. Try this

var x = null;
if(x){
   for(var i=0; i<x.length; i++)
   {
      //do stuff
   }
}

Upvotes: 2

Sylvain Cleymans
Sylvain Cleymans

Reputation: 1927

You can't call the method length on a null object. So you need to test if the object is null before calling it.

var x = null;
if(x != null)
{
  for(var i=0; x!= null && i < x.length; i++)
  {
     //do stuff
  }
}

or

var x = null;
for(var i=0;x!= null && i<x.length; i++)
{
   //do stuff
}

Upvotes: 0

genesis
genesis

Reputation: 50972

That's because it's null. Add this if statement

if (x !== null){
    for(var i=0; i<x.length; i++)
    {
        //do stuff
    }
}

and it should be fine.

Upvotes: 1

Michael Sagalovich
Michael Sagalovich

Reputation: 2549

try

var x = null;
for(var i = 0; x && i < x.length; i++) {
    //do stuff
}

This will first check whether x is not null. If x is null, for will not run. If it is not null, for will run as usual.

Upvotes: 2

Related Questions