27

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.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
cakl
  • 390
  • 1
  • 3
  • 13
  • 3
    what are the important distinctions for you between the words "definition" and "declaration"? – Pointy Dec 29 '13 at 04:13
  • ES5 talks about `var` *declaring* variables: http://es5.github.io/#x12.2 – mu is too short Dec 29 '13 at 04:15
  • The concept of "memory" in JavaScript is much more abstract than it is in some other languages, like C and C++. – Pointy Dec 29 '13 at 04:17
  • thanks @Pointy so does this statement reserve memory or not? – cakl Dec 29 '13 at 04:23
  • 2
    @cakl well in JavaScript it's not really defined behavior. It declares a symbol in the local scope. Whether there's memory allocated or not is up to the runtime system. – Pointy Dec 29 '13 at 04:24
  • @cakl Why are you worried about memory allocation? In JavaScript memory is dynamically allocated and automatically garbage collected. There are no pointers, malloc, etc in JavaScript. – sbking Dec 29 '13 at 04:26
  • @Cuberto I'm not worried about this. I just wanted to know if you can make a clear difference between declaration and definition in javascript as you can do this in c/c++. – cakl Dec 29 '13 at 04:32

9 Answers9

27

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.

Javascript Garden

PS - your analogy between C variable dec/def and JS was spot on. What you read on Wikipedia was correct.

Deryck
  • 7,608
  • 2
  • 24
  • 43
  • How is it correct? What are the JavaScript semantics for plain `var x;` that are comparable to C or C++? – Pointy Dec 29 '13 at 04:25
  • The keyword in that statement was 'analogy' meaning they aren't exact matches. What I said was `correct` is this: `Wikipedia says a declaration allocates memory and the definition assigns a value to this allocated memory.` – Deryck Dec 29 '13 at 04:27
  • 3
    Well my point is that in JavaScript, whether a `var` declaration actually allocates any memory is up to the runtime and pretty much completely transparent. It's similar to C, but significantly different too. – Pointy Dec 29 '13 at 04:30
  • 1
    Oh ok I gotcha. Thanks sorry I've been up a really long time lol – Deryck Dec 29 '13 at 04:35
14

Declaring a variable is like telling the (javascript) compiler that this token x is something I want to use later. It does point to a location in memory, but it does not yet contain a value. ie. it is undefined

var x;

defining it means to give it a value which you can either do it like:

x = 10; // defining a variable that was declared previously

or like this:

var y = 20; // declaring and defining a variable altogether.

http://msdn.microsoft.com/en-us/library/67defydd(v=vs.94).aspx http://www.w3schools.com/js/js_variables.asp

hamid
  • 1,828
  • 1
  • 13
  • 17
  • I guess the location of the object in memory couldn't be retrieved using javascript, (It's C/C++), or at least it would be engine dependent. The size of the object is irrelevant. You are not defining an object, you are declaring one. It only occupies memory when you assign a value to it. Then it is object dependent, ie. is it a number, string or Object. – hamid Dec 29 '13 at 07:01
2

I will give you a long answer for better explanation.

When the javascript engine is not able to find a particular variable in memory, it will throw an error. To be more specific, when the javascript engine (Execution Context) is not able to "reference" a variable in memory, it will throw a ReferenceError. This is not exactly the same as a Declaration Error, at least in javascript.

There is a deference between a not defined error and the value undefined.

So doing

var a = undefined;

and

var a;

will both log the same result i.e. undefined. This is because, when you simply do a var a; the javascript engine allocates memory for the variable and automatically sets it's value to undefined, which is different from saying that a doesn't exist at all - in which case it will throw a ReferenceError.

Hoisting

console.log(a);    // undefined
var a = 'something';

will log undefined because, the javascript engine knows there's a variable declared somewhere in the code - which means to say that the javascript engine actually does something before it executes the code - one of the thing it does is hoists variables. To put it simply, the above code is the same as

var a;             // hoisted (declared and defined the value `undefined`)
console.log(a);    // undefined
a = 'something'    // update the defined value to `something`

