1

I'm just wondering why should I use this method to return a function :

clusters.prototype.get_local_storage_data = function(data_key) {
    return +(this.localStorage.getItem(data_key) || 1);
};

What does the +() do there and why using that ? Is there a better way of returning the function or 1 if what the function gets is null ?

3 Answers 3

4

Using the + before a value forces that value to become a number. In the case above, the data key will be converted to a number (if it's found), or the number 1 will be returned. Either way, the result will be converted to a number.

+null;   // 0
+"3.14"; // 3.14
+1;      // 1

It's just ensuring that no matter what the output is, you will be returning a number.

Sign up to request clarification or add additional context in comments.

4 Comments

I see now, it comes in handy in my case, because the returned value is in fact a number, and will always be a number, at least that is what I expect it to be.
@Roland: getItem returns a string: dev.w3.org/html5/webstorage/#storage-0
I know that, but what I store is a number, so after I get it, using JSON.parse() it is the same thing I stored. It might as well be an object or an array, because I'm using JSON.stringfy(). Or am I wrong ?
@Roland If you're using JSON.parse() on the returned string, you will also end up with a number.
0

The + is there to cast the result to a number -

typeof +"123" // "number"

The way it's implemented looks just fine, and doesn't need to be changed.

Comments

0

The + is just making sure the return value is a number or else 1 would be true and not the number one. It's a shortcut for:

Number( expression )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.