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