0

At the moment I'm trying to wrap my head around the use case for declaring a Javascript variable but not initialising it right away. I understand that declaring a variable will store/set aside memory to that variable for future use, but what's the point in declaring a variable and not initialising it immediately?

My first thought would be a use case where you'd want to declare a variable to use in multiple functions, or for creating multiple objects, like so:

var me;

function firstMe(){
  var me = "Ryan";
  //do something...
}

function secondMe(){
 var me = "Bob";
 //do something...
}

Is it good practice to work with variables like this? What are the situations in which declaring a variable and not initialising it are useful or preferred?

Ryan
  • 69
  • 2
  • 10
  • 1
    This is too broad and quite subjective; it depends on what the programmer was trying to convey at the time of writing the code, and what the code does as well. If you can, edit your question to include a specific example case that you want explaining – Bojangles Jul 30 '14 at 07:01
  • here are some good answers: http://stackoverflow.com/questions/500431/javascript-variable-scope?rq=1 – lordvlad Jul 30 '14 at 07:01
  • There could be many reasons, such as wanting it to hold a reference to an element that can be used globally, but only initialising it on an onLoad function. – James Hunt Jul 30 '14 at 07:01
  • @Bojangles I don't really have a specific use case at the moment, I'm just wondering for future reference whether or not it's useful to work with variables in this way. – Ryan Jul 30 '14 at 07:03
  • @lordvlad I understand scope, I just don't quite understand when to declare vs initialise! – Ryan Jul 30 '14 at 07:04
  • @JamesHunt That makes sense, is there a specific use case you could reference? – Ryan Jul 30 '14 at 07:06
  • Done, see my answer below. – James Hunt Jul 30 '14 at 07:13

4 Answers4

3

For starters, it's always initialized as undefined:

var a;
a === undefined; // true
var b = undefined; // exact same thing

Now, since the language is weakly typed, when undefined a variable doesn't set up memory for future use, since it can't know how are you going to use it, until you assign something to it.

As for when to declare but not initialize, well that's very specific to your needs and constraints; for example, a common technique (to cope with javascript global scope nuances) is to declare all the variables you'll need at the beginning of a function, so they don't inadvertently go to the global scope if you forget to user var:

var a, b, c;
// some code
a = 1 // since it was declared at the beginning, this will stay in local scope

This is considered good practice.

And to clarify, in your example you're declaring var me inside each function, that actually creates a new variable in the local scope, so you're not changing the global scope; for instance, take this code:

var me = 'jaime';
function change() {
    var me = 'ryan';
}
change()
alert(me) // jaime

It may also worth adding that there's no practical performance benefit of declaring the variables before use (uninitialized), just don't worry about it.

Jaime Gómez
  • 6,961
  • 3
  • 40
  • 41
  • +1 for "declare at the beginning". This helps to manage variables and reduce the chance that they are inadvertently used twice. However, it also makes sense to declare counters in *for* statements in the iteration statement: `for (var i=0; ...; ...)` and other similar cases where the declaration should be associated with the use to make the code clearer. It's about coding style, not really about "right" or "wrong". – RobG Jul 30 '14 at 07:16
  • I do that too, it's a new scope after all, and it looks silly to have `var i, j, k;` at the beginning :) – Jaime Gómez Jul 30 '14 at 07:19
  • But initialising a variable with `var` in local scope will change the value of the variable you declared at the start. So if you wanted to use that variable multiple times, the global scope would be re-written each time you initialised it without `var`. Again, I suppose it depends on the use case, but I wouldn't think that would be a good approach. – Ryan Jul 30 '14 at 07:21
  • Actually no, if you use `var` in another scope it does the opposite, you *avoid* changing the global scope. Try it out! I would add it to my answer but it seems out of scope. – Jaime Gómez Jul 30 '14 at 07:23
  • For example, in your code, `me` inside the functions will not affect the global scope. – Jaime Gómez Jul 30 '14 at 07:25
  • Yeah that's my point! `var` in the local scope will not change my globally declared variable, but a variable initialised locally without `var` will change all previous instances of that global variable, which I wouldn't want to do if I were using that variable within multiple functions. – Ryan Jul 30 '14 at 07:31
  • You're right, and yeah you usually don't want that (it may well be the main source of javascript bugs), that's why that technique I mentioned was originally conceived. And there are other approaches you can use if you need to share state, to avoid using actual global variables. – Jaime Gómez Jul 30 '14 at 07:35
  • I just realised that I mistyped in my first comment "But initialising a variable with `var` in local scope..." It was meant to be "without `var`..." – Ryan Jul 30 '14 at 07:43
  • "It may also worth adding that there's no practical performance benefit of declaring the variables before use (uninitialized), just don't worry about it." That's what I was looking for. Thanks! – Ryan Jul 30 '14 at 07:44
  • @Ryan—the term "initialize" means assign a value the first time, which I think you are confusing with a variable declaration, e.g. `var identifier` which can also be an initialiser if an optional assignment is included, e.g. `var identifier = 'foo'`. – RobG Jul 30 '14 at 09:19
  • @RobG So if I declare a variable without a value and assign a value to it later, I'm not initialising it? – Ryan Jul 31 '14 at 06:37
  • @Ryan—you initialise it when you assign a value. – RobG Jul 31 '14 at 11:46
