The ||
operator is the logical function known as OR .
This function receives 2 parameters, and its operation can be described as; return false
if both parameters are false
. Otherwise, return true
. Therefore in JavaScript:
false || false ==> false
false || true ==> true
true || true ==> true
true || false ==> true
If you look carefully, the implementation of the operator ||
, can be simplified a bit: return true
if the first parameter is true
. Otherwise, return the second parameter. And this is really what JavaScript does. Proving:
true || 3 ==> true
false || 3 ==> 3
Now, I do not know if you heard about the falsy JavaScript values. These values falsy , are all those values that JavaScript considers as if they were false
. And you can test these values using the operator ||
. For example:
null || 5 ==> 5
undefined || 5 ==> 5
0 || 5 ==> 5
NaN || 5 ==> 5
'' || 5 ==> 5
"" || 5 ==> 5
Now .. What happens to your expression?
a || (a = "Algún valor")
The variable a
, is previously declared (In the definition: function(a)
). Therefore, it is not considered as an error.
However, a
does not contain a previous value, or rather, contains the default value: undefined
.
Now summarizing everything, when you execute:
a || (a = "Algún valor")
If a
was declared but has no value, it is interpreted as:
undefined || (acción) ==> Ejecuta la acción, que asigna un valor a la variable a.
If a
has a previous value, other than one falsy , it is interpreted as:
true || (accion) ==> Como el primer parámetro es true, no ejecuta la acción.
Remember that the operation ||
at the end returns true
or false
. But the result is discarded since you are not using it in any way.
As for your other doubt: Why does it only work with parentheses?
a || (a = 2) // Funciona
a || a = 2 // No funciona
This has to do with how JavaScript can interpret that code.
In the second case, it does not work because you can not know what the second parameter is for the operator ||
. The second parameter can be a
. But it can also be a = 2
which is what you wanted.
While in the first case it is clearly defined in parentheses which is the second parameter.
Finally:
(function(a){
a || (a = "Default value");
})();
That's just a big code block. A part of it, is the body of the function, which we already saw is the function OR . Now you can see that filthy like:
(function(){
// ... Cuerpo de la función anónima
})();
If you clean a little more:
let funcion = function(){..};
(funcion)();
It is clearer to see that it is the declaration of an anonymous function. And as soon as you finish declaring, it is executed by calling the parentheses ()
.
Interestingly, this has a name: Immediately Invoked Function Expression (Function invoked immediately) commonly abbreviated as IIFE .
That is in summary what was explained. A function that is invoked immediately after its declaration.