-1

When writing sound code should i be using global objects or passing locals to functions and then returning the functions local object back to the original function?

function func1(obj) {
  ..modify obj
  return obj;
}

object = func1(object)
..do something with modified object

or

var object={..};

function func1() {
  ..modifiy object
}

function func2() {
    func1();
    ..do something with modified object
}

func2();

the first seems more readable, the second seems like better practice...

3
  • 1
    The first seems like better practice, the second will suffer from side effects. I would create a constructor and set the object as property then add the methods to the prototype.
    – elclanrs
    Commented Sep 12, 2013 at 23:57
  • The first IS better practice, not just seems like it. There are situations where a global is needed (like the global JQuery object or it's alias $) but it's rare and should be very limited.
    – slebetman
    Commented Sep 13, 2013 at 0:05
  • This question is very broad and the answer depends on a multitude of circumstances. Stick a closure around both of those examples and voila, no global, but then which one is better practice? Depends on what you are trying to achieve. Commented Sep 13, 2013 at 0:10

1 Answer 1

3

JavaScript best practice is to not use global variables unless you absolutely have to. That being said it really depends on your situation. Douglas Crockford has 2 really nice articles on this subject. The first explains why they are so bad, the second provides tips for when a global variable must be used,

  1. http://yuiblog.com/blog/2006/06/01/global-domination/

  2. http://yuiblog.com/blog/2008/04/16/global-domination-part-two/

2
  • It's best practice in most languages, not just Javascript.
    – Barmar
    Commented Sep 13, 2013 at 0:11
  • @Barmar I am not very familiar with many other languages most of my experience is in JS, thank you for letting me know though :) Commented Sep 13, 2013 at 0:56

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.