0

What does the following code means in javascript

config = config || {}

2 Answers2

3
config = config || {}

Basically it is trying to initialize the config to an empty object {} if it hasn't already been initialized or initialized to one of the following values

  • undefined
  • null
  • ""
  • false
  • 0

if the config is undefined, null, "", false or 0, it will get a new value as {}

For example, following will be the scenarios where the first

var config = undefined; config =  config || {}; //output Object {}
var config = null; config =  config || {};//output Object {}
var config = 0; config =  config || {}; //output Object {}
var config = false; config =  config || {}; //output Object {}
var config = ""; config =  config || {}; //output Object {}

So, the OR condition is executed as if the Boolean(config) it false (it will be false if it is one of these values (undefined , null, "", false, 0 ) then it will execute the next statement {} and assign that value to config.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Or `if it hasn't already been initialized or It is initialized as falsey value...` I guess you need to edit... – Rayon Mar 10 '16 at 10:32
  • @RayonDabre thanks, made the edit – gurvinder372 Mar 10 '16 at 10:34
  • I downvoted because this question has been answered 100 times before. And when you keep answering duplicates like this all the information will be spread out over 100+ questions making finding all the information harder. – PeeHaa Mar 10 '16 at 10:49
  • @PeeHaa sure, fair enough. I will go through the original question and remove my answer if info I have given is already given in the original link. – gurvinder372 Mar 10 '16 at 10:50
1
var config = config || {} 

meaning that if config is false (config is null or "" or nan or undefined ) set variable as empty object if else set it as config

var config = config && {} 

meaning that if config is false (config is null or "" or nan or undefined ) set variable as config object if else set it as empty object

Bishoy Bisahi
  • 377
  • 1
  • 11