Toniq
Toniq

Reputation: 4996

Function call difference in javascript

What is the difference between these two and why would you use one over another?

MYUtils.isIOS = (function(){
    return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
}());

var ios = MYUtils.isIOS;

vs

MYUtils.isIOS = function(){
    return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
};

var ios = MYUtils.isIOS();

Upvotes: 0

Views: 24

Answers (1)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

In this example, there is no strong reason to use one over the other.

The first example runs, and sets the value. The value, from that point on, does not change.

In the second example, every time you call isIOS(), you are running the inner function. navigator.userAgent is not going to change at some point during your page life, so the result won't change.

However, should you be looking for some value that can change, perhaps checking if a certain HTML checkbox is set, or looking for a value set in localStorage then the second way is better, because you allow for a changing environment.

Upvotes: 1

Related Questions