6 Nullish coalescing operators every javascript programmer must know !

TL:DR :

Most of the time out javascript code becomes clumsier if we inserted the multiple null checks for the several entities. Those checks are kind of mandatory and if those checks were removed then this happens

TypeError: Cannot read p…


This content originally appeared on DEV Community and was authored by Sudarshan Sawandkar

TL:DR :

Most of the time out javascript code becomes clumsier if we inserted the multiple null checks for the several entities. Those checks are kind of mandatory and if those checks were removed then this happens

TypeError: Cannot read property 'xyz' of undefined

For preventing the programme from crashing and also making a code a bit neater, in this article I will explain some ways to handle this tricky situations

For the sake of examples, I will use following object to show you some example usage of the operators

let person = {
    name: "sud",
    age: 21,
    hobbie: {
        first: "Code",
        secodn: "Chess"
    }
}

Ternary Operator



Ternary operator is most commonly used operator in the code. Most programmers use this as the replacement of inline if --- else. This operator mainly used in the conditional rendering of components in React

//ternary 
let result = person.name === "sud" ? "Howdy Sud " : "Howdy Stranger"
console.log(result)

It is pretty straight forward. before ? is the condition. immediately after ? symbol is the block for true value of condition and other is for false result of condition

? Super Powered Ternary Operator ?



Ternary operator really shines when it is nested with itself and can be replace if ...... else ladder completely is used properly. In the following snippet, I used the operator as the if else block and made the code more readable for anyone

//ternary as if else 
let isAdult = person.age > 18 ?
        " You are adult :)"
        : age < 15 && age > 10  ?
        "You are on the way " 
        : "No Kids here "
console.log(isAdult)

It's pretty simple here, Append multiple conditions with consecutive block and then put last else block for default condition

Default Assignment with ??



Default assignment is one of my favorite once. This allows me to provide the placeholder value with minimal code by which we can trust the values and can implement type safety at logical level


let sudsAge = person.age ?? 22
console.log(`Sud's age is ${sudsAge}`)

Here we are assigning the default value to sudsAge if the person.age is undefined. It is pretty helpful. Thanks to this operator for saving us lengthy checks ❤

Multi Condition Evaluation with .includes()



Many times we have to check many conditions for both true / false values. For doing these, I used to write multi-line nested code of if and else block or use the switch statement. But here is the trick

//check with multiple conditions
let isSporty = ['Chess', 'cricket'].includes(person.hobbie.first) ? "true" : "Nope"
console.log(isSporty)

By replacing array values with real condition, we can check for all true values. If any values returns false then it will won't proceed .

Check Presence of Property In Object Using ?.



This is most useful operator in day to day life. Whether you are dealing with async API calls or dealing with blocking tasks, we easily assume the key will be present in the response of an API or output JSON object of any operation But, what if key is absent of undefined. Here is the trick

let sudsHobbyFirst = person?.hobbie?.third 
console.log(sudsHobbyFirst)

By using this operator we can make sure the property is present or not and perform checks / operations according to result.

Chaining Default Assignment and Membership Operator



Previously mentioned operator can be super powered if chained with the default assignment. We will assign the default value to variable if the property is undefined or absent.

//?. with ?? 
let sudsHobby = person?.hobbie?.third ?? "Nothing"
console.log(sudsHobby)

Here, we are assigning the placeholder value for sudsHobby
(? you will use this a lot ? )

Final Thoughts



This my small try to explain you all the usage of some operators which could possibly make your code neater and smaller rather than your previous code

?Please let me know your thoughts in comments

?hanks For Reading ...


This content originally appeared on DEV Community and was authored by Sudarshan Sawandkar


Print Share Comment Cite Upload Translate Updates
APA

Sudarshan Sawandkar | Sciencx (2021-05-03T03:58:48+00:00) 6 Nullish coalescing operators every javascript programmer must know !. Retrieved from https://www.scien.cx/2021/05/03/6-nullish-coalescing-operators-every-javascript-programmer-must-know/

MLA
" » 6 Nullish coalescing operators every javascript programmer must know !." Sudarshan Sawandkar | Sciencx - Monday May 3, 2021, https://www.scien.cx/2021/05/03/6-nullish-coalescing-operators-every-javascript-programmer-must-know/
HARVARD
Sudarshan Sawandkar | Sciencx Monday May 3, 2021 » 6 Nullish coalescing operators every javascript programmer must know !., viewed ,<https://www.scien.cx/2021/05/03/6-nullish-coalescing-operators-every-javascript-programmer-must-know/>
VANCOUVER
Sudarshan Sawandkar | Sciencx - » 6 Nullish coalescing operators every javascript programmer must know !. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/03/6-nullish-coalescing-operators-every-javascript-programmer-must-know/
CHICAGO
" » 6 Nullish coalescing operators every javascript programmer must know !." Sudarshan Sawandkar | Sciencx - Accessed . https://www.scien.cx/2021/05/03/6-nullish-coalescing-operators-every-javascript-programmer-must-know/
IEEE
" » 6 Nullish coalescing operators every javascript programmer must know !." Sudarshan Sawandkar | Sciencx [Online]. Available: https://www.scien.cx/2021/05/03/6-nullish-coalescing-operators-every-javascript-programmer-must-know/. [Accessed: ]
rf:citation
» 6 Nullish coalescing operators every javascript programmer must know ! | Sudarshan Sawandkar | Sciencx | https://www.scien.cx/2021/05/03/6-nullish-coalescing-operators-every-javascript-programmer-must-know/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.