Question

So in Javascript, there are two ways of declaring a single variable:

  1. Declaration var myVariable; then assignment myVariable = 1234; later on in the code
  2. Declaration and assignment in one line var myVariable = 1234;

For the first way, if you declare the variable, its value is undefined, until it is assigned to a value. So if it isn't yet assigned, it is basically worthless. Why would anyone do the first type of declaration?

On a related note, why does Javascript, and I guess any language that does this (C,C++, etc.), have both declarations and assignment (versus, say python-like assignment myVariable=1234), since the variable, even when declared, is useless until it is assigned?

Was it helpful?

Solution 4

There are a couple things you are missing here. :

1) All variable declarations are hoisted to the top of your function by the JS interpeter so ALL variables are undefined until assigned anyway, even the ones that are declared and assigned in the same statement later in the function. This is called "variable hoisting" and is a feature of the Javascript language. So, there is no functional difference between a variable that is defined at the top of the function and one that is defined later in the function. The only thing that affects the possible behavior of the function is where the variable is assigned a value.

So, because of variable "hoisting", a function like this with two inline variable declarations:

function(array) {
    for (var i = 0; i < array.length; i++) {
        var el = array[i];
        if (el > 3) {
            array[i] = el * el;
        }
    }
}

is actually treated like this by the js interpreter (where all variable declarations are hoisted to the beginning of the function):

function(array) {
    var i, el;
    for (i = 0; i < array.length; i++) {
        el = array[i];
        if (el > 3) {
            array[i] = el * el;
        }
    }
}

2) A variable that is undefined has a value. That value is undefined and can be useful. For example, it is falsey so that it can be tested in an if statement or any boolean test or it can even be tested explicitly to see if it's undefined. Here's an example:

function processIfNegative(array) {
    var foundNegative;
    array.foreach(function(el) {
        if (el < 0) {
            foundNegative = true;
        }
    });
    if (foundNegative) {
        // do some processing
    }
}

Now, for readability purposes, I would probably initialize foundNegative to false myself, but that isn't required because undefined is already falsey.

Or, here's an example where you explicitly check for the undefined value.

function processLowestPositive(array) {
    var lowestValue;
    array.foreach(function(el) {
        if (el >= 0) { 
            if (lowestValue === undefined) {
                lowestValue = el;
            } else if (el < lowestValue) {
                lowestValue = el;
            }
        }
    });
    // if there was a positive value found
    if (lowestValue !== undefined) {
        // process the lowest positive value
    }
}

Note: when testing for the undefined value explicitly, I always use === or !== so there are no type conversions and I'm sure the value is actually undefined.

OTHER TIPS

your variable will remain undefined until the interpreter reaches the line where you assign it a value.

All variables and functions are hoisted to the top of their respective scope at run time. Essentially, every single variable you have on that page will be declared undefined right when the script starts and remain that way until it finds itself an = sign somewhere.

Here's a much more in-depth explanation for you :)

Scroll a little bit to the section on hoisting but honestly, the whole thing is a very essential read.

Why would anyone do the first type of declaration?

This kind of declaration would often take place in order to access this variable from anothers level of scopes in your code.

//higher-scope variable
var name;

function setName(_name){
     //Usage at a lower scope
     name = _name;
}

Usage:

    //Notice how I use the "higher scope" variable at the
    //function and out of the functions - different scopes!

        setName("David");
        alert(name);

Sometimes people like to group all their variable declarations at the top of a function, so as to mimic what is actually happening with "variable hoisting".

If the desired initialization value is not yet known, then clearly it can't be initialized with that value.

Here is an example of what you can do :

var myfunc = function(flag){
    var myvar;
    if(flag) myvar = 42;
    else myvar = 0;
    return myvar;
}

So you see, here you myvar is undefined. and not set with a good reason. Another example

var myvar;
(function(){
    myvar = 42;
})()

In an another script :

alert(myvar);

Here the var will be global, whereas it was defined in an anomymous function.

It is possible to do this because you don't always need to assign it with something, but already want to define the variable. This can be useful if you're later going to assign it. For example:

var myValue;
if (condition) {
    myValue = 'myString1';
} else {
    myValue = 'myString2';
}

You don't want to assign a value to the variable in the first place, but you do want to use it further along. You can then just put the definition outside the if statement, and then just assign it with different things, depending on the if statement. Of course this example is oversimplified, but in situations similar to this one, it might be useful to do this.

This can also be useful in case you need to make a global variable:

(function scope() {
    var x;
    document.getElementById('myId').addEventListener('click', function(e) {
        x = this.innerHTML;
    });
})();

Now the variable x can be used from everywhere within the scoping functon.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top