<!-- HTML -->
<div id="target"></div>
// JavaScript
function MyObject() {}
var $my_div = $('#target'),
data;
$my_div.data('extra', (data = new MyObject()));
In JavaScript, the expression e.g. (data = new MyObject()) evaluates to MyObject object; whereas, in a language like C, the value of an expression is always true.
In the code snippet above, is (data = new MyObject()) only meant for a shortcut of doing exactly the same thing as the following?
...
var $my_div = $('#target'),
data = new MyObject();
$my_div.data('extra', data);
Clarifications:
I initially wasn’t sure what (data = new MyObject()) actually does. I was wondering why not separating that expression in its own line, rather than doing it in .data(). The question was whether there were any differences between doing that expression in .data() or separately.
The assignment operator in most languages actually evalutes to the value of assignment (=just like in JavaScript). For instance, it is common to see something like the below in C code:
It is just a matter of how a particular language interprets something (e.g. If it treats non-NULL pointer as true). Some (like C# or Java) do not and require you to be specific, like:
However, it doesn’t seem as readable, so few people go with it.
As for your question, the examples do the same – no hidden magic found 🙂