0

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();
asked Oct 24, 2015 at 19:58
2
  • 2
    No difference in practice because the target value does not ever change. The function is called sooner in the first. Commented Oct 24, 2015 at 20:04
  • The first really should be simplified to MYUtils.isIOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/g);. Maybe the difference is more obvious then. Commented Oct 24, 2015 at 21:38

1 Answer 1

1

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.

answered Oct 24, 2015 at 20:04
Sign up to request clarification or add additional context in comments.

2 Comments

Some browsers allows users to change their user agent string whenever they like, so "...is not going to change..." should perhaps be "is unlikely to change". ;-)
While that is true, @RobG, I thought that only affected the next page load -- but I haven't actually tested that out. You might be right. Thanks.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.