[javascript] Can I set variables to undefined or pass undefined as an argument?

I’m a bit confused about JavaScript’s undefined and null values.

What does if (!testvar) actually do? Does it test for undefined and null or just undefined?

Once a variable is defined can I clear it back to undefined (therefore deleting the variable)?

Can I pass undefined as a parameter? E.g.:

function test(var1, var2, var3) {

}

test("value1", undefined, "value2");

This question is related to javascript undefined

The answer is


You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just defined it to something.

You cannot (should not?) pass undefined to a function. If you want to pass an empty value, use null instead.

The statement if(!testvar) checks for boolean true/false values, this particular one tests whether testvar evaluates to false. By definition, null and undefined shouldn't be evaluated neither as true or false, but JavaScript evaluates null as false, and gives an error if you try to evaluate an undefined variable.

To properly test for undefined or null, use these:

if(typeof(testvar) === "undefined") { ... }

if(testvar === null) { ... }

Just for fun, here's a fairly safe way to assign "unassigned" to a variable. For this to have a collision would require someone to have added to the prototype for Object with exactly the same name as the randomly generated string. I'm sure the random string generator could be improved, but I just took one from this question: Generate random string/characters in JavaScript

This works by creating a new object and trying to access a property on it with a randomly generated name, which we are assuming wont exist and will hence have the value of undefined.

function GenerateRandomString() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 50; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

var myVar = {}[GenerateRandomString()];

Try this:

// found on UglifyJS
variable = void 0;

The for if (something) and if (!something) is commonly used to check if something is defined or not defined. For example:

if (document.getElementById)

The identifier is converted to a boolean value, so undefined is interpreted as false. There are of course other values (like 0 and '') that also are interpreted as false, but either the identifier should not reasonably have such a value or you are happy with treating such a value the same as undefined.

Javascript has a delete operator that can be used to delete a member of an object. Depending on the scope of a variable (i.e. if it's global or not) you can delete it to make it undefined.

There is no undefined keyword that you can use as an undefined literal. You can omit parameters in a function call to make them undefined, but that can only be used by sending less paramters to the function, you can't omit a parameter in the middle.


The basic difference is that undefined and null represent different concepts.

If only null was available, you would not be able to determine whether null was set intentionally as the value or whether the value has not been set yet unless you used cumbersome error catching: eg

var a;

a == null; // This is true
a == undefined; // This is true;
a === undefined; // This is true;

However, if you intentionally set the value to null, strict equality with undefined fails, thereby allowing you to differentiate between null and undefined values:

var b = null;
b == null; // This is true
b == undefined; // This is true;
b === undefined; // This is false;

Check out the reference here instead of relying on people dismissively saying junk like "In summary, undefined is a JavaScript-specific mess, which confuses everyone". Just because you are confused, it does not mean that it is a mess.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

This behaviour is also not specific to JavaScript and it completes the generalised concept that a boolean result can be true, false, unknown (null), no value (undefined), or something went wrong (error).

http://en.wikipedia.org/wiki/Undefined_value


YES, you can, because undefined is defined as undefined.

console.log(
   /*global.*/undefined === window['undefined'] &&
   /*global.*/undefined === (function(){})() &&
   window['undefined']  === (function(){})()
) //true

your case:

test("value1", undefined, "value2")

you can also create your own undefined variable:

Object.defineProperty(this, 'u', {value : undefined});
console.log(u); //undefined

To answer your first question, the not operator (!) will coerce whatever it is given into a boolean value. So null, 0, false, NaN and "" (empty string) will all appear false.


The best way to check for a null values is

if ( testVar !== null )
{
    // do action here
}

and for undefined

if ( testVar !== undefined )
{
    // do action here
}

You can assign a avariable with undefined.

testVar = undefined;
//typeof(testVar) will be equal to undefined.

JavaScript, how to set a variable to undefined on commandline:

Set a variable to undefined in the js javascript command line terminal that comes with Java on Ubuntu 12.10.

el@defiant ~ $ js

js> typeof boo
"undefined"

js> boo
typein:2: ReferenceError: boo is not defined

js> boo=5
5

js> typeof boo
"number"

js> delete(boo)
true

js> typeof boo
"undefined"

js> boo
typein:7: ReferenceError: boo is not defined

If you set a variable to undefined in a javascript:

Put this in myjs.html:

<html>
<body>
    <script type="text/JavaScript">
        document.write("aliens: " + aliens);
        document.write("typeof aliens: " + (typeof aliens));
        var aliens = "scramble the nimitz";
        document.write("found some aliens: " + (typeof aliens));
        document.write("not sayings its aliens but... " + aliens);
        aliens = undefined;
        document.write("aliens deleted");
        document.write("typeof aliens: " + (typeof aliens));
        document.write("you sure they are gone? " + aliens);
    </script>
</body>
</html>

It prints this:

aliens: undefined
typeof aliens: undefined
found some aliens: string
not sayings its aliens but... scramble the nimitz
aliens deleted
typeof aliens: undefined
you sure they are gone? undefined

WARNING! When setting your variable to undefined you are setting your variable to another variable. If some sneaky person runs undefined = 'rm -rf /'; then whenever you set your variable to undefined, you will receive that value.

You may be wondering how I can output the undefined value aliens at the start and have it still run. It's because of javascript hoisting: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html