Thomas
Thomas

Reputation: 113

Syntax for setting a variable in javascript

(Edit: I found this syntax while reading someone else's code)

Is there any good reason for using the following syntax for setting a variable in javascript:

this.index >= this.items.length && (this.index = 0);

Is it just to get the expression on one line of code, or is there another, dare I say better, reason for this way of doing it...

Edit: The code is equivalent to:

if (this.index >= this.items.length) { 
    this.index = 0; 
}

Upvotes: 2

Views: 70

Answers (3)

MichaC
MichaC

Reputation: 13381

I think the intention of this code is

 this.index = this.index >= this.items.length ? this.items.length : 0;

or

 this.index = this.index >= this.items.length ? 0 : this.items.length;

3rd possible intention (that might be really what it should do).

 this.index = this.index >= this.items.length ? 0 : this.index;

But that's just best guess, the line doesn't make any sense at all... And you usually do not assign a variable like this. Actually it doesn't even assign the variable this.index.

Actually your code is really working. See working example here: http://jsfiddle.net/Elak/EthsP/

Never saw this syntax before tbh and I write lots of JavaScript... But you never stop learning new stuff :p

Upvotes: 1

iConnor
iConnor

Reputation: 20189

No, there isn't a good reason, i think people just do it a lot so it's a "one liner", you're better off using a if like this.

if( this.index >= this.items.length ) {
    this.index = 0;
}

Because as you can see people get confused with what it actually does.

But you can still keep it a one liner like so

if( this.index >= this.items.length ) { this.index = 0; }

Upvotes: 1

Halcyon
Halcyon

Reputation: 57709

Wow, no. Just no. I consider myself a pretty good JavaScript programmer and I can't tell you what this code does.

Does it just do this.index = this.items.length or does it do something weird like this.index = false?

If you intend:

if (this.index >= this.items.length) {
    this.index = 0;
}

Then you could consider:

this.index = (this.index >= this.items.length) ? 0 : this.index;

But that doesn't really improve it, does it?

Upvotes: 3

Related Questions