Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for #
Ankit Tanna
Ankit Tanna

Posted on

     

#"/t/javascript">#javascript#typescript#codereview#codequality

I HATE RUN-TIME CONSOLE ERRORS

Here, I have said it in big bold capital letters. Usually they arise because you try to access a property ofundefined ornull.

You must have been aware of this dreadful image:
Web console run-time error image

This happens usually when we try to do something like this:

functionprintPersonDetails(person){console.log(person.age);}printPersonDetails(undefined);
Enter fullscreen modeExit fullscreen mode

As soon as you pass person asundefined the clock of the doomsday starts ticking and at any moment when this function is triggered, you shall see the run-time error.

You might argue that you could write unit tests but since JavaScript provides all the fallback mechanisms in place then why wait for unit tests to be written.

Option 1 - Use default values for function parameters

This is the least a developer should do.

Before

functionadd(a,b,c){returna+b+c;}add(1,undefined,2);// Run-time error
Enter fullscreen modeExit fullscreen mode

After

functionadd(a=0,b=0,c=0){returna+b+c;}add(1,undefined,2);// Run-time error
Enter fullscreen modeExit fullscreen mode

Providing default values to parameters is a good practice.

Option 2 - Nullish coalescing operator (??)

This(??) new symbol is a life saver. This is a logical operator that returns RHS operator if LHS is null/undefined.
RHS/LHS - right/left hand side (duh!)

I 💗 this feature!

functionadd(a,b,c){constvalOfA=a??0;constvalOfB=b??0;constvalOfC=c??0;returna+b+c;}add(null,undefined,null);// Run-time error
Enter fullscreen modeExit fullscreen mode

Option 3 - Logical Nullish assignment operator (??=)

This(??=) new symbol is another life saver. The logical nullish assignment(x ??= y) operator only assigns ifx isnullish (null or undefined).

I 💗 this feature!

functionprintPersonDetails(person){person.age??=0;console.log(person?.age);// 0 and no run-time error}printPersonDetails({age:undefined});
Enter fullscreen modeExit fullscreen mode

Option 4 - Destructuring and Rest defaults

This option is also pretty handy but can take some time to wrap your head around.

Before

vartmp=getSomeRecords();varfirst=tmp[0];varsecond=tmp[1];varfirstName=first.name;varfirstEmail=first.email!==undefined?first.email:"nobody@none.tld";varsecondName=second.name;varsecondEmail=second.email!==undefined?second.email:"nobody@none.tld";functiongetSomeRecords(){return[{name:"a",email:"a@gmail.com",},{name:"b",email:"b@gmail.com",},];}
Enter fullscreen modeExit fullscreen mode

After

var[{name:firstName,email:firstEmail="nobody@none.com"},{name:secondName,email:secondEmail="nobody@none.com"}]=getSomeRecords();functiongetSomeRecords(){return[{name:"a"},{name:"b",email:"b@gmail.com",},];}
Enter fullscreen modeExit fullscreen mode

The same rest parameter concept can be applicable to function parameters as well.

Before

functionprintPersonDetails(person){console.log(person.age);console.log(person.name);}printPersonDetails(undefined);// 💥 💥 Blast!!!
Enter fullscreen modeExit fullscreen mode

After

functionprintPersonDetails({age:age=0,name:name='john doe'}){console.log(age);console.log(name);}printPersonDetails(undefined);// Works// OR if you are lazy to repeat propertiesfunctionprintPersonDetails({age=0,name='john doe'}){console.log(age);console.log(name);}printPersonDetails(undefined);// Works
Enter fullscreen modeExit fullscreen mode

The above technique can also be useful if you have more than 3 parameters in your function and you don't like remembering the sequence of them (I don't). This feature is known as named-parameters.

Option 5 - Use Elvis(?) operator

I hate this option but I will still list it.

functionprintPersonDetails(person){console.log(person?.age);// undefined and no run-time error}printPersonDetails(undefined);
Enter fullscreen modeExit fullscreen mode

But what if person is not undefined and you tried to access a property inside age but age turns out to be undefined/null?

Option 5.1 Use Elvis(?) operator AND Non-Null Assertions (TypeScript 3.9 onwards only)

functionprintPersonDetails(person){console.log(person?.age!.unit);// undefined and no run-time error// ORconsole.log((person?.age).unit);// undefined and no run-time error}printPersonDetails({age:undefined});
Enter fullscreen modeExit fullscreen mode

The(...) or! provide the non-null assertions

These techniques are the ones that needs to be followed to avoid embarrassing production run-time errors on your console.

I have a small YouTube channel namedEverydayJavaScript. Please do subscribe to the channel if you liked this post.

Happy error-free coding!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Ankit Tanna
I am a YouTuber who makes Tutorials to understand the concept in the easiest way. My Channel "Everyday JavaScript"
  • Location
    Pune, India
  • Work
    Team Lead at Pune
  • Joined

More fromAnkit Tanna

What's new in TypeScript v4.4?
#typescript#javascript#webdev#angular
TypeScript - Build Types from Interfaces
#typescript#javascript#interfaces
How to create a type for complex JSON object in TypeScript?
#typescript#javascript#node#json
DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp