6

I had a code problem when testing if some vars are empty or not, and decide to test it in a fiddle:

Testing null values

var result = "";
var Teste = new Object();
Teste.ObjectNew = new Object();
Teste.StringNew = new String();
Teste.NumberNew = new Number();
Teste.ArrayNew = new Array();
Teste.ObjectLiteral = {};
Teste.StringLiteral = "";
Teste.NumberLiteral = 0;
Teste.ArrayLiteral = [];
Teste.ObjectNull = Object(null);
Teste.StringNull = String(null);
Teste.NumberNull = Number(null);
Teste.ArrayNull = [null];
for (var i in Teste) {
  if (Teste[i] == null) {
    result += "<p>Type " + i + " is null: " + Teste[i] + "</p>";
  } else {
    result += "<p>Type " + i + " is not null: " + Teste[i] + "</p>";
  }
}

document.getElementById("result").innerHTML = result;
<div id="result"></div>

The result is:

Type ObjectNew is not null: [object Object]

Type StringNew is not null:

Type NumberNew is not null: 0

Type ArrayNew is not null:

Type ObjectLiteral is not null: [object Object]

Type StringLiteral is not null:

Type NumberLiteral is not null: 0

Type ArrayLiteral is not null:

Type ObjectNull is not null: [object Object]

Type StringNull is not null: null

Type NumberNull is not null: 0

Type ArrayNull is not null:

I tested in Safari, same result.

I was coding in php altogether with JS and had problems in adjust my mind. In php, $var = array() returns NULL, but in JavaScript it seams there is never null value at any type. In EcmaScript definition, null is "primitive value that represents the intentional absence of any object value", but it seams impossible in JavaScript at list by my tests, excluding the case of v = null that i think is a Null type of var.

In addition, I believe AS3 follow the ecmascript concept by split type of for from it's values, the var statement "build" a var as an object apart from values.

So how do we correctly refer to a null value, if there is a way to?

EDIT

I did this test when I had this situation: I created a variable that has the relative directory of a graphic library. If this variable is null, it means I don't wish to change it from the default value (I have a table with default values) during initializing phase of my software, so the system just add the proper http base for the directory. If the variable is not null, it will assume the value was just assigned to it. But if it is an empty space, it means the directory is the root, but will be taken as null, generating an error.

Dinamyc:

var dir = new String(); // should be null
// initializing
dir = ""; // the directory will be the root
// finish ini
if(dir==null) … // assume the default value, but this doesn't work, so how can I know?
Gustavo
  • 1,673
  • 4
  • 24
  • 39
  • 2
    *"In php, $var = array() returns NULL"* I doubt that. `$var` should be an empty array. In JavaScript, as in PHP (I believe), `null` is very specific value. Why would you think that `null` should be equal to an empty string or an empty array? – Felix Kling Sep 24 '14 at 03:19
  • I did a test, $var==NULL returns TRUE. – Gustavo Sep 24 '14 at 11:52
  • Can't test right now, but I guess PHP performes **type conversion**. That's one of the reasons why you should basically always use **strict comparison** (`===`), in PHP as well as in JavaScript – Felix Kling Sep 24 '14 at 13:15
  • In JS it's actually ok to use loose comparison to test for null (`x == null`), because it will only be true if `x` is either `null` or `undefined`. No type conversion takes place. However the comparison rules in PHP are different: http://php.net/manual/en/types.comparisons.php – Felix Kling Sep 24 '14 at 13:21

3 Answers3

3

In EcmaScript definition, null is "primitive value that represents the intentional absence of any object value", but it seams impossible in JavaScript at list by my tests, excluding the case of v = null that i think is a Null type of var.

Well, all the test cases in your test had a value. I'm not sure why you did exclude

Teste.Null = null;

but it would have worked for it. Also, a Teste.Undefined = undefined would be compare as equal to null.

