Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the code " length === +length" mean in JavaScript? [duplicate]

Tags:

javascript

I just read the underscope source code, and cannot get the point from this code:

_.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return obj;
    iterator = createCallback(iterator, context);
    var i, length = obj.length;
    if (length === +length) {   // why +length?
        for (i = 0; i < length; i++) {
            iterator(obj[i], i, obj);
        }
    } else {
        var keys = _.keys(obj);
        for (i = 0, length = keys.length; i < length; i++) {
            iterator(obj[keys[i]], keys[i], obj);
        }
    }
    return obj;
};

why length===+length ? I guess this used for force to convert if length is not a number? Could somebody give me a hand?

like image 583
Tyler.z.yang Avatar asked Jul 24 '14 07:07

Tyler.z.yang


People also ask

What does length mean in JavaScript?

length is a property of arrays in JavaScript that returns or sets the number of elements in a given array.

Is length a method or property in JavaScript?

length is a property of array, not a method if it was a method getting the length of an array would be of O(n), but by keeping it as a property its O(1).

What does function length return in JavaScript?

A Function object's length property indicates how many arguments the function expects, i.e. the number of formal parameters. This number excludes the rest parameter and only includes parameters before the first one with a default value.

Why array length is not a function?

Though arrays are objects in Java but length is an instance variable (data item) in the array object and not a method. So, we cannot use the length() method to know the array length.


2 Answers

+length is a method to convert anything to a number.

If it's a number, the value doesn't change, and the comparison returns true. If it's not a number, the assertion is false.

What is unary + used for in Javascript?

like image 154
StingRay21 Avatar answered Oct 19 '22 22:10

StingRay21


+length converts any value of length to a number (NaN if not possible).

So length===+length just tests that length is really a number (not a string that could be converted to a number), and that it's not NaN (which isn't equal to itself).

like image 27
Denys Séguret Avatar answered Oct 19 '22 20:10

Denys Séguret