1

If you redeclare "var me" inside your functions, these vars will not be global. You would rather do:

var me;

function firstMe(){
  me = "Ryan";
  //do something...
}

function secondMe(){
 me = "Bob";
 //do something...
}
lpg
  • 4,897
  • 1
  • 16
  • 16
  • This doesn't answer his question, it corrects his example. Suggest an edit. – James Hunt Jul 30 '14 at 07:01
  • it dosn't answer it per se, but it hints to something the op is maybe misunderstanding – lordvlad Jul 30 '14 at 07:03
  • 2
    It doesn't answer it at all. He's asking why variables would be declared but not initialised, not the difference between local and global variables. All this does is fix an unrelated issue in his example. – James Hunt Jul 30 '14 at 07:03
  • From what I understand, initialising a variable (whether global or local) without `var` will affect all other previous cases in which you've initialised or declared that variable, and is bad practice. Am I right? – Ryan Jul 30 '14 at 07:07
1

Declaring a variable but not initialising it depends on the programmer and the situation. It is a very broad subject. An example where it could happen is if a global reference to an element is desired. The document would have to load before the variable can be initialised, but it would need to be declared first.

var canvas;
function onLoad()
{
    canvas = document.getElementById("myCanvas");
}

But if you are talking about locally, again, it is all down to the programmer.

James Hunt
  • 2,448
  • 11
  • 23
  • And so by declaring it first and waiting for your document to load to initialise it, are you increasing performance? – Ryan Jul 30 '14 at 07:14
  • Well, if you do it this way around, the variable wouldn't need to be created locally in each function it needs to be used. Creating one variable instead of recreating it locally several times is certainly more efficient performance wise. – James Hunt Jul 30 '14 at 07:33
  • Ok, your example makes more sense than any of the others, but I still fail to see the gain in declaring your variable outside a function and then initialising it in a function. I guess it's just a preference thing. Thanks for helping! – Ryan Jul 30 '14 at 07:40
  • Well, when it comes to ints and Strings, it's probably best to initialise as you declare, even if it is 0 or "" so int/String functions can then be used on them. When it comes to dynamic references to objects however, those objects might only be created within functions, so they can only be initialised then. (Such as document elements, or custom class-based objects for whatever reason) – James Hunt Jul 30 '14 at 07:45
  • I've still got a million more "what ifs", but perhaps I should save them for another day :) – Ryan Jul 30 '14 at 07:49
  • Well, if any questions arise, drop me an email OR, if it is specific enough, ask it on here. – James Hunt Jul 30 '14 at 07:51
  • Yeah, I'll try to bring in a more specific use case next time. – Ryan Jul 30 '14 at 07:53
0

I don't know about javascript memory management (except that you really should not care about it in almost all cases..), but the most common reason to define a variable is to define it's scope.

In your example, you have written var in front of your variable inside both functions. This means those variables have a scope only inside that function. (So it's not the same "me" as outside the function).

If you leave var out however from both functions, the both functions will share the same variable.

For example

var lock;

function doSomething() {
    lock = true;
    // do something
}

function doSomethingElse() {
    if (lock) .. else ..
}  

doSomething and doSomethingElse functions both use the same lock variable.

And to answer your question:

Is it good practice to work with variables like this? What are the situations in which declaring a variable and not initialising it are useful or preferred?

I think the above example is a perfectly acceptable example. Using "global variables" as such is bad programming paradigm, but if you are doing a simple script then why not.

Esko Piirainen
  • 1,296
  • 2
  • 14
  • 28
  • Yes, and if I were to initialise my variable without `var` inside my function it would also assign that value to the previous instance where I declared my variable in the global scope. – Ryan Jul 30 '14 at 07:10