Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript set value inside if

Another function from Backbone.js

escape: function(attr) {
  var html;
  if (html = this._escapedAttributes[attr]) return html;
  ...

What's the advantage of doing it as above ?, not as per below?

var html = this._escapedAttributes[attr];
if( html ) return html;
like image 427
Lydon Ch Avatar asked Sep 10 '26 19:09

Lydon Ch


1 Answers

Whether this is an advantage or confusing, is pretty much up to you, your team and your coding conventions.

Another example where this might be really useful

function foo( arr, elem ) {
    while( elem = arr.shift() ) {
       console.log( elem * elem );
    }
}

where you would use it like

foo([5,4,3,2,1]);

The same thing goes for if statements. Sometimes it can make sense or is helpful to assign a value to some variable within a condition, to directly have that access within the case. Of course this might not be convinient for some folks who is not used to it, but again, if your conventions and your team agrees on stuff like this, it can be pretty neat.

Other languages offer this "feature" by default. For instance, a special variable name like $_ or -> just automatically refers the thing you took your hands on.

like image 186
jAndy Avatar answered Sep 13 '26 09:09

jAndy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!