var result = "";
var Teste = {
    Null: null,
    Undefined: undefined,
    ObjectNew: new Object(),
    StringNew: new String(),
    NumberNew: new Number(),
    ArrayNew: new Array(),
    ObjectLiteral: {},
    StringLiteral: "",
    NumberLiteral: 0,
    ArrayLiteral: [],
    ObjectNull: Object(null),
    StringNull: String(null),
    NumberNull: Number(null),
    ArrayNull: [null]
}
for (var i in Teste) {
    result += "<p>Type "+i+" is"+(Teste[i] == null?"":" not")+" null: "+Teste[i]+"</p>";
}

document.getElementById("result").innerHTML = result;
<div id="result"></div>

So how do we correctly refer to a null value, if there is a way to?

Use the value null. Don't wrap it in anything, or you'd get a wrapper around it (e.g. your array [null]).

If you want to test arrays ([]) or strings ("") for their emptyness (which is a different concept than non-existance of the value), you should check for their .length to be 0.

var dir = new String(); // should be null

No. You've created a Wrapper object (which you never should need) around an empty string here (which you don't seem to want). To declare a variable, but not initialise it, just use

var dir;

or

var dir = null;

and then they will have the value undefined or null, which both are == null in your if-condition.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Do you realize that you're using undefined type of var or null type to "emulate" a null value? To had a value or not is conceptual (0 == null?) Cool this discussion, but maybe I opened a to conceptual question to this forum. And I think you're close to the answer: there is no null value in JavaScript, we may emulate it. See that at the end, we don't know if dir is a String, as JS allow type mutation, we can use it, but we should register in a comment about, or it might generate confusion or even errors. – Gustavo Sep 24 '14 at 14:11
  • I'm not sure what your understanding of a "null value" is, apparently you don't mean JavaScript's `null` value. Are you looking for something like "nullable types" or `Option`? Yes, a comment would be appropriate if plan to leave a variable `undefined`, but explicitly assigning `null` should be enough. – Bergi Sep 24 '14 at 14:21
  • Related: [What is the difference between null and undefined in JavaScript?](http://stackoverflow.com/q/5076944/1048572) and [Why is null an object and what's the difference between null and undefined?](http://stackoverflow.com/q/801032/1048572) – Bergi Sep 24 '14 at 14:30
  • My understanding of a null value were formed when coding in php and AS3, I came to JavaScript (as a language) later and with some pre-concepts. This one was wrong, the only variable that allow null value is Null type, in JavaScript. I check your answer as right because I think other programers will solve their problems by my question and your answer, but I think you seams a little "closed". My suggestion is you read again the EcmaScript concept of a null value. Also, I see the String Wrapper Object as a constructor, I should change my glasses before code in JS! – Gustavo Sep 24 '14 at 15:39
  • I don't think null values are so different in these languages (altough I don't know AS), only [PHP has weirder equality](http://stackoverflow.com/q/8236354/1048572) than JavaScript when using loose typing. In Js, you wouldn't compare to `null` to recognize `0` or `""`, you'd just use them as booleans - they're "falsy" values. Yes, my answer is based solely on the ES spec :-) – Bergi Sep 24 '14 at 16:18
  • In AS3 and PHP is possible to create an object with null value, so a == comparison with null as result doesn't mean the type is undefined. As you answered, JavaScript see null not as a "value object" as defined by ES, but as result of the fact that type is undefined (you don't know the kind of bottle were create therefore can't initialize a value, than is null). If the type is defined, a initial value is assigned, as you said, it will never be empty. There isn't much difference when doing the daily code, but means a lot as a conception. – Gustavo Sep 26 '14 at 17:21
1

In JavaScript, null is a special value an object (yes, object - the type of null is object) can have that represents it having no value - this is distinct from it being empty. You can think of {} (empty object) as an empty glass, while null would mean that the glass doesn't even exist. It's also distinct from the variable not being defined at all - when a variable is defined, but set to null, it has a place "reserved" to put the glass (or possibly something else) at some point, but right now that space is not occupied.

As for your test, comparing with either '', 0 or false will give you the is null messages (only when using == and not === for comparison of course). If that's what you're trying to achieve, probably the "proper" (easiest to understand) way to check if a variable has zero or empty value (similar to PHP's empty) is if (!variable) ...

fstanis
  • 5,234
  • 1
  • 23
  • 42
  • Yes, I use (!variable) to detect a null value (e.g.: arguments of a function) but is very generic as is a conversion to false. I was thinking if there is something like varName:String = null (a real null String), but it seams JS doesn't follow this methodology, right? – Gustavo Sep 24 '14 at 01:51
  • To my knowledge, there is no such thing, but I'm not sure I understand in which situation would a null string be useful (or rather, in which situation should a null string differ from an empty string in a weakly typed language)? – fstanis Sep 24 '14 at 01:54
  • To test that a value is really is null instead of "falsy" use the `===` operator: `var foo = null; console.log(foo === null)` – slebetman Sep 24 '14 at 04:01
  • fstanis: I had some situations I need to know if the user actually want to use some text box. I down't know if he want that box leaved empty (he want, but not now) or he don't want the box at all. The solution is to put a checkbox instead of null button in the side, another var the will storage the null information. – Gustavo Sep 24 '14 at 12:27
-1

==== edit ====

ok, my bad, undefined means its unitialized, and null means it points to nothing, has no value.

http://www.2ality.com/2013/10/typeof-null.html

==== /edit ====

there are no such thing as null-string, or null-type. null has no type, it means the variable is not initialized, in other words the variable points to nowhere. any kind of uninitialized variable is null. like pointers in c++. a pointer can point to any type, but if its uninitialized it points to a quasi random place in memory.

SomeType* myVar;

its not null, if you use this object you mess things up big time and you have no way to tell if its a valid pointer, or not.

SomeType* myVar = 0;

this way you can tell that this is an uninitialized pointer by simply check if its 0 or not.

in higher level languages you don't have to deal with these issues directly so

var something:AnyObjectType;

is automatically null, a.k.a. uninitialized.

to test whether a string or an array is empty or not is an other question. in php $var = array(); if($var) evaluates to true, since its an actual object, not null. empty($var) would be the check you use to see if the array actually has any content. in js this would be if(myArray && myArray.length) to see if its a living object and to see if it has content.

strings could be more tricky, since a string with only whitespace in it is a completely valid object with actual content, yet you would consider it empty in most use-cases.

prizma
  • 57
  • 3
  • 1
    No, `null` does not mean the variable is not initialized. An uninitialized variable is undefined. Null is a value something can have. –  Sep 24 '14 at 11:47
  • torazaburo is right, however, it seams JavaScript does not have the "ability" of store null values in variables. Undefined we know well, when we forgot to create the var or is not in the scope and it shows up in the middle of our beautiful layout, right... – Gustavo Sep 24 '14 at 12:09
  • `null` has the `Null` type, which is different from `undefined` (and its type). And no, you cannot compare JS to null pointers or uninitialised C++ variables. – Bergi Sep 24 '14 at 12:38
  • yeah, my mistake, uninitialized is not null, sorry. – prizma Sep 26 '14 at 12:15
  • @Bergi however one can compare the 2 things, and should too, since the whole point of null and undefined in JS is to deal with the underlying problem/issue which is the same. the js engine doesn't have some magical way to deal with memory. – prizma Sep 26 '14 at 12:25
  • @prizma: I thought you actually read that article. Null is a type, and [`typeof` gets it wrong](http://es5.github.io/#x11.4.3) – Bergi Sep 26 '14 at 12:53
  • @Bergi well, I posted the article to show that talking about pointers in relation with JS is a valid argument :) null-type is a thing, you are right, and I was wrong, but from JS perspective it makes no difference, you would never declare a variable like var something:Null, since NullType has only one possible value... Any var which holds a null value becomes JSTYPE_NULL in the engine, but its a js-engine implementation thing, and as you said before it makes no sense to talk about c in relation with JS... :) – prizma Sep 26 '14 at 13:35