Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery's $.each convert numbers to objects?

jQuery's each function executes the callback function in the context of the array's element:

$.each([3], function () {
    console.log(this === 3);
    console.log(this.valueOf() === 3);
});

I expected true true, but got false true. This indicates the array's elements get boxed by the each function.

My question has two parts:

  • What is the motivation behind boxing the number?
  • Can a new each function be written to work as I expected?
like image 388
Ryan Avatar asked Feb 16 '26 10:02

Ryan


1 Answers

My guess is that when the $.each() callback is called using .call() and the 3 is passed as the first argument so that it will be the this pointer that javascript always boxes the 3 into an object since the this pointer is always supposed to be an object.

An interesting observation by Oleg is that in strict mode, you get true and true as the output. See demo: http://jsfiddle.net/jfriend00/hjpQG/

Again, thanks to Oleg, here's a reference that describes that it's not boxed into an object in strict mode.

And, an ECMAScript reference from apsillers that contains this step: "Else if Type(thisArg) is not Object, set the ThisBinding to ToObject(thisArg)". This step happens internally in the JS engine in the process of calling a function in any way (when not in strict mode).


To work-around this in all browsers, you can either change the === to == or you can switch to using the 2nd argument passed to the callback which is the undisturbed value.

$.each([3], function (index, value) {
    // use value argument
    log(value === 3);
    log(this.valueOf() === 3);
});

$.each([3], function (index, value) {
    // double equals
    log(this == 3);
    log(this.valueOf() === 3);
});

Or, if you are only trying to support browsers that support strict mode, you can use strict mode with your original code.

like image 189
jfriend00 Avatar answered Feb 18 '26 22:02

jfriend00



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!