JavaScript questions #Day 1

1. What’s the output ?

function sayHi() {
console.log(name);
console.log(age);
var name = ‘Lydia’;
let age = 21;
}

sayHi();

A: Lydia and undefined
B: Lydia and ReferenceError
C: ReferenceError and 21
D: undefined and ReferenceError


This content originally appeared on DEV Community and was authored by Sooraj S

1. What's the output ?

function sayHi() {
  console.log(name);
  console.log(age);
  var name = 'Lydia';
  let age = 21;
}

sayHi();

A: Lydia and undefined
B: Lydia and ReferenceError
C: ReferenceError and 21
D: undefined and ReferenceError

Within the function, we first declare the name variable with the var keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of undefined, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the name variable, so it still holds the value of undefined.

Variables with the let keyword (and const) are hoisted, but unlike var, don't get initialized. They are not accessible before the line we declare (initialize) them. This is called the "temporal dead zone". When we try to access the variables before they are declared, JavaScript throws a ReferenceError.So answer is D.


This content originally appeared on DEV Community and was authored by Sooraj S


Print Share Comment Cite Upload Translate Updates
APA

Sooraj S | Sciencx (2021-07-13T03:57:16+00:00) JavaScript questions #Day 1. Retrieved from https://www.scien.cx/2021/07/13/javascript-questions-day-1/

MLA
" » JavaScript questions #Day 1." Sooraj S | Sciencx - Tuesday July 13, 2021, https://www.scien.cx/2021/07/13/javascript-questions-day-1/
HARVARD
Sooraj S | Sciencx Tuesday July 13, 2021 » JavaScript questions #Day 1., viewed ,<https://www.scien.cx/2021/07/13/javascript-questions-day-1/>
VANCOUVER
Sooraj S | Sciencx - » JavaScript questions #Day 1. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/07/13/javascript-questions-day-1/
CHICAGO
" » JavaScript questions #Day 1." Sooraj S | Sciencx - Accessed . https://www.scien.cx/2021/07/13/javascript-questions-day-1/
IEEE
" » JavaScript questions #Day 1." Sooraj S | Sciencx [Online]. Available: https://www.scien.cx/2021/07/13/javascript-questions-day-1/. [Accessed: ]
rf:citation
» JavaScript questions #Day 1 | Sooraj S | Sciencx | https://www.scien.cx/2021/07/13/javascript-questions-day-1/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.