My Coding Quiz #49

in voilk •  5 months ago

    My Coding Quiz #49 👨‍💻🛠️🧩

    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: [ 'success', undefined ]. The key to this quiz is in the instructions of the main program, that is, the fourth line. We have here: console.log([test(), b]).

    The value returned by the function test is 'success', because the variable a inside test has no value, or rather, is undefined. Since in the code, that variable was declared with var and within the main program, it will be considered a global variable, which makes it accessible from test.

    However, the matter does not end there. Even though variable a was declared after it was used, it is still valid code, because var makes the scope of its declared variables the whole code block where it was applied. So, since var was applied at the main level of the program here, the variable a is global. Another way to understand this is that Javascript moves declarations with var to the first line of the code block, making them accessible before or after they are used.

    On other hand, the reason why b is undefined when making the console.log is because although var makes the variable recognisable before it is declared, the same is not true for its value. The variable b took the value 1 only after it was used by console.log, so it was undefined at that point.

    These are some of the quirks, features or flaws of the var statement in Javascript, which is why we should avoid it. If we had used let instead, a ReferenceError exception would have been thrown, which would make the debugging and bug-prevention process easier.


    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 #49 👨‍💻🛠️🧩

    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: [ 'success', undefined ]. La clave de este quiz está en las instrucciones del programa principal, es decir, la cuarta línea. Tenemos aquí: console.log([test(), b]).

    El valor devuelto por la función test es 'success', porque la variable a dentro de test no tiene valor, o mejor dicho, es undefined. Dado que en el código esa variable fue declarada con var y dentro del programa principal, será considerada una variable global, lo que la hace accesible desde test.

    Sin embargo, el asunto no termina ahí. Aunque la variable a se declaró después de su uso, sigue siendo código válido, porque var hace que el alcance de sus variables declaradas sea el bloque de código completo donde se aplicó. Entonces, dado que var se aplicó aquí en el nivel principal del programa, la variable a es global. Otra forma de entender esto es que Javascript mueve las declaraciones con var a la primera línea del bloque de código, haciéndolas accesibles antes o después de su uso.

    Por otro lado, la razón por la cual b es undefined al hacer console.log es porque aunque var hace que la variable sea reconocible antes de ser declarada, no ocurre lo mismo con su valor. La variable b tomó el valor 1 solo después de que fuera utilizada por console.log, por lo que era undefined en ese punto.

    Estas son algunas de las peculiaridades, características o defectos de la declaración var en Javascript, por lo que debemos evitarla. Si hubiéramos usado let en su lugar, se habría generado una excepción ReferenceError, lo que facilitaría el proceso de depuración y prevención de errores.


    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!