Skip to content

Instantly share code, notes, and snippets.

@teffcode
Created June 4, 2020 04:49
Show Gist options
  • Select an option

  • Save teffcode/25fdf7f7ef1b89411b04c9cf4b4316aa to your computer and use it in GitHub Desktop.

Select an option

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鈥檙e 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



@nicorr-05
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