See this post. You have to understand the difference between undefined and undeclared variables.

At least you would do:

var x; //undefined until assignment;
isUndefined(x); // returns true;
Answer from bash0ne on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
The undefined global property represents the primitive value undefined. It is one of JavaScript's primitive types.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Functions › Default_parameters
Default parameters - JavaScript | MDN
Default function parameters allow ... 2)); // Expected output: 10 console.log(multiply(5)); // Expected output: 5 ... In JavaScript, function parameters default to undefined....
🌐
DEV Community
dev.to › sajidurshajib › javascript-default-parameter-for-null-and-undefined-25kk
Javascript default parameter for null and undefined - DEV Community
November 13, 2021 - Now, if I don't give any parameter what will be happen? Let's check... const sayHi = (greeting) => { console.log(greeting) } sayHi() //your@console:~$ undefined
🌐
The Valley of Code
thevalleyofcode.com › javascript-iife-undefined
Passing undefined to JavaScript Immediately-invoked Function Expressions
See, undefined is passed as argument, but not passed as a parameter when we invoke the function. So, inside the function the value of the variable undefined is (guaranteed) the original value of undefined.
🌐
Medium
medium.com › front-end-weekly › beginners-guide-dealing-with-undefined-in-javascript-d98ac7e413db
Beginner’s Guide: Dealing with Undefined in JavaScript | by Brandon Evans | Frontend Weekly | Medium
June 8, 2023 - Understanding their differences can help you handle them correctly in your code. undefined is the default value for uninitialized variables, inaccessible properties, and function parameters that were not provided.
🌐
TutorialsPoint
tutorialspoint.com › how-to-pass-the-value-undefined-to-a-function-with-multiple-parameters-in-javascript
How to pass the value 'undefined' to a function with multiple parameters in JavaScript?
We can pass the value 'undefined' to a function with multiple parameters using a variable that has the value of 'undefined'. In JavaScript, whenever a user declares a variable, it automatically contains the value of 'undefined'.
🌐
W3Schools
w3schools.com › js › js_function_parameters.asp
JavaScript Function Parameters
JavaScript functions do not perform ... check the number of arguments received. If a function is called with missing arguments (less than declared), the missing values are set to undefined....
Find elsewhere
🌐
EliuX Overflow!
eliux.ca › javascript › common-errors › why-this-gets-undefined-inside-methods-in-javascript
Why this gets undefined in high order functions in Javascript? - EliuX Overflow!
January 27, 2021 - > function Soldier(numBullets) { this.numBullets = numBullets; this.checkStatus = function() { console.log(this === captain); console.log(`I am ${this}`); console.log(`I have ${this.numBullets} bullets`); } } > captain = new Soldier(5); > captainStatus = captain.checkStatus; > captainStatus(); false I am [object Window] I have undefined bullets · This happened because in the browser window was the object that owned captainStatus at the moment of its execution. Try these same instructions again, but this time in a nodejs console to see what happens. Who is the owner of the method this time? Each time we are going to execute functions in Javascript, it is important to remember that:
🌐
Dmitri Pavlutin
dmitripavlutin.com › 7-tips-to-handle-undefined-in-javascript
7 Tips to Handle undefined in JavaScript
March 23, 2023 - The first version of append(), ... to verify whether these properties exist in toAppend. A property accessor evaluates to undefined if the property does not exist....
🌐
Reddit
reddit.com › r/learnjavascript › can i provide undefined as an input parameter in order to ignore this parameter?
r/learnjavascript on Reddit: Can I provide undefined as an input parameter in order to ignore this parameter?
February 8, 2023 -

