Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 2, 2022 11:20 pm GMT

You don't need null

While a lot of programming languages that have a "nullish" type (null, nil, etc.) debate about avoiding it, JavaScript is the only popular one that has two, you read that right, two nullish types. One of the most common recommendations is to stick to using only one, and my recommendation is to only use undefined and avoid null. In this article, we will go over the reasons you might also want to avoid null in JavaScript and TypeScript.

The nullish that the language uses

As Douglas Crockford put it in one of his talks, JavaScript itself uses undefined all the time, so let's use the one the language uses:

let something; // This is undefined!const otherThing = {    foo: "hi",};otherThing.bar; // This is also undefinedconst aFunction = anArgument => {    // anArgument here is undefined if no value is passed};

To use null on all those scenarios, we need to explicitly set the values to null, which will look like this:

let something = null;const otherThing = {    foo: "hi",    bar: null,};const aFunction = (anArgument = null) => {};

I don't know about you, but for me...

That's undefined with extra steps

What if I want to define a nullish value intentionally?

In that case, just assign undefined to it:

const anObject = {    ...otherObject,    propertyToNullify: undefined,};

That nasty bug with the type of null

We all know at this point about the bug with typeof null, that bug doesn't apply to undefined which works as expected:

typeof null; // "object" typeof undefined; // "undefined" 

Why would we use a bugged value intentionally?

Smaller API responses

API response sizes are reduced drastically if we rely on undefined instead of null. Here's a response example using null:

{    "foo": "foo",    "bar": null}

Versus with undefined:

{    "foo": "foo"}

The case with Array

Array is a special case, because when we create a new array of a given size, the items inside said array are actually empty, not undefined. This empty means that if you check for their value, it will give you undefined, but they aren't taking any space in memory (performance reasons), so if you try to loop over it, it will give you nothing:

const array = new Array(3); // [empty, empty, empty]array[0] === undefined; // truearray.map(console.log); // nothing logs 

The arguments in favor of null

When I say that you don't need null, folks that use it a lot (generally coming from other languages that have null as the only nullish value) get pretty mad about such claims. The most common response I get is:

null is for intentional missing values, and undefined should be used when the values were never set in the first place.

The first thing I think with responses like that is: Why would you ever need to make that distinction? Both are "nullish", and you don't need to differentiate between "intentionally missing" and "unintentionally missing". One common usage of null is to do stuff like this:

const people = [    {        firstName: "Luke",        middleName: null,        lastName: "Shiru",    },    {        firstName: "Barack",        middleName: "Hussein",        lastName: "Obama",    },];

But you can just omit middleName when the user doesn't have one:

const people = [    {        firstName: "Luke",        lastName: "Shiru",    },    // ...];

And the TypeScript representation would be something like this:

type Person = {    firstName: string;    middleName?: string;    lastName: string;};

Why would we spend memory with a null value there, or bits with a JSON coming from the back-end, when we can just omit what is not there?

But the API is responding with null (maybe written in Java), so I have to use null all over my app as well.

My answer to that is: Use an API wrapper. Instead of "spreading" null all over your codebase, update your surface of contact with the API so nulls are removed, and if you have any contact with the folks making the API, voice your concern of making API responses smaller by getting rid of null values. You should try to avoid ending up over-engineering/over-complicating your app just to deal with null when you can just avoid it altogether.

But in React I use null when I want a component to not render anything

You can use undefined as well.

You have to type 5 more characters when you write undefined explicitly in your code.

Generally, you will rely on it implicitly (omitting the value), but even if we had to type it every time, is worth it compared to all the downsides of null.

Languages without nullish

There are languages out there that don't have nullish values, and instead rely on Maybe, which is a type that means "we might get a certain type or nothing". We can do a simple implementation of that in TypeScript like this:

const Maybe<Type> = Type | undefined;

So we might get whatever type we are expecting or undefined. We can just use ? as well when it's a property or argument:

const aFunction = (optionalArgument?: Type) => // ...type AnObject = {    optionalProperty?: Type;};

To deal with our "Maybes" we can use operators such as nullish coalescing (??) and optional chaining (?.), so...

// We don't need to do something nasty like this:const greet = name => `Hello, ${name !== null ? name : "Guest"}`;// We can do this:const greet = name => `Hello, ${name ?? "Guest"}`;// Or better yet, because we are using undefined, we can actually...const greet = (name = "Guest") => `Hello, ${name}`;

Linting like a champ

If you're convinced that null is not a good nullish value, you can avoid it from now on using this great ESLint plugin, and just add this to your linting rules:

{    "plugins": ["no-null"],    "rules": {        "no-null/no-null": "error"    }}

Closing thoughts

My personal opinion about null in JavaScript is "anything written with null can be written with undefined instead", but your millage might vary, so as usual I close this article with a few open questions: Do you NEED to use null? Don't you have a way of resolving that issue without it?

Thanks for reading this, and special thanks to the 3100+ followers that motivate me to keep doing this series! Remember that if you don't agree with something said here, you can just leave a comment and we can discuss it further.

See you in the next post of this series!

DISCLAIMER
This series is called "You don't need ...", emphasis on need, meaning that you would be fine without the thing that the post covers. This series explores alternatives, it doesn't impose them, so consider that before glancing over the post and ranting on the comment section.


Original Link: https://dev.to/vangware/you-dont-need-null-3m4n

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To