IIFE: What exactly does this code do?

Pseudo example code:

var GO = (function(go) {
	
	go = go || {};
	
	go.init = function(x) {
	
	   console.log(x);
	
	};
	
	go.hello = function(msg) {
	
	   console.log('Hello: ' + msg);
	
	};
	
	return go;
	
}(GO || {}));

GO.init('blah');

GO.hello('Billy');

Could someone explain to me what:

GO || {}

… and:

go = go || {};

… are doing? What’s the purpose of passing GO to the IIFE? Is it redundant to say “xxx || {}” in two locations?

If it is of any help, the original code can be found here.

Thanks!

The above code is an example of the OR operator, we use this in JavaScript to determine whether the variable go is defined as a argument with a value other then false, undefined or null otherwise it jumps to the or || statement in which you set your fallback as which in this case is an empty object.

Hi Chris, many thanks for the reply, I really appreciate it!!! :slight_smile:

Thanks for the note about the specific syntax. I probably should have been more clear… I actually understand what “GO || {}” does, where I’m unclear is:

What’s the point of having “GO || {}” and “go = go || {};”? Aren’t they both doing the same thing?

Correct me if I’m worng, but when GO gets called, it passes itself or an empty object to the IIFE/closure (i.e. “GO || {}”). Within the closure, the first line ends up checking if the passed in parameter is defined, if not, it assigns an empty object (i.e. “go = go || {};”)…

What I’d like to know: Can I remove one or the other in terms of checking if it’s defined?

In other words, could I just ditch the second check like so:

var GO = (function(go) {
	
	// No need to do the same thing here, right?
	
	go.init = function(x) {
	   
	   console.log(x);
	   
	};
	
	go.hello = function(msg) {
	   
	   console.log('Hello: ' + msg);
	   
	};
	
	return go;
	
}(GO || {})); // We've already determined if GO is defined, otherwise pass empty object.

I hope that clarifies my question. Please let me know if I can be more clear.

Thanks!
Micky

Anyone got any tips? :slight_smile:

I’m asking because my gut is telling me that one of those bits of logic can be nuked… But, I want to make sure I’m not overlooking something obvious (or not so obvious)… Any JS gurus out there that can shed some light on this bit of code?

Thank you!

Cheers,
Micky

I was able to find help from a user on IRC:

in that exact instance you could remove either, but removing the outer one is safer, because it’s closer to where the problem would occur if go was ever not an object

I have some info here.