Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a single equals in an if. Javascript. Any good reason?

jQuery.each(player, function(key, val){                     
     if (el = $("#pr_attr_plain_"+key)){
          el.text(val === "" ? 0 : " " + val);
     }
});

I inherited a project and I came across something strange. The guy who started the project is an expereinced programmer, definitely more so then myself. Is there any value or reason (no matter how bad) in doing this:

if (el = $("#pr_attr_plain_"+key))

It works now and it's in a portion of the code that I don't have to touch. I don't want to change it and have it produce unexpected consequences without knowing what it might do.

like image 897
JoeM05 Avatar asked Sep 24 '10 21:09

JoeM05


People also ask

What does a single equals symbol in JavaScript indicate?

Single Equal (=) in JavaScript We use Single Equal sign to assign value to the variable or to initialize an object. For example. var t = new Date(); //Variable assignment var amount = 100; //Object initialization var t = new Date();

Can you use an equal sign in an if statement?

Two equals signs placed together ask if two values are equal to each other. For example, the statement (A == B) is true when a is equal to b. An exclamation point and an equals sign placed together determine if two values are not equal to each other.

What is three equal signs in JavaScript?

Triple equal sign in javascript means equality without type coercion. For example: 1=="1" // true, automatic type coersion 1==="1" // false, not the same type.

What does == mean in JavaScript?

The equality operator ( == ) checks whether its two operands are equal, returning a Boolean result. Unlike the strict equality operator, it attempts to convert and compare operands that are of different types.


2 Answers

It can be correct. The code is equivalent to:

jQuery.each(player, function(key, val){                     
     el = $("#pr_attr_plain_"+key);
     if (el){
          el.text(val === "" ? 0 : " " + val);
     }
});
like image 91
LatinSuD Avatar answered Oct 20 '22 09:10

LatinSuD


If the el = $("#pr_attr_plain_"+key) evaluates to 0 or false or null or undefined, it won't go inside the if-block. In all other cases it will.

like image 32
Aishwar Avatar answered Oct 20 '22 09:10

Aishwar