My Coding Quiz #45 馃懆鈥嶐煉火煕狅笍馃З
Welcome to the new installment of my series of Coding Quizzes, in which you will be able to test your knowledge and skills about programming and software development in a simple and fun way. If you want to learn more about it visit my blog here on Hive and the first post where I introduced it.
Without further ado, here's the riddle...

By @eniolw
What's your choice?
Solution to the previous quiz: {}. This script basically consists of two lines. To define r
we used the grouping operator or parenthesis to extend over several lines, because unlike Python, we don't have a line-skipping character in Javascript. But maybe if we rewrite this as const r = !! true && {} || [] && false
it will be more readable. Is it though? You tell me.
Now, let's get the truth value associated with each operand, be it truthy or falsy:
true
is obviously truthy, but writting!! true
is a tautology. We could use that operator to get the boolean value of an expression, but applying it totrue
is redundant.{}
is a truthy value. We have already discussed that unlike in Python, an empty object in Javascript does not evaluate to falsy.[]
is also truthy for the same reason.false
is obviously a falsy value.
We see that the crux of the matter then is the order of priority of the logical operators !
, &&
and ||
. If you know about programming languages, you should know that conjunction (&&
) has a higher priority than disjunction (||
), but negation (!
) has an even higher priority. In other words, Javascript interprets the whole expression like this: ((!! true) && {}) || ([] && false)
. Of course, for Javascript, parentheses are unnecessary, but using them helps get the point across.
So, first the double negation is resolved, followed by the first conjunction: true && {}
. This results in {}, since the &&
operator returns the last truthy operand if they are all truthy.
Then, Javascript understands that the second operand of the ||
, that is, the expression ([] && false)
is unnecessary to evaluate, since the first operand is already a truthy value. This is something very basic in logic and programming languages, where it is known as short-circuiting and it helps to optimise the code.
The output is therefore {}.
Although the code looks very simple, I didn't imagine it would take me so long to explain these concepts.
If you want to blog about computer science and programming content, I invite you to join Hive and participate in its communities, such as STEM-social, Develop Spanish, Programming & Dev and others.
Mi Quiz de Programaci贸n #45 馃懆鈥嶐煉火煕狅笍馃З
Bienvenido a mi nueva serie de Quizzes de Programaci贸n, en la cual podr谩s poner a prueba tus conocimientos y habilidades sobre programaci贸n y desarrollo de software de una manera sencilla y divertida. Si quieres aprender m谩s sobre ella visita mi blog aqu铆 en Hive y el primer post donde la present茅.
Sin m谩s pre谩mbulos, he aqu铆 el acertijo...

Por @eniolw
驴Cu谩l es tu elecci贸n?
Soluci贸n al quiz anterior: {}. Este script consta b谩sicamente de dos l铆neas. Para definir r
usamos el operador de agrupaci贸n o par茅ntesis para extenderlo a varias l铆neas, porque a diferencia de Python, no tenemos un car谩cter de salto de l铆nea en Javascript. Pero tal vez si reescribimos esto como const r = !! true && {} || [] && false
ser谩 m谩s legible. Pero, 驴lo es? T煤 d铆melo.
Ahora, obtengamos el valor de verdad asociado con cada operando, ya sea verdadero o falso:
!! true
es obviamente veraz (truthy), pero decir!! true
es una tautolog铆a. Podr铆amos usar ese operador para obtener el valor booleano de una expresi贸n, pero aplicarlo atrue
es redundante.{}
es un valor veraz (truthy). Ya hemos comentado que, a diferencia de Python, un objeto vac铆o en Javascript no se eval煤a como falso (falsy).[]
tambi茅n es veraz (truthy) por la misma raz贸n.false
es obviamente un valor falso (falsy).
Vemos que el meollo de la cuesti贸n entonces es el orden de prioridad de los operadores l贸gicos !
, &&
y ||
. Si conoces de lenguajes de programaci贸n, debes saber que la conjunci贸n (&&
) tiene mayor prioridad que la disyunci贸n (||
), pero la negaci贸n (!
) tiene una prioridad a煤n mayor. En otras palabras, Javascript interpreta la expresi贸n completa as铆: ((!! true) && {}) || ([] && false)
. Por supuesto, para Javascript, los par茅ntesis son innecesarios, pero usarlos ayuda a entender el punto mejor.
Entonces, primero se resuelve la doble negaci贸n, seguida de la primera conjunci贸n: true && {}
. Esto da como resultado {}, ya que el operador &&
devuelve el 煤ltimo operando verdadero si todos son veraces (truthy).
Entonces Javascript entiende que el segundo operando del ||
, es decir, la expresi贸n ([] && false)
es innecesaria de evaluar, ya que el primer operando ya es un valor veraz (truthy). Esto es algo muy b谩sico en l贸gica y lenguajes de programaci贸n, donde se le conoce como cortocircuito y ayuda a optimizar el c贸digo.
Por lo tanto, la salida es {}.
Aunque el c贸digo parece muy simple, no imagin茅 que me tomar铆a tanto tiempo explicar estos conceptos.
Si quieres bloguear sobre contenido inform谩tico y de programaci贸n, te invito a unirte a Hive y participar en sus comunidades, tales como STEM-social, Develop Spanish, Programming & Dev y otras.