Instagram | Twitter | LinkedIn
When executing the following code, What would the order of the functions look like on the Call Stack ?
Click here to see the correct answer and explanation 👀
Correct Answer | Explanation |
---|---|
C | The Call Stack is a data structure which records the function calls, basically where in the program we are. If we call a function to execute, we push something on to the stack, and when we return from a function, we pop off the top of the stack. Is important to consider that the Call Stack works based on the LIFO principle i.e., last-in-first-out. As we run this code, we first look for the main function where all the execution will start. In the above, it starts from console.log(bar(6)), which is pushed on to the stack, next frame on top of it is the function bar with it’s arguments which in turn calls function foo which is again pushed on to the top of stack. |
Explanation based on 👉🏼 Understanding Javascript Function Executions — Call Stack, Event Loop , Tasks & more | Medium and JavaScript Call Stack | JavaScript Tutorial
Code:
function foo(b) {
var a = 5
return a * b + 10
}
function bar(x) {
var y = 3
return foo(x * y)
}
console.log(bar(6))
Al ejecutar el siguiente código, ¿Cómo sería el orden de las funciones en el Call Stack?
Haz click aquí para ver la respuesta correcta y su explicación 👀
Respuesta correcta | Explicación |
---|---|
C | El Call Stack es una estructura de datos que registra las llamadas a funciones, básicamente nos dice en qué parte del programa estamos. Algo importante a tener en cuenta es que el Call Stack funciona según el principio LIFO, es decir, último en entrar, primero en salir. Cuando se ejecuta el script, el motor de JavaScript coloca el contexto de ejecución global (indicado por la función main() o global()) en el Call Stack. Este contexto de ejecución global entra en la fase de creación y pasa a la fase de ejecución. La fase de ejecución comienza desde console.log(bar(6)) que se empuja a la parte superior de la pila. Luego, se ejecuta la función bar con sus argumentos y se empuja a la parte superior de la pila (es decir, encima del console.log). Luego, la función bar llama a la función foo, que nuevamente se empuja a la parte superior de la pila (es decir, encima de la función bar). |
Explicación basada en 👉🏼 Understanding Javascript Function Executions — Call Stack, Event Loop , Tasks & more | Medium y JavaScript Call Stack | JavaScript Tutorial
Código:
function foo(b) {
var a = 5
return a * b + 10
}
function bar(x) {
var y = 3
return foo(x * y)
}
console.log(bar(6))
Excelente