function f(one, two){

if(!one) {

console.log(\one is not defined.`)`

return;

}

if(!two) {

console.log(\two is not defined.`);`

return

}

return one + two;

}

function(1);

f(undefined, 2); //is this an accepted way to do this?

f(1,2);

--------

I want to define a function that has multiple function signatures based on the input parameters it receives.

  • If I want to ignore the second input parameter, I can simple provide the first parameter while leaving the second parameter out.

  • How do ignore the 1st input parameter while providing a second parameter? I could provide a undefined,

    • is this an accepted way to achieve my object?

🌐
Stack Overflow
stackoverflow.com › questions › 52437205 › function-parameter-undefined-javascript
Function Parameter Undefined - Javascript - Stack Overflow
No, if you use a global variable and a local variable with same name, the local variable is accessed. If you passed the global variable as a parameter in function call, its value will be passed to the function which can be accessed inside the function. But if you are still getting undefined make sure the variable you passed has a value and its not undefined.
Top answer
1 of 3
20

What this is doing, is reassigning undefined to undefined inside that closure. Thats a failsafe. Because other code may accidentally do something like

undefined = something;
console.log(undefined); // will output 'something'

And thats valid in javascript(if the JS engine being used has not implemented ECMAScript 5 specification, in ECMAScript 5 spec undefined is non non-writable, MDN DOC ),

Quote from MDN New_in_JavaScript 1.8.5 (ECMA 5) Page

Changes to global objects

Global objects made read only

The NaN, Infinity, and undefined global objects have been made read only, per the ECMAScript 5 specification.

And from ES5 Annotated Spec in Guthub

ES5 spec Section x15.1.1.3

15.1.1.3 undefined

The value of undefined is undefined (see 8.1).

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

Even if global undefined is not writable You can have a local variable named undefined and can mess up your code(mainly comparisons with undefined). But that's your responsibility. You can have codes like

(function(){
    console.log('Second Case: ');
    var undefined = 'Something';
    console.log(undefined); // Will log `something`
    var a ; // a is undefined
    console.log(a  ===  undefined); // false, as undefined is changed
    // you might expect a === undefined will return true, but as 
    // `undefined` is changed it will return false.
    console.log(a); // undefined
})();

Demo: http://jsfiddle.net/joycse06/V4DKN/

However if undefined is writeable then the above assignment may hamper many comparison made with undefined after that line of code as undefined is not undefined anymore. It has some value now.

So as they are calling that anonymous function like

( window ) // one argument only

And receiving

( window, undefined)  // only window is passed when calling the function
          // Second argument is not passed means it's undefined
          // so undefined is restored to undefined inside that function
          // and no global accidental assignments can hamper jQuery's 
          // code using 'undefined' now

That means inside that closure undefined is restored to undefined, as it has not been passed any value thus securing use of undefined inside that anonymous function.

A very good detailed article on this http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/

I am quoting some lines from the above article link to make things clear

What is undefined?

In JavaScript there is Undefined (type), undefined (value) and undefined (variable).

Undefined (type) is a built-in JavaScript type.

undefined (value) is a primitive and is the sole value of the Undefined type.

Any property that has not been assigned a value, assumes the undefined value. (ECMA 4.3.9 and 4.3.10).

A function without a return statement, or a function with an empty return statement returns undefined. The value of an unsupplied function argument is undefined.

var a;
typeof a; //"undefined"

window.b;

typeof window.b; //"undefined"



var c = (function() {})();

typeof c; //"undefined"



var d = (function(e) {return e})();

typeof d; //"undefined"

undefined (variable) is a global property whose initial value is undefined (value), Since its a global property we can also access it as a variable. For consistency I’m always going to call it a variable in this article.

typeof undefined; //"undefined"
var f = 2;
f = undefined; //re-assigning to undefined (variable)
typeof f; //"undefined"

As of ECMA 3, its value can be reassigned :

undefined = "washing machine"; //assign a string to undefined (variable)
typeof undefined //"string"
f = undefined;
typeof f; //"string"
f; //"washing machine"

Needless to say, re-assigning values to the undefined variable is very bad practice, and in fact its not allowed by ECMA 5.

2 of 3
3

Undefined is a type but is also a global variable.

You can have a module that overwrites the value of undefined by doing undefined = whatever.

undefined in the is actually an undefined parameter of a function wrapping the whole code:

(function(window, undefined) {
    // undefined is the undefined parameter
}(window)); 

It's safe, as the undefined parameter is in local scope, and no one except the code in this function can assign to it.

It's not necessary to use undefined as parameter when define an anonymous function.

If you see above function you wll notice that it expects two parameter but one is supplied.

Why undefined need to restored?

because, to makes sure that undefined is indeed undefined in the scope between curly braces, even if someone has written something like undefined = "defined"; in the global scope, because undefined can actually be redefined.

So if you have something like

var undefined = 1;

(function(window, undefined) {
  console.log(undefined); // output will be undefined not 1
}(window));
🌐
Paige Niedringhaus
paigeniedringhaus.com › default function parameter values: javascript es6 feature series (pt 3)
Default Function Parameter Values: JavaScript ES6 Feature Series (Pt 3) | Paige Niedringhaus
August 23, 2019 - Enter the default function parameters; they allow named parameters in a function to be initialized with default values if no value or undefined is passed in. As I briefly explained above, up until now, in JavaScript, function parameters automatically default to undefined; which meant we had to test parameter values in a function body, check for potentially undefined parameters and assign values if they were undefined.
🌐
Stack Exchange
softwareengineering.stackexchange.com › questions › 374155 › adding-new-parameter-to-javascript-function
undefined behavior - Adding new parameter to Javascript function - Software Engineering Stack Exchange
If you don't change the original calls the undefined is implicitly passed for the arguments you don't specify. ... var foo = function(options){ var first = options.first; var second = options.second; var third = options.third; ... } This way, you have a much cleaner Interface foo({first:"Test", third:"Test3"}) You name the parameters, you want to set explicitely.
Top answer
1 of 10
589

I'm a bit confused about Javascript undefined & null.

null generally behaves similarly to other scripting languages' concepts of the out-of-band ‘null’, ‘nil’ or ‘None’ objects.

undefined, on the other hand, is a weird JavaScript quirk. It's a singleton object that represents out-of-band values, essentially a second similar-but-different null. It comes up:

  1. When you call a function with fewer arguments than the arguments list in the function statement lists, the unpassed arguments are set to undefined. You can test for that with eg.:

    function dosomething(arg1, arg2) {
        if (arg2===undefined)
        arg2= DEFAULT_VALUE_FOR_ARG2;
        ...
    }
    

    With this method you can't tell the difference between dosomething(1) and dosomething(1, undefined); arg2 will be the same value in both. If you need to tell the difference you can look at arguments.length, but doing optional arguments like that isn't generally very readable.

  2. When a function has no return value;, it returns undefined. There's generally no need to use such a return result.

  3. When you declare a variable by having a var a statement in a block, but haven't yet assigned a value to it, it is undefined. Again, you shouldn't really ever need to rely on that.

  4. The spooky typeof operator returns 'undefined' when its operand is a simple variable that does not exist, instead of throwing an error as would normally happen if you tried to refer to it. (You can also give it a simple variable wrapped in parentheses, but not a full expression involving a non-existant variable.) Not much use for that, either.

  5. This is the controversial one. When you access a property of an object which doesn't exist, you don't immediately get an error like in every other language. Instead you get an undefined object. (And then when you try to use that undefined object later on in the script it'll go wrong in a weird way that's much more difficult to track down than if JavaScript had just thrown an error straight away.)

    This is often used to check for the existence of properties:

    if (o.prop!==undefined) // or often as truthiness test, if (o.prop)
       ...do something...
    

    However, because you can assign undefined like any other value:

    o.prop= undefined;
    

    that doesn't actually detect whether the property is there reliably. Better to use the in operator, which wasn't in the original Netscape version of JavaScript, but is available everywhere now:

    if ('prop' in o)
        ...
    

In summary, undefined is a JavaScript-specific mess, which confuses everyone. Apart from optional function arguments, where JS has no other more elegant mechanism, undefined should be avoided. It should never have been part of the language; null would have worked just fine for (2) and (3), and (4) is a misfeature that only exists because in the beginning JavaScript had no exceptions.

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

Such a ‘truthiness’ test checks against false, undefined, null, 0, NaN and empty strings. But in this case, yes, it is really undefined it is concerned with. IMO, it should be more explicit about that and say if (testvar!==undefined).

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

You can certainly assign undefined to it, but that won't delete the variable. Only the delete object.property operator really removes things.

delete is really meant for properties rather than variables as such. Browsers will let you get away with straight delete variable, but it's not a good idea and won't work in ECMAScript Fifth Edition's strict mode. If you want to free up a reference to something so it can be garbage-collected, it would be more usual to say variable= null.

can I pass undefined as a parameter?

Yes.

2 of 10
25

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) { ... }