What does the following code means in javascript
config = config || {}
What does the following code means in javascript
config = config || {}
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
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
.
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