Javascript - If statements check both expression and definition declaration? This is confusing - javascript

var boolTrue = true;
var randomObject;
if (boolTrue)
// this will fire
if (randomObject)
// this will fire, because the object is defined
if (!objectNotDefined)
// this will fire, because there is no defined object named 'objectNotDefined'
Coming from a C++ and C# background, I am very familiar with the basic if(expression) syntax. However, I think it is not very readable to have both expressions (true/false) and have object existence also being a expression. Because now if I see a function like below, i don't know if the data coming in is an object (existence/undefined check) or a boolean.
function(data) {
if (data)
// is this checking if the object is true/false or if the object is in existence?
}
Is this just the way it is? I mean, is there anyway to easily read this? Also, where is this documented anywhere in the JS spec (curious)?

In Javascript everything is "true" (or "truthy" to be more precise using Javascript parlance) except false, 0, undefined, null, NaN and empty string.
To avoid confusion use:
if (data === true) // Is it really true?
and
if (typeof data === 'undefined') // Is the variable undefined?

You can check for (non-)existence separately:
if ( typeof variable == 'undefined' ) {
// other code
}
However, the syntax you show is commonly used as a much shorter form and is sufficient in most usecases.

The following values are equivalent to false in conditional statements:
false
null
undefined
The empty string ”
The number 0
The number NaN

It checks whether it is truthy.
In JavaScript, everything is truthy except false, 0, "", undefined, null and NaN.
So, true will pass, as well as any object (also empty objects/arrays/etc).
Note that your third comment is true if you mean "declared but not defined" - a variable that has never been declared throws a ReferenceError on access. A declared, non-defined variable (var something;) is undefined (so, not truthy) so it will indeed pass the condition if you negate it.

Related

Is there a difference between typeof x === 'undefined' vs if (x)

