My Coding Quiz #45

in voilk •  5 months ago

    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...




    Quiz
    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:

    1. 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 to true is redundant.
    2. {} is a truthy value. We have already discussed that unlike in Python, an empty object in Javascript does not evaluate to falsy.
    3. [] is also truthy for the same reason.
    4. 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...




    Quiz
    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:

    1. !! 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 a true es redundante.
    2. {} 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).
    3. [] también es veraz (truthy) por la misma razón.
    4. 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.

      Authors get paid when people like you upvote their post.
      If you enjoyed what you read here, create your account today and start earning FREE VOILK!