Can a null value automatically occur in JS - javascript

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.

Related

When does javascript throw reference error?

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.

javaScript closures. Undefined value as input stops script. Sometimes

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)'

why does accessing a property of a boolean value not throw an error - javascript

Why does accessing false.bar not throw an error while undefined.bar does?
var foo1 = false;
var foo2;
console.log(foo1.bar); // undefined
console.log(foo2.bar); // Uncaught TypeError: Cannot read property 'bar' of undefined
Look around for "boxing", you'll find that many answers have already been written.
To sum it up, Boolean, Number and String instances will magically "box" primitive values in a context where you're treating them as objects. Booleans don't have any useful methods or properties except the default Object-inherited ones, so you'll never see boolean boxing. But the language allows it.
However, there are no Null or Undefined constructors to box those values, so trying to access properties of null and undefined is an error.
In your example, foo1 actually exists, so we can check for a property on it (it has no property defined called "bar", so we get a undefined for that).
The other case, foo2, doesnt exists (it never has been init and is still undefined), so trying to check for a property will result in a error.
It's because false itself is an object, while undefined isn't.
Variable is undefined if it wasn't assigned a value yet, like foo2 in your code. You're trying to access a property of something that doesn't exist, so JS gets scared and throws error.
When you're trying to access foo1, the object foo1 exists, since you've assigned false to it. JS doesn't mind that this object doesn't have a "bar" property and will just return undefined, as in "this property isn't defined yet".

Javascript undefined, truthy vs typeof operator

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.

When do I initialize variables in JavaScript with null or not at all?

I have seen different code examples with variables declared and set to undefined and null. Such as:
var a; // undefined - unintentional value, object of type 'undefined'
var b = null; // null - deliberate non-value, object of type 'object'
If the code to follow these declarations assigns a value to a or to b, what is the reason for using one type of declaration over another?
The first example doesn't assign anything to the variable, so it implicitly refers to the undefined value (see 10.5 in the spec for the details). It is commonly used when declaring variables for later use. There is no need to explicitly assign anything to them before necessary.
The second example is explicitly assigned null (which is actually of type null, but due to a quirk of the JavaScript specification, claims to have type "object"). It is commonly used to clear a value already stored in an existing variable. It could be seen as more robust to use null when clearing the value since it is possible to overwrite undefined, and in that situation assiging undefined would result in unexpected behaviour.
As an aside, that quirk of null is a good reason to use a more robust form of type checking:
Object.prototype.toString.call(null); // Returns "[object Null]"
I just saw this link which clarified my question.
What reason is there to use null instead of undefined in JavaScript?
Javascript for Web Developers states "When defining a variable that is meant to later hold an object, it is advisable to initialize the variable to null as opposed to anything else. That way, you can explicitly check for the value null to determine if the variable has been filled with an object reference at a later time."
I don't think there's a particular better way of doing things, but I'm inclined to avoid undefined as much as possible. Maybe it's due to a strong OOP background.
When I try to mimic OOP with Javascript, I would generally declare and initialize explicitly my variables to null (as do OOP languages when you declare an instance variable without explicitly initializing it).
If I'm not going to initialize them, why even declare them in the first place? When you debug, if you haven't set a value for a variable you watch, you will see it as undefined whether you declared it or not...
I prefer keeping undefined for specific behaviours:
when you call a method, any argument you don't provide would have an undefined value. Good way of having an optional argument, implementing a specific behaviour if the argument is not defined.
lazy init... in my book undefined means "not initialized: go fetch the value", and null means "initialized but the value was null (eg maybe there was a server error?)"
arrays: myArray[myKey] === null if there is a null value for this key, undefined if a value has never been set for this key.
Be careful though, that myVar == null and myVar == undefined return the same value whether myVar is undefined, null or something else. Use === if you want to know if a variable is undefined.
I would explicitly choose null, to not create an object whose id is later overwritten anyway:
var foo = {}; // empty object, has id etc.
var foo2 = null; // good practice, // filled with an object reference at a later time
var foo3;// undefined, I would avoid it
console.log(typeof foo);
console.log(typeof foo2);
console.log(typeof foo3);
Setting null also ensures good readability to identify the datatype (object),
results in
object
object
undefined
Source (Professional JavaScript for Web Developers 3rd Edition):
When defining a variable that is meant to later hold an object, it is
advisable to initialize the variable to null as opposed to anything
else. That way, you can explicitly check for the value null to
determine if the variable has been filled with an object reference at
a later time, such as in this example:
if (foo2 != null){
//do something with foo2
}
The value undefined is a derivative of null, so ECMA-262 defines them to be superficially equal as follows:
console.log(null == undefined); // prints true
console.log(null === undefined);// prints false
null is an object.. When something is undefined it is nothing.. it is not an object, neither a string, because it hasn't been defined yet.. obviously.. then it is simply a property with no function..
example:
You declare a variable with var but never set it.
var foo;
alert(foo); //undefined.
You attempt to access a property on an object you've never set.
var foo = {};
alert(foo.bar); //undefined
You attempt to access an argument that was never provided.
function myFunction (foo) {
alert(foo); //undefined.
}

Categories