-2

Consider this code:

function x(){
    console.log(y);
}
x();
var t = x();
console.log(t);

This will throw an error. But if you comment the first console.log inside the function, it will work and print undefined.

What is the explanation of this behavior.

Thank you.

admdev
  • 448
  • 2
  • 9
  • the console.log inside function x tries to print out something not existing, but the console.log(t) prints out the functions return, which is undefined (not return) – inubs Jan 05 '18 at 11:45
  • https://fiddle.jshell.net/tpLtyofe/ – Roy Bogado Jan 05 '18 at 11:45
  • 1
    You need to read a little bit about javascript variables, functions and scopes :) – Tareq Jan 05 '18 at 11:46
  • The error that happens should tell you exactly why `Uncaught ReferenceError: y is not defined` you could have easily seen that and even searched for what that means. This question shows no research effort. – Nope Jan 05 '18 at 11:49
  • @Tareq I'm currently reading speakingjs online. It's a good book but not always as clear as I wish. If you have better resource on the subject in javascript please provide me. – admdev Jan 05 '18 at 12:34
  • @admdev there is some interactive tutorials. take a look here https://www.webpagefx.com/blog/web-design/interactive-javascript-tutorials/ – Tareq Jan 05 '18 at 12:36

1 Answers1

2

var t declares a variable. It (t) exists but it has the undefined value. When you read it, you get the undefined value (which x() returns because there is no return statement in that function).

y isn't declared anywhere. When you try to read it, you get a ReferenceError. (This aborts further processing so the result of the script doesn't run and the console.log(t) statement is never reached).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335