Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding usage of not operator in :selected

I just came across this FIDDLE online. The JS looks like below:

$(function() {
    $('#add').click(function() {
        return !$('#select1 option:selected').appendTo('#select2');
    });
    $('#remove').click(function() {
        return !$('#select2 option:selected').appendTo('#select1');
    });
});

HTML ::

<SELECT id="select1" name="select1" size="3"><OPTION value="1">Test 1</option><OPTION value="2">Test 2</option></select> 
<SELECT id="select2" name="select2"></select>
<br><input type="button" id="add" value="Add >>"><input type="button" id="remove" value="<< Remove">

Its basically just a piece of JS interchanging a select values. But what I don't understand is the usage of the ! operator(not operator).

Now I understand that the not operator inverses the result, but in the above code what is it really doing? I am not understanding what the not operator is doing in the above fiddle and what impact it is having on the end result? Can anybody explain?

like image 434
Alexander Solonik Avatar asked Oct 02 '15 17:10

Alexander Solonik


1 Answers

It's a fancy way of doing:

$('#add').click(function() {
        $('#select1 option:selected').appendTo('#select2');
         return false;
});

the return false prevents default behavior of the button by cancelling the event.

Since an object will always be truthy, !object will be false and $(selector) returns an object

like image 178
charlietfl Avatar answered Sep 30 '22 06:09

charlietfl