Skip to content

Instantly share code, notes, and snippets.

@teffcode
Created June 4, 2020 04:49
Show Gist options
  • Save teffcode/25fdf7f7ef1b89411b04c9cf4b4316aa to your computer and use it in GitHub Desktop.
Save teffcode/25fdf7f7ef1b89411b04c9cf4b4316aa to your computer and use it in GitHub Desktop.

👋🏼 Welcome 👋🏼

Quiz banner

Instagram | Twitter | LinkedIn


👅 Choose your language



🚀 English version


What is the output of the following code ?

  A. undefined
  B. 🎩
  C. 👒

👀 Click here to see the correct answer and explanation

Correct Answer:

A. undefined

Explanation:

var variables are "function scope". What does this mean? It means they are only available inside the function they’re created in. In this case, the variable declaration (var hat) whose scope is the function Accessory(), is hoisted to the top of the function.

This is how the interpreter views the above code:

var hat = "🎩";

function Accessory() {
  var hat;
  console.log(hat);
  hat = "👒";
}

Accessory();

Because of this, we can use variables before we declare them. However, we have to be careful because the hoisted variable is initialised with a value of undefined. The best option would be to declare and initialise our variable before use.


Explanation based on 👉🏼 Hoisting & Understanding Hoisting in JavaScript



🚀 Spanish version


¿ Qué imprime el siguiente código ?

  A. undefined
  B. 🎩
  C. 👒

👀 Haz click aquí para ver la respuesta correcta y su explicación

Correct Answer:

A. undefined

Explanation:

Las variables var son "function scope". ¿Qué significa esto? Significa que solo están disponibles dentro de la función en la que se crean. En este ejemplo, la declaración de variable (var hat) cuyo alcance es la función Accessory(), se eleva a la parte superior de la función.

Así es como el intérprete ve el código anterior:

var hat = "🎩";

function Accessory() {
  var hat;
  console.log(hat);
  hat = "👒";
}

Accessory();

Debido a esto, podemos usar variables antes de declararlas. Sin embargo, debemos tener cuidado porque la variable elevada se inicializa con un valor de undefined. La mejor opción sería declarar e inicializar nuestra variable antes de usarla.


Explicación basada en 👉🏼 Hoisting & The Difference Between Function and Block Scope in JavaScript



@Nrestrepo05
Copy link

Hey, Teff. Está genial!!

noté que escribiste initialised, creo que quisiste escribir initialized. No es nada importante, pero no quiero que te critiquen por ello...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment