Beginner javascript help — Can you return a variable without initializing it?

hi guys. i’m not sure if this goes here but can someone help or explain this problem for me? i have tried googling it but i am not having any luck. any help would be appreciated, thanks!

“declare a variable without initializing it and return it”

I know how to declare a variable but not sure how to return it. I thought you could only return using a function.

This question is really interesting !
in JavaScript, if you declare a variable and if you don’t assign any value. the default value of that variable will be undefined. in function if you dont return any value ,that function value is also be undefined.

var a
console.log(a)
// i declare variable. but i did not assign any value so it will print undefined to console
a=2
console.log(a)
// now i assigned value 2 to a . now value of a is 2 
function a(){
var b=2
}
console.log(a())
// calling the function without returning any value. so you can see value . so function a will return default value undefined to console
   
function a(){

return 2
}
console.log(a())
// now i return 2 as the value of function a. so it will override the default value undefined . so two will be printed to console as the value of function a  

Yes. It will return undefined.


That’s how you would do it.


Correct. Functions return things. Presumably, you are supposed to be doing this inside a function.

Exploiting var is indeed how you would do this, and I think it will work with let as well, definitely not with const as those always must be initialized when declared (otherwise they wouldn’t be very const).

The bigger question is, why on earth would you? This is basically a trick question about some corner case of JavaScript, not a legitimate question for teaching programming. Using the value of an uninitialized variable is a bug; if you want to return undefined, do so explicitly.

so doing so explicitly would include using a function?

Yes, you’d use return undefined (or just return). Variables should always be defined by the time you use them, and returning them counts as using them.

so, I should be using a function to answer this question?

I don’t know the context of the question, but if they want you to return a value the presumably there is a function involved.