On this page, it shows some example code, containing the following line:
var Subject = ( function( window, undefined ) {
What is the undefined as a function parameter?
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.
Because you used to be able to redefine the value of undefined, but not anymore. Undefined is a special type that has several use cases. If it was redefined to true, code like this would break:
if(my_var === undefined) {
dont_load_missiles());
} else {
load_missiles();
}
I recently asked a similar question ( SO link ) and the community suggested this article.
Following statements in the selected answer ( link ) theoretically answers the question;
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.
I believe a practical example might be helpful
var undefined = 7;
function printUndefined(undefined) {
document.getElementById("output").innerHTML += undefined + "<br/>";
}
printUndefined(); // Output is undefined
printUndefined(undefined); // Output is 7
printUndefined(10); // Output is 10
JSfiddle
Therefore the only guarantee is that the method caller is in control of the context.
Related
In "non-strict" mode of javascript, We can assign value to undefined. I tried to assign it value but when I tried to print that value it's giving me strange results.
let a = 10;
undefined = 20;
a = undefined;
console.log(a); // undefined not 20
console.log(undefined); // undefined not 20
If I create my own scope then undefined can be overwritten. I know that since ECMA 5 you cannot override undefined it's read-only. Then how I am getting the following output(set undefined to 10) for my own scope?
Does it means that I can write that in my own scope(non-global) only?
(function (undefined) {
undefined = 10;
console.log("Value of undefined: " + undefined);
})();
This is as expected. References to undefined is actually window.undefined, and the undefined property of window is non-writable:
console.log(Object.getOwnPropertyDescriptor(window, 'undefined'));
And non-writable properties can't be overwritten.
The difference is that in strict mode, trying to write to it throws an error, whereas in sloppy mode, the failure is silent.
The same sort of behavior can be seen if you assign another non-writable property to window and try to overwrite it:
Object.defineProperty(window, 'prop', { value: 'value', writable: false });
window.prop = 5;
console.log(window.prop);
(() => {
'use strict';
window.prop = 10;
})();
Although You Don't Know JS says you can "assign a value to the globally provided undefined identifier", this is only true for ES3 environments and below. In ES5+ (which pretty much all browsers support nowadays), undefined is not overwritable.
Playing with javascript closures I end up with this question I cannot reach to explain.
(function() {
console.log("Inside closure"); //does not work
}(foo));
It does not work because foo is undefined. referenceError
But if prior I set var foo = undefined; it works (tested on Chrome and ff).
It is not the same to be undefined that to be set to undefined?
example in jsfiddle
In javaScript, 'undefined' is one of the primitive data types. It represents the type of an object.
var a = undefined;
var b;
console.log((typeof(a)));
console.log((typeOf(b)));
The output will be undefined for both the cases.
If you don't declare a variable at all and try to access it, the error thrown will be the following. I tried to access c which is not declared at all.
Uncaught ReferenceError: c is not defined(…)
Having a variable whose value is undefined is not the same as having no variable with that name.
In ECMAScript, identifiers are resolved according to Identifier Resolution, which returns a reference given by GetIdentifierReference.
In case the variable doesn't exist, the base value of that reference will be undefined, otherwise it will be an environment record.
When GetValue gets the value of that reference, it will check IsUnresolvableReference. If the base value is undefined, it will return false, and GetValue will throw a ReferenceError exception.
If the variable exists (even if its value is undefined), GetValue will return its value.
If you are not sure whether some variable exists, you can use the typeof operator, which returns "undefined" for unresolvable references instead of throwing.
If the question is:
But what if somebody uses the the common jQuery wrapper and has the jQuery script not working yet?
Then you will still get a reference error if the jQuery identifier is not in the global scope because it is trying to find the reference to jQuery but it will not exist.
the undefined keyword is passed in the closure so that if undefined is assigned a value, it will not mess with your code. For example:
var undefined = 123
if(undefined){
console.log("pass")
}
this code will pass. If you Pass through undefined but leave out the parameter when you invoke it, undefined will have not a value assigned to it. It wont be looking for a reference as you haven't assigned the parameter For example :
(function(undefined){
// undefined will be undefined.
}())
I've done a quick example here for you : https://jsfiddle.net/gn7h3641/
TLDR : if your asking JavaScript for the value of a variable that doesn't exist(not been defined with var), it will explode because it has not got a reference to find the value yet which is different to checking if something is undefined in a 'if(test === undefined)'
Recently, I've been learning JavaScript. I'm coming across a few JavaScript errors that say "__ is undefined" - What exactly does this mean, and why is this coming up? I'm looking more or less for an explanation on why this error is occurring and what can be done to fix it, or why it's generally occurring in the first place.
For example: Here are two functions (validate and onSearch) --- When I try to run "onSearch", I get the Ran SEARCH... trace in the console, however it disappears. Additionally, when I run it through JSHero (trying to debug), it tells me that "onSearch" is undefined, and I'm curious as to why.
I've go some experience developing with ActionScript, but I'm totally new to JavaScript. I'd really appreciate your input and explanation regarding what this actually means. Thanks you.
function validate(query){
console.log("Ran VALIDATE...");
// Trim whitespace from start and end of search query
while(query.charAt(0) === " "){
query = query.substring(1, query.length);
};
while(query.charAt(query.length-1) === ""){
query = query.substring(0, query.length-1);
};
console.log("Query length:",query.length);
console.log("Beginning conditional...");
// Check search length, must have 3 characters
if(query.length < 3){
console.log("Display alert...");
alert("Your search query is too small, try again.");
// (DO NOT FIX THE LINE DIRECTLY BELOW)
searchInput.focus();
}else{
console.log("Searching query...");
onSearch(query);
};
};
// Finds search matches
function onSearch(query){
//var search = function(query){
console.log("Ran SEARCH...");
// split the user's search query string into an array
var queryArray = query.join(" ");
// array to store matched results from database.js
var results = [];
// loop through each index of db array
for(var i=0, j=db.length; i<j; i++){
// each db[i] is a single video item, each title ends with a pipe "|"
// save a lowercase variable of the video title
var dbTitleEnd = db[i].indexOf('|');
var dbitem = db[i].tolowercase().substring(0, dbTitleEnd);
// loop through the user's search query words
// save a lowercase variable of the search keyword
for(var ii=0, jj=queryArray.length; ii<jj; ii++){
var qitem = queryArray[ii].tolowercase();
// is the keyword anywhere in the video title?
// If a match is found, push full db[i] into results array
var compare = dbitem.indexOf(qitem);
console.log("Compare:",compare);
if(compare != -1){
results.push(db[i]);
};
};
};
console.log("Hello");
results.sort();
// Check that matches were found, and run output functions
if(results.length === 0){
noMatch();
}else{
showMatches(results);
};
};
EDIT**
"db" is defined in an external file. It's just an array of URL's. It's still saying it's not defined as well, which is what I'm asking.
How do you define
1) A variable
2) A function
If you get a TypeError along the lines "Blah is undefined" or "cannot read property foo of undefined", it means that you have a variable or property that has the value undefined, which is the default value for a variable until you assign something to it.
This is as opposed to having a variable you haven't defined yet and trying to read its value, which will fire a ReferenceError instead.
For instance, consider the below:
var foo;
console.log(foo.bar); // "TypeError: Cannot read property 'bar' of undefined"
The foo variable exists, but its value is undefined, so trying to read a property from it causes an error.
Contrast that to:
console.log(missing); // "ReferenceError: missing is not defined"
Here, the symbol missing is not defined; the engine has no idea what you're talking about. This usually indicates a missing var statement.
Side note: JavaScript has a very surprising behavior if you assign to a variable you've never declared (in ES3 or in ES5 in "loose" mode): It creates a global variable. I call this The Horror of Implicit Globals. It means that if instead of console.log(missing); above, I did this:
missing = "foo";
...I'd be creating a new global variable, even if that code is within a function. Thankfully, in ES5, we can use "strict" mode, which makes this the ReferenceError it always should have been. :-)
It usually means that the 'thing' you're requesting does not exist(or atleast can't be found by the function requesting it). This can be a variable, object or a function.
In the case of the onSearch you're talking about is that the function can't be found, most likely. It could be that the file with the function in it is loaded after the file requests it(So onSearch is in b.js, the one requesting it is in a.js. a.js is in your <head> before b.js). Therefore it's not yet present, since javascript files load linear.
Your problem
The problem is not that onSearch is undefined, but it uses a variable db which is undefined.
Cases
(From now on I will assume qwertyuiopasddsghjdsvjkfhjkl is not declared)
You see undefined errors when:
You use variable you have not declared.
qwertyuiopasddsghjdsvjkfhjkl; // ReferenceError: qwertyuiopasddsghjdsvjkfhjkl is not defined
You use a property on a declared but undefined variable:
var a;
a.b; // TypeError: a is undefined
A variable is undefined when:
(Error) You have not declared it
// qwertyuiopasddsghjdsvjkfhjkl is undefined
qwertyuiopasddsghjdsvjkfhjkl; // ReferenceError: qwertyuiopasddsghjdsvjkfhjkl is not defined
(No error) You have declared it but it has no value
var a; //a is undefined
(No error) You assign a variable to void(0) (you can change 0 with everything) or and unmodified undefined
var a = undefined; //a is undefined
var a = void(0); //a is undefined
undefined = 'abc';
var a = undefined; //a is NOT undefined
How to check
If you don't know if a variable is undefined, you can use
typeof myVar === 'undefined'
It returns true if:
myVar is not declared
myVar is declared but is undefined
It returns false if myVar is declared and myVar is not undefined
myVar === void(0)
It returns true if myVar is declared and myVar is undefined
It returns false if myVar is declared and myVar is not undefined
It throws an error if myVar is not declared
myVar === undefined
It's the same as myVar === void(0) if undefined has not been modified.
!myVar, if(myVar)
It returns true if myVar is declared and
myVar is undefined
or
myVar is falsy (null, 0, false, '')
It returns false if myVar is declared and myVar is truthy
It throws an error if myVar is not declared
I have below javascript function-
function ResponseVal()
{
this.value1;
this.value2;
}
var Response = new ResponseVal();
I tried and execute above code in chrome consolebar.I could not understand why newly created object "Response" does not show property value1 and value2. Can anyone help me to understand it what is happening and why properties are not displaying.
You should set the values to something. All you've done is try to read them in the constructor.
function ResponseVal()
{
this.value1 = "";
this.value2 = "";
}
var Response = new ResponseVal();
Declaring a property without setting it essentially does nothing. While it won't result in an error, some interpreters will throw a warning—as will strict mode, I believe.
JavaScript doesn't make this immediately obvious. For example, if you do this:
function Hello() {
this.value1;
}
var h = new Hello;
alert(h.value1);
The alert will read undefined. However, the property value1 was never actually accessed—it doesn't exist at all because you did not provide a value for it.
Rather than throwing an error, JavaScript returns undefined any time you try to access a property that doesn't exist. So you will get the same result if you write, say:
alert(h.property_that_doesnt_exist); //alerts 'undefined'
Iterating through the properties of h shows clearly that the property value1 does not exist:
for (var key in h) {
alert(key + ' = ' + h[key]);
}
This alerts nothing, because no properties will be found. However, if you set the property to the JS primitive undefined, the property WILL exist:
function Hello() {
this.value1 = undefined;
}
var h = new Hello;
for (var key in h) {
alert(key + ' = ' + h[key]); //alerts 'undefined'
}
You can run the above code here: http://jsfiddle.net/Acdmn/
But there's no good reason to set a property/variable to undefined. To create a property with an "empty" value, JavaScript programmers typically use null:
function Hello() {
this.value1 = null;
}
This makes it clear that the property was created intentionally, but you're not ready to give it a meaningful value yet.
Lastly, note that property definitions work differently from "normal" (private) variables explicitly set with var (even though these are also properties, in this case of the window object). If you write:
var foo;
alert(foo);
alert(some_undefined_variable_name);
The first alert will say undefined. The variable foo was created, does exist, and contains the primitive value undefined (even though you didn't set it explicitly). The second alert, however, will throw a reference error:
ReferenceError: some_undefined_variable_name is not defined
So JavaScript is unforgiving about using undefined variables, but it doesn't care if you try to use an undefined property.
They are still undefined. They only exist once defined.
You need to assign values to value1 and value2, 'null' at least.
I'm doing some experimenting with this malicious JavaScript line: var undefined = true;
Every uninitialized variable in JavaScript has the value of undefined which is just a variable that holds the special value of 'undefined', so the following should execute the alert:
var undefined = true,
x;
if (x) {
alert('ok');
}
But it doesn't, and my question is why?
On further experimentation, I tried the following:
var undefined = true,
x = undefined;
if (x) {
alert('ok');
}
This time, the alert is executed.
So my question is...since in the first snippet x holds undefined (because it is not initialized), why didn't the alert execute? The strange thing is that when explicitly stating that x is undefined (x = undefined), the alert executed...
There is a difference between a variable named undefined and the value called undefined.
var undefined = true,
x;
In this example, the variable undefined is set to the value true, and x to the value (not the variable!) undefined.
var undefined = true,
x = undefined;
In this example, the variable undefined is set to the value true as well, and x is set to the value contained in the variable undefined (which is true).
So, while you can declare a variable named undefined, you cannot change the fact that non-initialized variables are set to the value undefined.
Just declaring a variable called "undefined" does not mean that you're overriding the built-in concept of what the native "undefined" value is.
Imagine if Java would let you use "null" as an identifier. Well, I guess Java doesn't have the same coercion as Javascript. Anyway the Javascript statement
if (x) alert("foo");
involves an implicit coercion of the value of "x" to boolean. The value isn't defined, so its coercion to "boolean" results in false.
Uninitialized variables get the special value undefined. When you assign a variable to another variable you're giving it a string that references a variable you've defined within the current scope. In this case you've defined a variable named undefined so the JavaScript engine will look first through the variables, see that you've named one undefined and then assign it that variable.