So, yes, declaration and definition happen together in javascript (automatically - if you don't do it yourself) and the default defined value is undefined.

ES6

Just an additional note

const a;

will throw a SyntaxError where a initializer (definition) is necessary. const is the only time when you need to declare and define manually.

kaizer1v
  • 898
  • 8
  • 20
2
> var x;
undefined
> x
undefined // now it looks like x is defined to the value undefined
> y
ReferenceError: y is not defined

Although it is usually said that Javascript is an interpreted language, but there is also a compilation step that happens very fast just before the interpreter runs. The job of this compilation step is to create scope chains, where variables are declared(no read/write operation here, just simple name-keeping) in their respective scopes. These variables will point to some memory location but value in it will be undefined until some execution is carried out by the interpreter.

> Compiler run:

When compiler sees var x;, it will simply book-keep this variable in its respective scope.

The next x; and y; are simply ignored in the compilation step as they are execution statements.

> Interpreter run:

When interpreter sees var x;, it will skip this as there is no read/write operation here.

Now when interpreter sees x;(execution statement), "x" will already be declared in the scope, and it will hold value "undefined", which is what you get on the console.

But when interpreter sees y; similarly, there has been no previous declaration or name-keeping for it in the compilation step, and thus we get the ReferenceError as expected.

Hope someone finds this comment useful.

Sarthak Joshi
  • 141
  • 3
  • 2
0
var x, y, z;

var x;

var h = 4;

i = 4;

all the above are global variables if placed at the top, (outside any functions)

Lets say that the javascript has a function start

function start() {
      x = 5*5;
}

the global variable x is now equal to 25

Where as if the var x; was not placed outside of any functions, that variable x would just be local to that function.

CRABOLO
  • 8,605
  • 39
  • 41
  • 68
0

You declare JavaScript variables with the var keyword: var carname;

After the declaration, the variable is empty (it has no value).

To assign a value to the variable, use the equal sign var carname="Volvo";

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.

The variable carname will have the value undefined after the execution of the following statement: var carname;

var hoisting

In JavaScript, a variable can be declared after being used.

 bla = 2
 var bla;
  // ...

  // is implicitly understood as:

 var bla;
 bla = 2;

For that reason, it is recommended to always declare variable at the top of functions. Otherwise, it may lead to confusing cases

When declaring a variable without assigning a value to it, there still needs to be some memory available for it, otherwise you cannot make a reference to the variable later in the program. I don't think it's a noticeable amount of memory being used and won't make a difference.

Gourav
  • 1,765
  • 2
  • 15
  • 16
0
var x;

This is a variable declaration. In Js if you don't assign any value to variable in declaration. It will get undefined by default.

var x; // declaring x
console.log(x); // output: undefined

But if you have not even declared the variable in you try to access it. It says that the variable is not defined.

console.log(y);  // Output: ReferenceError: y is not defined

If you need access to objects between JS files, it's good practice to expose one object to the global namespace and declare fields and methods on that object.

File 1:

var myObject;
myObject.myField = "Field!";   

File 2:

myObject.prototype.myFunction = function () {
    return this.myField;
};

I have taken from a really good discussion on : Equivalent of C extern declaration in JavaScript

https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Questions

Apurva Pathak
  • 692
  • 1
  • 9
  • 22
0

Various trivia regarding the difference between undefined and null completely aside, the short answer is: there is no equivalence in Javascript. There are no bare "forward declarations". Javascript variable declarations are definitions. Variables that have been defined but not explicitly initialized will contain the value 'undefined'. There is no "external linkage".

If you refer to an identifier that is not in any accessible scope (perhaps because it doesn't exist the first place), you will get your "ReferenceError: y is not defined". This has nothing to do with variable value or storage.

aaron
  • 1,068
  • 12
  • 14
-1

In simple terms,

undefined means value to the variable is not defined.

not defined means the variable itself is not defined.

var x; //value is not defined. So, x //undefined

//y variable is not declared or defined. So, y // y is not defined

  • 2
    I think you're confusing undeclared with undefined yourself in this answer on the third line. – Sjeiti Apr 15 '19 at 14:21
  • in the third line, since y is not declared and definitely not defined further, it doesn't find a reference to it and so, you get an error that the variable y is not defined. – Aneesha Rao Apr 16 '19 at 07:18