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 OverflowSee 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;
Basically, undefined represents value, which are not defined formally by user. Consider your example :
var isUndefined = function(obj){
return typeof obj == 'undefined';
};
So, isUndefined() when invoked without any argument, then the value of obj will be undefined in the function.
myFunction(undefined,"abc"); this way should work, what is the problem?
see here
Here is undefined documentation from mozilla, supported by all browsers
The void operator seems to be the most common way to explicitly get undefined.
You would use it like this in your example:
myFunction(void 0, "abc");
It's also a reliable method for comparing against undefined that is guarded against undefined being accidentally overridden in older JavaScript environments:
var x;
if (x === void 0) {
// this will execute
}
This is used to prevent from overriding the value of undefined in non-strict mode.
In non-strict mode, the value of undefined can be override by assigning other value to it.
undefined = true; // Or any other value
So, using the value of undefined will not work as expected.
In strict-mode, undefined is read-only and assigning value to it will throw error.
In the code, the value to the last parameter is not passed, so it'll be implicitly passed as undefined.
var Subject = ( function( window, undefined ) {
}(window)); // <-- No parameter is passed for the last value
That is done to make sure that undefined always is undefined. In JavaScript, since undefined isn't a reserved word but a regular variable, this would be allowed for instance:
undefined = 2; // Assign a different value to undefined
if (undefined == 2) // Now this statement would be true
So in your case
var Subject = ( function( window, undefined ) {
They pass in window and use it , but then they don't pass a second value to the undefined parameter, thus undefined will be undefined.
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?
When you put text in the parameter, text becomes letters inside the function.
var swapCase = function(letters){ //anything you put as a parameter in this function will become 'letters'
var newLetters = "";
for(var i = 0; i<letters.length; i++){
if(letters[i] === letters[i].toLowerCase()){ //letters[i] represents the character in the 'i' position (which is assigned in the for loop) in the string you added as a parameter.
newLetters += letters[i].toUpperCase();
}else {
newLetters += letters[i].toLowerCase();
}
}
console.log(newLetters);
return newLetters;
}
var text = "Life is 10% what happens to you, and 90% of how you REACT to it";
var swappedText = swapCase(text); // You are adding the text string as a parameter in the function, thus it becoming the letter variable inside the function
letters is a function parameter, so basically when you call swapCase(text), the function takes text and assign it to letters. If you call the function without parameter like this swapCase() then you basically pass undefined to this function and that is assign to letter. You can do a quick check at the beginning of the function to check for that.
if(letters === undefined) return false;
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.
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));
Thanks to JonathanMitchell for suggesting the object parameter.
const add = (args = {}) => {
const a = args.a || 1;
const b = args.b || 2;
return a + b;
}
Examples:
add(); // 3
add({a: 2}) // 4
add({b: 3}); // 5
Edit:
loganfsmyth offered a much better solution.
using || is bad form because if you pass 0 it would also use the default.
A better and more compact solution:
const add = ({a = 1, b = 2} = {}) => a + b
Logan used ES6's deconstruction assignment (see "Default" values) to assign a and b default values in the event that such parameters evaluate to undefined.
In practice,a better option would be to create a feed dictionary to pass into the function. That way you can set which values you like and leave others as is or to another value.
feed_dict = {x: 1, y: 2}
Then you should structure a function to take in a dictionary and perform the addition on its values
const add = (dict) => {
for (var keys in dict) {
sum += dict[keys]
}
return sum
add(feed_dict)
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:
When you call a function with fewer arguments than the arguments list in the
functionstatement lists, the unpassed arguments are set toundefined. 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)anddosomething(1, undefined);arg2will be the same value in both. If you need to tell the difference you can look atarguments.length, but doing optional arguments like that isn't generally very readable.When a function has no
return value;, it returnsundefined. There's generally no need to use such a return result.When you declare a variable by having a
var astatement in a block, but haven't yet assigned a value to it, it isundefined. Again, you shouldn't really ever need to rely on that.The spooky
typeofoperator 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.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
undefinedobject. (And then when you try to use thatundefinedobject 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
undefinedlike any other value:o.prop= undefined;that doesn't actually detect whether the property is there reliably. Better to use the
inoperator, 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.
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) { ... }