Is this a variable definition or declaration? And why?
var x;
..and is the memory reserved for x after this statement?
EDIT: In C extern int x;
is a declaration, int x = 5;
is a definition. What's the analog in JS? Wikipedia says a declaration allocates memory and the definition assigns a value to this allocated memory.
SECOND EDIT: I think the explanation of @Deryck sounds great, but there's some output that disagrees with his explanation:
> var x; undefined > x undefined // now it looks like x is defined to the value undefined > y ReferenceError: y is not defined
If the ReferenceError
output would say y is not declared
it would make sense. But often I read that JS has two non-values: null
and undefined
. So var x
would be a definition with the value undefined
.
Wikipedia says a declaration allocates memory and the definition assigns a value to this allocated memory.
Declaration means that variable is only declared and memory is allocated, but no value is set. However, definition means the variables has been initialized. The same works for variables, arrays, collections, etc.
The function declaration (function statement) defines a function with the specified parameters. You can also define functions using the Function constructor and a function expression.
Function declaration is a prototype that specifies the function name, return types and parameters without the function body. Function Definition, on the other hand, refers to the actual function that specifies the function name, return types and parameters with the function body.
var x
is a declaration because you are not defining what value it holds but you are declaring its existence and the need for memory allocation.
var x = 1
is both declaration and definition but are separated with x
being declared in the beginning while its definition comes at the line specified (variable assignments happen inline).
I see that you already understand the concept of hoisting
but for those that don't, Javascript takes every variable and function declaration and brings it to the top (of its corresponding scope) then trickles down assigning them in order.
You seem to know most of this already though. Here's a great resource if you want some advanced, in-depth exploration. Yet I have a feeling you've been there before.
PS - your analogy between C variable dec/def and JS was spot on. What you read on Wikipedia was correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With