I've always maintained the practice of checking if a value is undefined using
if (typeof x === 'undefined')
However, a colleague is suggesting that using if (x) { is better.
Is there any difference between these two methods from a computational point of view?
There are at least two differences off the top of my mind:
Checking the type as undefined only checks for undefined, unlike if(x), which checks for any truthy values (e.g. true, a non-empty string, a non-zero number, etc)
You can perform typeof on non-existent variables, even in strict mode. You'll get a reference error if you never declared x and did if(x)
"use strict";
const a = undefined;
const b = "truthy value";
if(a) {
console.log("a in if"); // never executes
}
if(typeof a !== "undefined") {
console.log("a with typeof"); // never executes
}
if(b) {
console.log("b in if"); // executes
}
if(typeof b === "undefined") {
console.log("b with typeof"); // never executes
}
try {
if(c) console.log("this should error");
} catch(e) {
console.log("Can't access non-existent variable");
}
console.log("No error:", typeof c);
When should I use which one?
Generally:
Use if(x) when...
You're checking for a boolean
You're checking for (not) 0
You're checking for a non-empty empty string (probably use if(string.length) instead)
Checking the return value of a function (e.g. a function returns null when there's no result for a query or an object when there is (DOM functions like document.getElementById return null when no element with that ID exists))
Use if(typeof x !== "undefined") when...
You're checking whether an object key exists (if(typeof obj.key !== "undefined")) (the proper way as a commentator pointed out is with Object.hasOwn(obj, "key"))
You're checking whether a variable exists (not sure when or why you would do that though)
Checking whether an argument has been passed
Other uses like when you're writing an Express server and checking user-provided content
Something else I probably forgot...
Something that's useful to keep in mind is that Javascript is dynamically typed, even if it looks like it's just variables. There are a handful of types in JS, and Undefined (with caps) is one, and the only value it can hold is undefined. Think of it like saying you have the Number type and it only accepts 42. This is important to know because JS engines have to observe spec.
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.
There is a lot of variation in application code, but you can know that variables that have not been assigned are of type Undefined with value undefined and not something else. Next to Undefined is Null, which has a single value, null. Null, unlike Undefined, needs to be assigned.
In the spec you'll also the find the table for the result you get for each variable type.
You'll notice that Undefined has its own return value, as well as Boolean, but Null returns "object", which is reported to be a mistake in the original spec that we can't get rid of.
With types out of the way, we get to Boolean coercion, which is how if statements work out the condition. The spec has a table of cases that define when a value should be coerced into true or false.
You'll see that an if clause receives the Undefined type, it returns false. The same happens with Null. There are a few other cases that can also return false even if they are not Undefined or Null.
The Number type with values 0, -0, NaN
The String type with length 0 ("")
The BigInt type with value 0
As others have already answered, applications of the spec come in a few different places. The reasons as for why typeof exists and there is an overlap with the falsey evaluation arise from how the JS engines handle values and perform coercion into Boolean.

Javascript using if(foo) exists to check if variable is set

I realize that this question is extremely similar to many others, but I must be missing some nuance with checking whether a variable is set or not. I have seen this in other developers code:
if(foo){
doSomething(foo);
}
else{
alert('error of whatever');
}
With the intent that the doSomething() will only execute if foo is set or not undefined. However, when I google this, it seems everyone says "typeof" should be used instead of the above method. I specifically see this in use with angular, like this:
if($scope.property){
dothis();
}
Am I missing something? When I see the above code, it seems to work, but all the answers I see never say this is the correct way to check if something is set or exists.
For if() checks, in MOST scenarios where you are checking for the existence of a property on an object (your situation), what you have described is perfectly valid, easy and convenient. It checks for the existence of the property and returns true if it exists.
However, there are plenty of nuanced areas where a typeof check is "more" correct, particularly if your type is being coerced in any way via == or if you want to differentiate between null and undefined.
For instance, if null is a valid value for your property to have but undefined is not, in your example dothis() would still be called. You would prevent this with a typeof check.
if (typeof $scope.property === 'undefined') {
dothis();
}
Finally, if you are checking for the existence of a variable instead of the existence of a property, an exception will be thrown if the variable you are checking is not defined, forcing you to use a typeof check.
In those scenarios, verbosity is your friend.
This has to do with the concept of "truthiness". Any value besides false, 0, "", null, undefined, and NaN is "truthy" which means the first block of the if-statement will run. For instance:
if ("") {
alert("falsie"); // won't run because the empty string ("") is falsie
} else {
alert("truthie"); // will run
}
whereas
if ("something") {
alert("truthy"); // will run because "something" is truthy
} else {
alert("falsie"); // won't run
}
Going back to your example, if foo is truthy (meaning that it has ANY value other than false, 0, "", null, undefined, and NaN) then it will run the first block of the if-statement (which has the doSomething() function in it).
You could also use short circuit evaluation and do this in one line.
($scope.property && doThis())
It is better to use typeof if you need to explicitly check whether the value is undefined or not. If you just want to check if the value is truthy, then you don't need typeof.
The reason the typeof operator is preferred is because it doesn't throw a ReferenceError exception when used with an undeclared variable.
However, it is important to note that variables initialized as null will return "object", so to avoid this issue, the following code is recommended:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
What you are checking this way is if foo is not:
false
Undefined
Null
+0, −0, or NaN
Empty String
More info here:
https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/
This way your function is only executed if foo is valid.
You may want to be more specific and check against a certain type with typeof.
var foo = 'foo';
if (typeof foo === 'string') { // true
doSomething();
}
The typeof operator returns a string indicating the type of the
unevaluated operand.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

I'm building a node scraper that uses cheerio to parse the DOM. This is more or a vanilla javascript question though. At one part of my scrape, I'm loading some content into a variable, then checking the variable's length, like so:
var theHref = $(obj.mainImg_select).attr('href');
if (theHref.length){
// do stuff
} else {
// do other stuff
}
This works just fine, until I came across a url for which $(obj.mainImg_select).attr('href') didn't exist. I assumed that my theHref.length check would account for this and skip through to the else: do other stuff statement, but instead I got:
TypeError: Cannot read property 'length' of undefined
What am I doing wrong here and how can I fix this?
You can check that theHref is defined by checking against undefined.
if (undefined !== theHref && theHref.length) {
// `theHref` is not undefined and has truthy property _length_
// do stuff
} else {
// do other stuff
}
If you want to also protect yourself against falsey values like null then check theHref is truthy, which is a little shorter
if (theHref && theHref.length) {
// `theHref` is truthy and has truthy property _length_
}
Why?
You asked why it happens, let's see:
The official language specificaion dictates a call to the internal [[GetValue]] method. Your .attr returns undefined and you're trying to access its length.
If Type(V) is not Reference, return V.
This is true, since undefined is not a reference (alongside null, number, string and boolean)
Let base be the result of calling GetBase(V).
This gets the undefined part of myVar.length .
If IsUnresolvableReference(V), throw a ReferenceError exception.
This is not true, since it is resolvable and it resolves to undefined.
If IsPropertyReference(V), then
This happens since it's a property reference with the . syntax.
Now it tries to convert undefined to a function which results in a TypeError.
There's a difference between an empty string "" and an undefined variable. You should be checking whether or not theHref contains a defined string, rather than its lenght:
if(theHref){
// ---
}
If you still want to check for the length, then do this:
if(theHref && theHref.length){
// ...
}
In addition to others' proposals, there is another option to handle that issue.
If your application should behave the same in case of lack of "href" attribute, as in case of it being empty, just replace this:
var theHref = $(obj.mainImg_select).attr('href');
with this:
var theHref = $(obj.mainImg_select).attr('href') || '';
which will treat empty string ('') as the default, if the attribute has not been found.
But it really depends, on how you want to handle undefined "href" attribute. This answer assumes you will want to handle it as if it was empty string.
If you aren't doing some kind of numeric comparison of the length property, it's better not to use it in the if statement, just do:
if(theHref){
// do stuff
}else{
// do other stuff
}
An empty (or undefined, as it is in this case) string will evaluate to false (just like a length of zero would.)
As has been discussed elsewhere, the .length property reference is failing because theHref is undefined. However, be aware of any solution which involves comparing theHref to undefined, which is not a keyword in JavaScript and can be redefined.
For a full discussion of checking for undefined variables, see Detecting an undefined object property and the first answer in particular.
You can simply check whether the element length is undefined or not just by using
var theHref = $(obj.mainImg_select).attr('href');
if (theHref){
//get the length here if the element is not undefined
elementLength = theHref.length
// do stuff
} else {
// do other stuff
}

What reason is there to use null instead of undefined in JavaScript?

I've been writing JavaScript for quite a long time now, and I have never had a reason to use null. It seems that undefined is always preferable and serves the same purpose programmatically. What are some practical reasons to use null instead of undefined?
I don't really have an answer, but according to Nicholas C. Zakas, page 30 of his book "Professional JavaScript for Web Developers":
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
At the end of the day, because both null and undefined coerce to the same value (Boolean(undefined) === false && Boolean(null) === false), you can technically use either to get the job done. However, there is right way, IMO.
Leave the usage of undefined to the JavaScript compiler.
undefined is used to describe variables that do not point to a reference. It is something that the JS compiler will take care for you. At compile time the JS engine will set the value of all hoisted variables to undefined. As the engine steps through the code and values becomes available the engine will assign respective values to respective variables. For those variables for whom it did not find values, the variables would continue to maintain a reference to the primitive undefined.
Only use null if you explicitly want to denote the value of a variable as having "no value".
As #com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing". If you are calling a non-existing property of an object, then you will get undefined. If I would make that property intentionally empty, then it must be null so you know that it's on purpose.
TLDR; Don't use the undefined primitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference. On the other hand, use null if and only if you intentionally want a variable to have "no value".
Sidebar: I, personally, avoid explicitly setting anything to undefined (and I haven't come across such a pattern in the many codebases/third party libs I've interacted with). Also, I rarely use null. The only times I use null is when I want to denote the value of an argument to a function as having no value, i.e.,:
function printArguments(a,b) {
console.log(a,b);
}
printArguments(null, " hello") // logs: null hello
null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.
That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.
Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simplifies things a lot. I never have to check if x === undefined || x === null, I can just check x === undefined. And if you're in the habit of using == or simply stuff like if(x) ... , stop it.
!x will evaluate to true for an empty string, 0, null, NaN - i.e. things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.
undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it has no value.
Everyone has their own way of coding and their own internal semantics, but over the years I have found this to be the most intuitive advice that I give people who ask this question: when in doubt, do what JavaScript does.
Let's say you are working with object properties like options for a jQuery plugin...ask yourself what value JavaScript gives a property that has yet to be defined -- the answer is undefined. So in this context, I would initialize these types of things with 'undefined' to be consistent with JavaScript (for variables, you can do var myVar; instead of var myVar = undefined;).
Now let's say you are doing DOM manipulation...what value does JavaScript assign to non-existent elements? The answer is null. This is the value I would initialize with if you are creating a placeholder variable that will later hold a reference to an element, document fragment, or similar that relates to the DOM.
If you're working with JSON, then a special case needs to be made: for undefined property values, you should either set them to "" or null because a value of undefined is not considered proper JSON format.
With this said, as a previous poster has expressed, if you find that you're initializing stuff with null or undefined more than once in a blue moon, then maybe you should reconsider how you go about coding your app.
You might adopt the convention suggested here, but there really is no good reason to. It is not used consistently enough to be meaningful.
In order to make the convention useful, you first must know that the called function follows the convention. Then you have to explicitly test the returned value and decide what to do. If you get undefined, you can assume that some kind of error occurred that the called function knew about. But if an error happened, and the function knew about it, and it is useful to send that out into the wider environment, why not use an error object? i.e. throw an error?
So at the end of the day, the convention is practically useless in anything other than very small programs in simple environments.
A few have said that it is ok to initialise objects to null. I just wanted to point out that destructuring argument defaults don't work with null. For example:
const test = ({ name } = {}) => {
console.log(name)
}
test() // logs undefined
test(null) // throws error
This requires performing null checks prior to calling the function which may happen often.
A useful property in null that undefined does not qualifies:
> null + 3
3
> undefined + 3
NaN
I use null when I want to 'turn off' a numeric value,
or to initialize some. My last use was manipulating css transform:
const transforms = { perspective : null, rotateX : null };
// if already set, increase, if not, set to x
runTimeFunction((x) => { trasforms.perspective += x; });
// still useful, as setting perspective to 0 is different than turning it off
runTimeFunction2((x) => { transforms.perspective = null; });
// toCss will check for 'null' values and not set then at all
runTimeFunction3(() => { el.style.transform = toCss(transforms); });
Not sure if I should use this property thought...
DOM nodes and elements are not undefined, but may be null.
The nextSibling of the last child of an element is null.
The previousSibling of the first child is null.
A document.getElementById reference is null if the element does not exist in the document.
But in none of these cases is the value undefined; there just is no node there.
Unknown variable: undefined.
Known variable yet no value: null.
You receive an object from a server, server_object.
You reference server_object.errj. It tells you it’s undefined. That means it doesn’t know what that is.
Now you reference server_object.err. It tells you it’s null. That means you’re referencing a correct variable but it’s empty; therefore no error.
The problem is when you declare a variable name without a value (var hello) js declares that as undefined: this variable doesn’t exist; whereas programmers mostly mean: “I’ve not given it a value yet”, the definition of null.
So the default behavior of a programmer—declaring a variable without a value as nothing—is at odds with js—declaring it as not existing. And besides, !undefined and !null are both true so most programmers treat them as equivalent.
You could of course ensure you always do var hello = null but most won’t litter their code as such to ensure type sanity in a deliberately loosely-typed language, when they and the ! operator treat both undefined and null as equivalent.
In JavaScript, the value null represents the intentional absence of any object value. null expresses a lack of identification, indicating that a variable points to no object.
The global undefined property represents the primitive value undefined.
undefined is a primitive value automatically assigned to variables.
undefined is meant to say that the reference is not existing.
I completely disagree that usage null or undefined is unnecessary.
undefined is thing which keeping alive whole prototype chaining process.
So compiler only with null can't check if this property just equal to null, or its not defined in endpoint prototype. In other dynamic typed languages(f.e. Python) it throws exception if you want access to not defined property, but for prototype-based languages compiler should also check parent prototypes and here are the place when undefined need most.
Whole meaning of using null is just bind variable or property with object which is singleton and have meaning of emptiness,and also null usage have performance purposes. This 2 code have difference execution time.
var p1 = function(){this.value = 1};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
p = new p1();
if(index > 50000000){
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)
var p2 = function(){this.value = 1, p.x = null};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
p = new p2();
if(index > 50000000){
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)
I'm working through this exact question right now, and looking at the following philosophy:
Any function that is intended to return a result should return null if it fails to find a result
Any function that is NOT intended to return a result implicitly returns undefined.
For me, this question is significant because anyone calling a function that returns a result should have no question as to whether to test for undefined vs null.
This answer does not attempt to address:
Property values of null vs undefined
Variables within your functions being null vs undefined
In my opinion, variables are your own business and not a part of your API, and properties in any OO system are defined and therefore should be defined with value different from what they would be if not defined (null for defined, undefined is what you get when accessing something that is not in your object).
Here's a reason: var undefined = 1 is legal javascript, but var null = 1 is a syntax error. The difference is that null is a language keyword, while undefined is, for some reason, not.
If your code relies on comparisons to undefined as if it's a keyword (if (foo == undefined) -- a very easy mistake to make) that only works because nobody has defined a variable with that name. All that code is vulnerable to someone accidentally or maliciously defining a global variable with that name. Of course, we all know that accidentally defining a global variable is totally impossible in javascript...
Just wanna add that with usage of certain javascript libraries, null and undefined can have unintended consequences.
For example, lodash's get function, which accepts a default value as a 3rd argument:
const user = {
address: {
block: null,
unit: undefined,
}
}
console.log(_.get(user, 'address.block', 'Default Value')) // prints null
console.log(_.get(user, 'address.unit', 'Default Value')) // prints 'Default Value'
console.log(_.get(user, 'address.postalCode', 'Default Value')) // prints 'Default Value'
Another example: If you use defaultProps in React, if a property is passed null, default props are not used because null is interpreted as a defined value.
e.g.
class MyComponent extends React.Component {
static defaultProps = {
callback: () => {console.log('COMPONENT MOUNTED')},
}
componentDidMount() {
this.props.callback();
}
}
//in some other component
<MyComponent /> // Console WILL print "COMPONENT MOUNTED"
<MyComponent callback={null}/> // Console will NOT print "COMPONENT MOUNTED"
<MyComponent callback={undefined}/> // Console WILL print "COMPONENT MOUNTED"
There are already some good answers here but not the one that I was looking for. null and undefined both "technically" do the same thing in terms of both being falsy, but when I read through code and I see a "null" then I'm expecting that it's a user defined null, something was explicitly set to contain no value, if I read through code and see "undefined" then I assume that it's code that was never initialized or assigned by anything. In this way code can communicate to you whether something was caused by uninitialized stuff or null values. Because of that you really shouldn't assign "undefined" manually to something otherwise it messes with the way you (or another developer) can read code. If another developer sees "undefined" they're not going to intuitively assume it's you who made it undefined, they're going to assume it's not been initialized when in fact it was. For me this is the biggest deal, when I read code I want to see what it's telling me, I don't want to guess and figure out if stuff has "actually" been initialized.
Not even to mention that using them in typescript means two different things. Using:
interface Example {
name?: string
}
Means that name can be undefined or a string, but it can't be null. If you want it null you have to explicitly use:
interface Example {
name: string | null
}
And even then you'll be forced to initialize it at least with "null".
That's of course only true if you're using "strictNullChecks": true in tsconfig.json.
Based on a recent breakage we ran into, the example below shows why I prefer to use undefined over null, unless there is a specific reason to do otherwise:
function myfunc (myArg) {
if (typeof myArg === 'string') {
console.log('a', myArg);
} else if (typeof abc === 'object') {
console.log('b', myArg);
if (myArg.id) {
console.log('myArg has an id');
} else {
console.log('myArg has an id');
}
} else {
console.log('no value');
}
}
The following values will play nicely:
'abc'
{}
undefined
{ id: 'xyz' }
On the other hand the assumption of null and undefined being equivalent here breaks the code. The reason being is that null is of type of object, where as undefined is of type undefined. So here the code breaks because you can't test for a member on null.
I have seen a large number of cases with code of similar appearance, where null is just asking for problems:
if (typeof myvar === 'string') {
console.log(myvar);
} else if (typeof myvar === 'object') {
console.log(myvar.id);
}
The fix here would be to explicitly test for null:
if (typeof myvar === 'string') {
console.log(myvar);
} else if (myvar !== null && typeof myvar === 'object') {
console.log(myvar.id);
}
My attitude is to code for the weaknesses of a language and the typical behaviours of programmers of that language, hence the philosophy here of going with 'undefined' bey default.
To write simple code you need to keep complexity and variation down. When a variable or a property on an object does not have a value it is undefined , and for a value to be null you need to assign it a null value.
Undeclared vs Null
null is both an Object "type" and one of the 7 unique primitive value types called null
undefined is both a global scope property and type called undefined and one of the 7 unique primitive value types called undefined (window.undefined) .
It is the primitive types we use as values we are interested in.
In the case of null, as a value type it means an empty value has been assigned to a variable, but the variable type (Number, String, etc) is still defined. It just has no value. That is what null means. It means a variable has an empty value but it is still a value. It also reinitializes the variable with some kind of value, but is not undefined as a type.
undefined is a special case. When you declare a variable (or use a missing value not yet declared) it is of type undefined, as the browser does not know what type of data has been assigned to it yet. If the variable is declared but not assigned a value is is assigned the primitive calue undefined by default prior to assigning a value, and implies the variable does not exist or exists but has no value assigned.
Like null, undefined is also a primitive value type. But unlike null it means the variable does not exist, where null means the value does not exist. That is why its always better to check if the variable exists and has been assigned a variable using undefined before checking if the value is null or empty. undefined implies no variable or object exists in the compilation at all. The variable has either not been declared or declared with a missing value so not initialized. So checking for undefined is a very good way to avoid many types of errors in JavaScript and supersedes null.
That is why I would not rely on "truthy" checks for true/false with null and undefined, even though they will both return a false response, as undefined implies an additional step for missing feature, object, or variable, not just a true/false check. It implies something more. If you have a missing undeclared variable, truthy statements will trigger an ERROR!
Let's look at undefined first:
//var check1;// variable doesnt even exist so not assigned to "undefined"
var check2;// variable declared but not initialized so assigned "undefined"
var check3 = 'hello world';// variable has a value so not undefined
console.log('What is undefined?');
//console.log(check1 === undefined);// ERROR! check1 does not exist yet so not assigned undefined!
console.log(check2 === undefined);// True
console.log(check3 === undefined);// False
console.log(typeof check1 === 'undefined');// True - stops the ERROR!
console.log(typeof check2 === 'undefined');// True
console.log(typeof check3 === 'undefined');// False
As you can see undeclared variables, or declared but not initialized, both are assigned a type of undefined. Notice declared variables that are not initialized are assigned a value of undefined, the primitive value type but variables that do not exist are undefined types.
null has nothing to do with missing variables or variables not yet assigned values, as null is still a value. So anything with a null is already declared and initialized. Also notice a variable assigned a null value is actually an object type unlike undefined types. For example...
var check4 = null;
var check5 = 'hello world';
console.log('What is null?');
console.log(check4 === undefined);// False
console.log(check5 === undefined);// False
console.log(typeof check4 === 'undefined');// False
console.log(typeof check5 === 'undefined');// False
console.log(typeof check4);// return 'object'
console.log(typeof check5);// return 'string'
As you can see each act differently and yet both are primitive values you can assign any variable. Just understand they represent different states of variables and objects.

Why is null an object and what's the difference between null and undefined?

Why is null considered an object in JavaScript?
Is checking
if ( object == null )
Do something
the same as
if ( !object )
Do something
?
And also:
What is the difference between null and undefined?
(name is undefined)
You: What is name? (*)
JavaScript: name? What's a name? I don't know what you're talking about. You haven't ever mentioned any name before. Are you seeing some other scripting language on the (client-)side?
name = null;
You: What is name?
JavaScript: I don't know.
In short; undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it's not known what the value is.
One thing to remember is that null is not, conceptually, the same as false or "" or such, even if they equate after type casting, i.e.
name = false;
You: What is name?
JavaScript: Boolean false.
name = '';
You: What is name?
JavaScript: Empty string
*: name in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.
The difference can be summarized into this snippet:
alert(typeof(null)); // object
alert(typeof(undefined)); // undefined
alert(null !== undefined) //true
alert(null == undefined) //true
Checking
object == null is different to check if ( !object ).
The latter is equal to ! Boolean(object), because the unary ! operator automatically cast the right operand into a Boolean.
Since Boolean(null) equals false then !false === true.
So if your object is not null, but false or 0 or "", the check will pass
because:
alert(Boolean(null)) //false
alert(Boolean(0)) //false
alert(Boolean("")) //false
null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object". But that is actually a bug (that might even be fixed in ECMAScript 6).
The difference between null and undefined is as follows:
undefined: used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value.
> var noValueYet;
> console.log(noValueYet);
undefined
> function foo(x) { console.log(x) }
> foo()
undefined
> var obj = {};
> console.log(obj.unknownProperty)
undefined
Accessing unknown variables, however, produces an exception:
> unknownVariable
ReferenceError: unknownVariable is not defined
null: used by programmers to indicate “no value”, e.g. as a parameter to a function.
Examining a variable:
console.log(typeof unknownVariable === "undefined"); // true
var foo;
console.log(typeof foo === "undefined"); // true
console.log(foo === undefined); // true
var bar = null;
console.log(bar === null); // true
As a general rule, you should always use === and never == in JavaScript (== performs all kinds of conversions that can produce unexpected results). The check x == null is an edge case, because it works for both null and undefined:
> null == null
true
> undefined == null
true
A common way of checking whether a variable has a value is to convert it to boolean and see whether it is true. That conversion is performed by the if statement and the boolean operator ! (“not”).
function foo(param) {
if (param) {
// ...
}
}
function foo(param) {
if (! param) param = "abc";
}
function foo(param) {
// || returns first operand that can't be converted to false
param = param || "abc";
}
Drawback of this approach: All of the following values evaluate to false, so you have to be careful (e.g., the above checks can’t distinguish between undefined and 0).
undefined, null
Booleans: false
Numbers: +0, -0, NaN
Strings: ""
You can test the conversion to boolean by using Boolean as a function (normally it is a constructor, to be used with new):
> Boolean(null)
false
> Boolean("")
false
> Boolean(3-3)
false
> Boolean({})
true
> Boolean([])
true
What is the difference between null and undefined??
A property when it has no definition is undefined. a null is an object. Its type is object. null is a special value meaning "no value. undefined is not an object, its type is undefined.
You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
undefined == null
null == undefined
Refer to JavaScript Difference between null and undefined for more detail.
and with your new edit yes
if (object == null) does mean the same if(!object)
when testing if object is false, they both only meet the condition when testing if false, but not when true
Check here: Javascript gotcha
First part of the question:
Why is null considered an object in JavaScript?
It is a JavaScript design error they can't fix now. It should have been type null, not type object, or not have it at all. It necessitates an extra check (sometimes forgotten) when detecting real objects and is source of bugs.
Second part of the question:
Is checking
if (object == null)
Do something
the same as
if (!object)
Do something
The two checks are always both false except for:
object is undefined or null: both true.
object is primitive, and 0, "", or false: first check false, second true.
If the object is not a primitive, but a real Object, like new Number(0), new String(""), or new Boolean(false), then both checks are false.
So if 'object' is interpreted to mean a real Object then both checks are always the same. If primitives are allowed then the checks are different for 0, "", and false.
In cases like object==null, the unobvious results could be a source of bugs. Use of == is not recommended ever, use === instead.
Third part of the question:
And also:
What is the difference between null and undefined?
In JavaScript, one difference is that null is of type object and undefined is of type undefined.
In JavaScript, null==undefined is true, and considered equal if type is ignored. Why they decided that, but 0, "" and false aren't equal, I don't know. It seems to be an arbitrary opinion.
In JavaScript, null===undefined is not true since the type must be the same in ===.
In reality, null and undefined are identical, since they both represent non-existence. So do 0, and "" for that matter too, and maybe the empty containers [] and {}. So many types of the same nothing are a recipe for bugs. One type or none at all is better. I would try to use as few as possible.
'false', 'true', and '!' are another bag of worms that could be simplified, for example, if(!x) and if(x) alone are sufficient, you don't need true and false.
A declared var x is type undefined if no value is given, but it should be the same as if x was never declared at all. Another bug source is an empty nothing container. So it is best to declare and define it together, like var x=1.
People are going round and round in circles trying to figure out all these various types of nothing, but it's all just the same thing in complicated different clothes. The reality is
undefined===undeclared===null===0===""===[]==={}===nothing
And maybe all should throw exceptions.
TLDR
undefined is a primitive value in JavaScript that indicates the implicit absence of a value. Uninitialized variables automatically have this value, and functions without an explicit return statement, return undefined.
null is also a primitive value in JavaScript. It indicates the intentional absence of an object value. null in JavaScript was designed to enable interoperability with Java.
typeof null returns "object" because of a peculiarity in the design of the language, stemming from the demand that JavaScript be interoperable with Java. It does not mean null is an instance of an object. It means: given the tree of primitive types in JavaScript, null is part of the "object-type primitive" subtree. This is explained more fully below.
Details
undefined is a primitive value that represents the implicit absence of a value. Note that undefined was not directly accessible until JavaScript 1.3 in 1998. This tells us that null was intended to be the value used by programmers when explicitly indicating the absence of a value. Uninitialized variables automatically have the value undefined. undefined is a one-of-a-kind type in the ECMAScript specification.
null is a primitive value that represents the intentional absence of an object value. null is also a one-of-a-kind type in the ECMAScript specification.
null in JavaScript was designed with a view to enable interoperability with Java, both from a "look" perspective, and from a programmatic perspective (eg the LiveConnect Java/JS bridge planned for 1996). Both Brendan Eich and others have since expressed distaste at the inclusion of two "absence of value" values, but in 1995 Eich was under orders to "make [JavaScript] look like Java".
Brendan Eich:
If I didn't have "Make it look like Java" as an order from management,
and I had more time (hard to unconfound these two causal factors), then I would have preferred a Self-like "everything's an object"
approach: no Boolean, Number, String wrappers. No undefined and null.
Sigh.
In order to accommodate Java's concept of null which, due to the strongly-typed nature of Java, can only be assigned to variables typed to a reference type (rather primitives), Eich chose to position the special null value at the top of the object prototype chain (i.e. the top of the reference types), and to include the null type as part of the set of "object-type primitives".
The typeof operator was added shortly thereafter in JavaScript 1.1, released on 19th August 1996.
From the V8 blog:
typeof null returns object, and not null, despite null being a
type of its own. To understand why, consider that the set of all
JavaScript types is divided into two groups:
objects (i.e. the Object type)
primitives (i.e. any non-object value)
As such, null means “no object value”, whereas undefined means “no
value”.
Following this line of thought, Brendan Eich designed JavaScript to
make typeof return 'object' for all values on the right-hand side,
i.e. all objects and null values, in the spirit of Java. That’s why
typeof null === 'object' despite the spec having a separate null type.
So Eich designed the hierarchy of primitive types to enable interoperability with Java. This led to him positioning null along with the "object-type primitives" on the hierarchy. To reflect this, when typeof was added to the language shortly thereafter, he chose typeof null to return "object".
The surprise expressed by JavaScript developers at typeof null === "object" is the result of an impedance mismatch (or abstraction leak) between a weakly-typed language (JavaScript) that has both null and undefined, and another, strongly-typed language (Java) that only has null, and in which null is strictly defined to refer to a reference type (not a primitive type).
Note that this is all logical, reasonable and defensible. typeof null === "object" is not a bug, but a second-order effect of having to accommodate Java interoperability.
A number of imperfect backwards rationalisations and/or conventions have emerged, including that undefined indicates implicit absence of a value, and that null indicates intentional absence of a value; or that undefined is the absence of a value, and null is specifically the absence of an object value.
A relevant conversation with Brendan Eich, screenshotted for posterity:
typeof null; // object
typeof undefined; // undefined
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.
var x = null;
var y;
x is declared & defined as null
y is declared but not defined. It is declared with no value so it is undefined.
z is not declared so would also be undefined if you attempted to use z.
One way to make sense of null and undefined is to understand where each occurs.
Expect a null return value in the following situations:
Methods that query the DOM
console.log(window.document.getElementById("nonExistentElement"));
//Prints: null
JSON responses received from an Ajax request
{
name: "Bob",
address: null
}
RegEx.exec.
New functionality that is in a state of flux. The following returns null:
var proto = Object.getPrototypeOf(Object.getPrototypeOf({}));
// But this returns undefined:
Object.getOwnPropertyDescriptor({}, "a");
All other cases of non-existence are denoted by undefined (as noted by #Axel). Each of the following prints "undefined":
var uninitalised;
console.log(uninitalised);
var obj = {};
console.log(obj.nonExistent);
function missingParam(missing){
console.log(missing);
}
missingParam();
var arr = [];
console.log(arr.pop());
Of course if you decide to write var unitialised = null; or return null from a method yourself then you have null occurring in other situations. But that should be pretty obvious.
A third case is when you want to access a variable but you don't even know if it has been declared. For that case use typeof to avoid a reference error:
if(typeof unknown !== "undefined"){
//use unknown
}
In summary check for null when you are manipulating the DOM, dealing with Ajax, or using certain ECMAScript 5 features. For all other cases it is safe to check for undefined with strict equality:
if(value === undefined){
// stuff
}
Comparison of many different null checks in JavaScript:
http://jsfiddle.net/aaronhoffman/DdRHB/5/
// Variables to test
var myNull = null;
var myObject = {};
var myStringEmpty = "";
var myStringWhiteSpace = " ";
var myStringHello = "hello";
var myIntZero = 0;
var myIntOne = 1;
var myBoolTrue = true;
var myBoolFalse = false;
var myUndefined;
...trim...
http://aaron-hoffman.blogspot.com/2013/04/javascript-null-checking-undefined-and.html
To add to the answer of What is the differrence between undefined and null, from JavaScript Definitive Guide 6th Edition, p.41 on this page:
You might consider undefined to represent system-level, unexpected,
or error-like absense of value and null to represent program-level,
normal, or expected absence of value. If you need to assign one of
these values to a variable or property or pass one of these values to
a function, null is almost always the right choice.
null and undefined are both false for value equality (null==undefined): they both collapse to boolean false. They are not the same object (null!==undefined).
undefined is a property of the global object ("window" in browsers), but is a primitive type and not an object itself. It's the default value for uninitialized variables and functions ending without a return statement.
null is an instance of Object. null is used for DOM methods that return collection objects to indicate an empty result, which provides a false value without indicating an error.
Some precisions:
null and undefined are two different values. One is representing the absence of a value for a name and the other is representing the absence of a name.
What happens in an if goes as follows for if( o ):
The expression in the parentheses o is evaluated, and then the if kicks in type-coercing the value of the expression in the parentheses - in our case o.
Falsy (that will get coerced to false) values in JavaScript are: '', null, undefined, 0, and false.
The following function shows why and is capable for working out the difference:
function test() {
var myObj = {};
console.log(myObj.myProperty);
myObj.myProperty = null;
console.log(myObj.myProperty);
}
If you call
test();
You're getting
undefined
null
The first console.log(...) tries to get myProperty from myObj while it is not yet defined - so it gets back "undefined". After assigning null to it, the second console.log(...) returns obviously "null" because myProperty exists, but it has the value null assigned to it.
In order to be able to query this difference, JavaScript has null and undefined: While null is - just like in other languages an object, undefined cannot be an object because there is no instance (even not a null instance) available.
For example window.someWeirdProperty is undefined, so
"window.someWeirdProperty === null" evaluates to false while
"window.someWeirdProperty === undefined" evaluates to true.
Moreover checkif if (!o) is not the same as checking if (o == null) for o being false.
In Javascript null is not an object type it is a primitave type.
What is the difference?
Undefined refers to a pointer that has not been set.
Null refers to the null pointer for example something has manually set a variable to be of type null
Look at this:
<script>
function f(a){
alert(typeof(a));
if (a==null) alert('null');
a?alert(true):alert(false);
}
</script>
//return:
<button onclick="f()">nothing</button> //undefined null false
<button onclick="f(null)">null</button> //object null false
<button onclick="f('')">empty</button> //string false
<button onclick="f(0)">zero</button> //number false
<button onclick="f(1)">int</button> //number true
<button onclick="f('x')">str</button> //string true
From "The Principles of Object-Oriented Javascript" by Nicholas C. Zakas
But why an object when the type is null? (In fact, this has been acknowledged as an error by TC39, the committee that designs and maintains JavaScript. You could reason that null is an empty object pointer, making "object" a logical return value, but that’s still confusing.)
Zakas, Nicholas C. (2014-02-07). The Principles of Object-Oriented JavaScript (Kindle Locations 226-227). No Starch Press. Kindle Edition.
That said:
var game = null; //typeof(game) is "object"
game.score = 100;//null is not an object, what the heck!?
game instanceof Object; //false, so it's not an instance but it's type is object
//let's make this primitive variable an object;
game = {};
typeof(game);//it is an object
game instanceof Object; //true, yay!!!
game.score = 100;
Undefined case:
var score; //at this point 'score' is undefined
typeof(score); //'undefined'
var score.player = "felix"; //'undefined' is not an object
score instanceof Object; //false, oh I already knew that.
null is an object. Its type is null. undefined is not an object; its type is undefined.
The best way to think about 'null' is to recall how the similar concept is used in databases, where it indicates that a field contains "no value at all."
Yes, the item's value is known; it is 'defined.' It has been initialized.
The item's value is: "there is no value."
This is a very useful technique for writing programs that are more-easily debugged. An 'undefined' variable might be the result of a bug ... (how would you know?) ... but if the variable contains the value 'null,' you know that "someone, somewhere in this program, set it to 'null.'" Therefore, I suggest that, when you need to get rid of the value of a variable, don't "delete" ... set it to 'null.' The old value will be orphaned and soon will be garbage-collected; the new value is, "there is no value (now)." In both cases, the variable's state is certain: "it obviously, deliberately, got that way."
The other fun thing about null, compared to undefined, is that it can be incremented.
x = undefined
x++
y = null
y++
console.log(x) // NaN
console.log(y) // 0
This is useful for setting default numerical values for counters. How many times have you set a variable to -1 in its declaration?
Undefined means a variable has been declared but it has not been assigned any value while Null can be assigned to a variable representing "no value".(Null is an assignment operator)
2.Undefined is a type itself while Null is an object.
3.Javascript can itself initialize any unassigned variable to undefined but it can never set value of a variable to null. This has to be done programatically.
What is a type?
A type is a way to categorize values. Here is a table with the types in question and their typeof result.
Type
Values type contains
typeof result
Is typeof result a lie?
Undefined
Only: undefined
"undefined"
No
Null
Only: null
"object"
Yes
Object
Infinite amount of values: {}, {a: "b"}, ...
"object"
No
null is not an object, its a value of type Null.
The typeof operator is lying! It returning "object" for null is a mistake in the JavaScript language.
I wrote a chapter about this in my open-source e-book. You can read it here https://github.com/carltheperson/advanced-js-objects
Use null to define something as having no value, use undefined when you expect something might not be defined at all.
For example, if a variable has no value, assign it as null.
var weDontHaveAValue = null;
If you expect that something might be not defined at all, e.g. an optional options argument, use undefined.
if (typeof args.optionalParam !== 'undefined') { }
The main difference between null and undefined is that null represents
a missing object, while undefined represents an uninitialized state of a variable.
You can think of null as an undefined object but undefined will be undefined only
since its type is undefined.
let a;
console.log(a); //undefined, since it is declared but not initialized
console.log(null == undefined) //true
console.log(null === undefined) // false
console.log(typeof null) //object
console.log(typeof undefined) //undefined
Not defined and undefined are not the same thing happening.
age;
You: What is the value of age?
Computer: Okay, let me check my memory/reference table..... at this point (the time of you asking), i do not see any identifier named age, not in this scope/context or any parent scope/context; age is not known to me. Maybe later i will come across an instruction to add that identifier to memory, but it does not exist right now.
var age;
You: What is the value of age;
Computer: Okay, checking my memory... I see an identifier in my reference table with that name age but no value or pointer or anything was assigned to it at the time i added it, so i don't know; you can consider it (age) empty/nothing/useless.
var age = null;
You: What is the value of age;
Computer: Okay, checking my memory... i see age in my reference table: it is null. Basically, it is nothing/empty, you cannot do anything with this value; this was intentional.
Now, i probably should not explain it this way but hopefully it will make sense.
I can see why null was designed to be an object in JS, and i personally like it that way.
null and undefined practically means the same thing: empty/nothing. The difference is in how it is used conceptually.
I look at null as developer-intended nothingness; something being null was done on purpose to represent nothing. I look at undefined as computer-intended nothingness; something not having value by accident of the developer/user.
For example, if you call a function from a library/sdk and got back null, you can almost be sure that was designed on purpose by the developer/author; they specifically wanted to indicate nothingness.
Also see - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null

Categories

Resources