Mik_A Mik_A - 1 month ago 6
Javascript Question

+$ in jquery. How come not only the basic $

I have some jQuery code where

+$(...)
is used in many places. The code does not work without the
+
part, when doing just
$(...)
.

I couldn't find any explanation through Google. I'd appreciate any guidance if possible.

function calculate() {
var a = +$('#a').val(); // what is +$ ?
var b = +$('#b').val();
var c = b * 108.40;
//etc
}

Answer

+$() is actually two operations, where first $() runs to grab your input and then + coerces whatever the value of the input is into a number.

Here's a breakdown of what is happening:

var valueA = $('#a').val(); // "123"
var numberA = +valueA;      //  123

console.log('valueA is a ' + typeof valueA);   // 'valueA is a string'
console.log('numberA is a ' + typeof numberA); // 'numberA is a number'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="a" value="123"/>