I have this very simple question, but I can not find any complete answer for this question.
JavaScript's null and undefined is the values of variables that have not been initialised and the value you get when you query the value of an object property or an array element that does not exist.
I first thought we get a referenceerror when we attempt to access a non-existent property of an object or an array element that does not exist, but as it turns out it isn't the case.
But on which occasions actually does it throw a referenceerror?
I appreciate if someone can tell all the situations when it can throw a referenceerror
You get a reference error when you:
Attempt to read a variable that has not been declared
Attempt to write to a variable that has not been declared when working in Strict Mode (in legacy mode this will create an implicit global instead)
JavaScript's null and undefined is the values of variables that have not been initialised
No. A variable that has been declared but not assigned a value or a property that has not been assigned a value will have undefined as a default value. undefined can also be explicitly assigned. null can only be explicitly assigned.
Related
In JS an "undefined" value could occur automatically by mistake.(eg:- if you call a function which does not return any thing)
Can a "null" value occur automatically?
undefined is what is returned when you attempt to access a property that is not there or an array value that is not there. It is also the initial value of a variable that has been declared, but not assigned a value yet. These are not really mistakes, but the way the language is designed when you request a value that is not there.
null does not occur by default like undefined does. If a variable or property or return value is null, that is because some programmer or API specifically assigned or returned null.
Also, calling a function that does not exist throws a ReferenceError.
This question already has answers here:
Why does accessing a non-existent object property result in `undefined` instead of throwing a `ReferenceError`?
(2 answers)
Closed 1 year ago.
In below code, if I print this.property2 on console, JS engine prints undefined, if I replace the statement to print only property2 compiler
throws a reference error. If I declare the variable property2 then the compiler will return undefined.
function foo() {
var property;
console.log(this.property2)
console.log(this.property2 === property2)
console.log(property2)
}
foo.property="property value";
var property2; // modified to resolve reference error
foo();
console.log(foo.property);
As I have shown in the code this.property2 is equal to property2 so why javascript behaves differently for the same variable.
Coming to my question are both variables(this.property2 and property2) different? If yes, then why comparison returns true?
If no, then why I have to declare property2 to get the return value and this.property2 returns values without
declaration.
Am I missing anything?
Why reading undeclared variable gives reference error but undeclared object property returns undefined in javascript?
It really comes down to: Because that's what Brendan Eich decided it should do when designing this stuff. But we can see some reasons he may have made those choices:
In the first case, you have a completely unknown identifier. In the second case, there's context: We know we're looking for an object property. Also note that we can assign to an unknown property without error (doing so creates the property; and that's a good thing, because for a long time it was the only way to create a property [if we loosely take property initializers in an object initializer as an assignment of sorts]; now we have Object.defineProperty [which assigns a value as part of the process] and its plural cousin and the related second argument to Object.create), which balances nicely balances with being able to read an unknown property without error.
He certainly could have made reading an unknown property from an object an error, he just didn't; and there's no changing it now. :-)
Note that early on he made assigning to an unknown identifier a mechanism for creating a global variable. (!) That one, thankfully, was fixed by strict mode.
Side note: You don't declare properties, you create them. Only functions, classes (which are really functions), and variables are declared.
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)'
Considering the following code:
//the var Test has NOT been declared yet
console.log((typeof Test)); // "undefined"
console.log(Test); //"Uncaught ReferenceError: Test is not defined"
Why does the second console.log statement throw a ReferenceError and the first displays undefined.
Because test is undefined.
In that first console.log you're asking the system to tell you the type of a variable. So it looks through the current scope chain to find a reference to that variable so it may infer its type.
When it doesn't find the variable, it receives the undefined primitive. Which has a type, as I'm sure you've guessed, of undefined.
The second time you're asking it to print out the value of an undefined variable. Since the variable is not defined (there is no reference to it in the current scope chain), this is an error you're trying to ACCESS DATA that doesn't exist, not just infer its type.
So,
I have always used the type of construction for testing the presence of variables:
if(foo){
doThings();
}
Now, I'm getting an
Uncaught ReferenceError: foo is undefined
Here's a fiddle
it's a fact that the var was never even declared.
My question is, is this normal behaviour? I've used this many times and i think this is not the first time the variable is not declared; i'm almost sure that i never had a problem with this, it just returned false and didn't get in the condition.
Any help and clarification is welcome.
If a variable has not been declared then an attempt to reference it will result in a reference error.
If a variable has been declared but not assigned a value then it will implicitly have the value undefined and your code will work as expected.
In your case, this is what happens:
Evaluate the if statement [if ( Expression ) Statement]
This involves evaluating Expression, which returns a reference, as per 10.3.1
Call GetValue on the returned reference
If the reference is not resolvable (it's value is undefined), throw a reference error
Coerce the value of the reference to a boolean value
The algorithm for determining the value of a reference traverses the chain of nested lexical environments until it reaches the outermost context. When it reaches that point and still does not find a binding for the provided identifier it returns a reference whose base value is undefined.
When the base value of a reference is undefined that reference is said to be "unresolvable", and when a reference is unresolvable any attempt to reference it will result (unsurprisingly) in a reference error.
check the updated fiddle. If you haven't declare a variable then in condition u will have to check its type.
var a = 1;
var b;
try{
if(typeof(c)!='undefined') {
alert("OK");
}
} catch(ex){
alert(ex);
}
fiddle
var is a reserved keyword in Javascript.
The following is the corresponding error
Uncaught SyntaxError: Unexpected token var