My Coding Quiz #26

in #hive-19638711 months ago

My Coding Quiz #26 👨‍💻🛠️🧩

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: string. First, two constant variables a and b are created whose values, although they represent digits, are actually of type string, since they are literals in quotation marks; nothing surprising.

Line 2 creates a new constant variable c (yes, it sounds strange to talk about "constant variables", but that's what they are). This is the striking part of the quiz that reveals another of Javascript's quirks. Let's take a closer look at what happens on this line:

const c = a +-+- b


We have a series of + and - operators and this does not cause an exception. Rather, it is valid code that concatenates characters and makes conversions as required.

The expression begins to evaluate from left to right. When you say a + ... where a is of type string, what will ultimately happen is a concatenation of strings. So we already know in advance the data type of c.

However, what else is going on there? Well, the -+- b part is something that applies to the second operand entirely, that is, to b. Its value is '7.0'. The last operator - will convert it to the negative number -7, where the floating part is ignored, as it is unnecessary. Then the + operator simply acts as a bridge for the first - operator to change the sign of the number, resulting in 7. This bridge is not optional, as Javascript will generate a syntax error if we write const c = a +-- b.

We then have '9' + '7' which is '97', the value assigned to c.

Line 3 obtains the data type of c using the typeof operator and we already know that the result is 'string'.

At the end of the day, this code might not be very useful, but it is not invalid syntax and would not be suspicious to the interpreter, so we should definitely know how Javascript works. Additionally, it generates observable effects, so I speculate that it could be useful for writing hacks, obfuscations, etc.


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

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: string. Primero se crean dos variables constantes a y b cuyos valores, aunque representan dígitos, son realmente de tipo strings, pues son literales entre comillas; nada sorprendente.

La línea 2 crea una nueva variable constante c (sí, suena raro hablar de "variables constantes", pero eso es lo que son). Esta es la parte llamativa del quiz que revela otra de las peculiaridades de Javascript. Miremos más de cerca qué ocurre en esta línea:

const c = a +-+- b


Tenemos una serie de operadores + y - y ello no provoca excepción. Más bien es código válido que lo que hace es concatenar caracteres y hacer conversiones según se requiera.

La expresión comienza a evaluarse de izquierda a derecha. Cuando se dice a + ... donde a es de tipo string, lo que ocurrirá ultimadamente es una concatenación de strings. De modo que ya sabemos de antemano el tipo de dato de c.

Sin embargo, ¿qué más ocurre allí? Pues bien, la parte -+- b es algo que aplica al segundo operando por completo, es decir, a b. Su valor es '7.0'. El último operador - lo convertirá en el número negativo -7, donde la parte flotante se desprecia, pues es innecesaria. Luego el operador + simplemente hace de puente para que el primer operador - cambie el signo del número, resultando en 7. Este puente no es opcional, pues Javascript generará un error de sintaxis si escribimos const c = a +-- b.

Tenemos entonces '9' + '7' que es '97', el valor asignado a c.

La línea 3 obtiene el tipo de dato de c usando el operador typeof y ya sabemos que el resultado es 'string'.

Al final del día, este código podría resultar poco útil, pero no es una sintaxis inválida y no sería sospechosa para el intérprete, por lo que definitivamente debemos conocer cómo funciona Javascript. Además, genera efectos observables, por lo que especulo con que podría ser útil para escribir hacks, ofuscaciones, etc.


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.

Sort:  

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

se muy poco de php y hace un tiempo no lo uso, pero le ?? es un operador que funcional prácticamente igual en casi todos los lenguajes preguntando si el valor es null otorga el que se da por defecto. Creo que sera int 3 supongo que porque no esta el ; en var1

Se que otros lenguajes tienen sus versiones de ?? de PHP, pero todos no son exactamente iguales a este. De allí que pueda sorprender a algunos al verlo por primera vez. Gracias por participar, conoceremos la solución en la próxima edición.