2

As stated in the title of my question, I recently stumbled upon this variable declaration:

options = options || {};

So, as far as I understand - I am a beginner on lowest level - we have the global var options, which is assigned as...now I am lost...options or empty?

I know, this is probably an easy question, but I still don't seem to find a suitable answer. All help is very appreciated.

With regards, Julius

Julius R.
  • 57
  • 10
  • I can receive info for documentation where you find this condition (if) or code please... – Mirko Cianfarani Aug 01 '13 at 12:32
  • The source can be found in line 26 of this document: http://demo.tutorialzine.com/2011/03/custom-facebook-wall-jquery-graph/js/script.js – Julius R. Aug 01 '13 at 12:35
  • This statement (OR)s the empty object with variable itself. I think it ensures that `option` does not remain undefined after current statement (if it was undefined) or retain object's value. – Puneet Aug 01 '13 at 12:35
  • Thank you Quentin, it is a duplicate! I understand it means, if options is not set, use {}. But what is {}? Empty array? – Julius R. Aug 01 '13 at 12:38
  • It's merely one way of creating a new empty object. – Ernest Friedman-Hill Aug 01 '13 at 12:39
  • 2
    A general point to whoever is doing it: if you disagree with an answer please state why. All but one of the answers has been downvoted with no reason given. – Adrian Wragg Aug 01 '13 at 12:45

5 Answers5

2

It basically means "if there is no options object currently defined, then create an empty object to populate the variable options".

So:

if(!options){

    options = {}

}else{ 

    options = options 

}

In response to your comment:

A {} is an empty object. It's akin to new Object().

shennan
  • 10,798
  • 5
  • 44
  • 79
  • 3
    such unnecessary downvoting going on here... we don't need to split hairs over the semantics of `defined/undefined` - it's a pretty straight-forward explanation. – shennan Aug 01 '13 at 12:37
  • 1
    Thank you shennan, very simple and unarguably decent explanation – Julius R. Aug 01 '13 at 12:48
0

It's a simplyfied version of:

if ( !options ) {
    options = {};
}

Another way of writing this is:

options || (options={});

It's simple create the object options if it's not allready set to anything.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
0

It's a way of initialising an object if it hasn't already been initialised.

If options exists, then it evaluates to:

    options = options

If options is null, then it treats it as 'false' and evaluates the second parameter, so becomes:

    options = {};
Adrian Wragg
  • 7,311
  • 3
  • 26
  • 50
0

It basically says "if options exists, then use it; otherwise, set options to an empty object."

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
0

If the options object exists, define it as options. If it doesn't, create an empty object.