JavaScript Nullish Operators

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Nullish Operators

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

nullish coalescing

|| is unsafe:

let message, input;

message = input || 'default value';

console.log(null || 'default value'); // 'default value'
console.log(undefined || 'default value'); // 'default value'
console.log('valid input' || 'default value'); // 'valid input'
console.log('' || 'default value'); // 'default value' 😱

console.log(null || 100); // 100
console.log(undefined || 100); // 100
console.log(10 || 100); // 10
console.log(0 || 100); // 100 😱

?? is better:

let message, input;

// nullish coalescing is just a shorthand for a nullish check
message = input ?? 'default value';
message = input == null ? 'default value' : input;

console.log(null ?? 'default value'); // 'default value'
console.log(undefined ?? 'default value'); // 'default value'
console.log('valid input' ?? 'default value'); // 'valid input'
console.log('' ?? 'default value'); // ''

console.log(null ?? 100); // 100
console.log(undefined ?? 100); // 100
console.log(10 ?? 100); // 10
console.log(0 ?? 100); // 0

Optional nullish chaining

let john = {
name: 'John',
address: {
country: 'France',
}
};

let jane = {
name: 'Jane',
};

function logPerson(person) {
console.log('Name:', person.name);
console.log('Country:', person.address?.country);
}

logPerson(john); // ✅ Name: John, Country: France
logPerson(jane); // ✅ Name: Jane, Country: undefined

Three Syntax forms of Optional Chaining

const jamie = {
name: 'Jamie',
cat: {
name: 'Pixel',
toys: ['floppy fish']
}
};

console.log(jamie.dog); // ✅ undefined
console.log(jamie.dog?.name); // ✅ undefined

console.log(jamie.getAddress); // ✅ undefined
console.log(jamie.getAddress?.()); // ✅ undefined

console.log(jamie.cat.hobbies); // ✅ undefined
console.log(jamie.cat.hobbies?.[0]); // ✅ undefined
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

Modern JavaScript comes with a neat operator called Ledge coalescing to provide a default value in the presence of a knowledge that is null or undefined values. Let's say we want to initialize a message variable based on a provided input. People often incorrectly use the bullion or operator for this purpose, but it has an issue where it does more than what you expect. It does work fine if the value is null or undefined. So here you can see that if null or undefined is used, it fallbacks to the default value and for other strings it seems to work fine. For example, here,

00:31

it uses the provided input instead of the fallback default value. But the issue is that in addition to null and undefined, the OR operator actually works on the concept of falsey values. So an empty string will also fall back to the default value in addition to strings. Another example is numbers as well. So nalan and defined. Sure the boin operator does what you expect and for wallet numbers it works except when you provide the number zero. So the OR operator is not the same as a knowledge check, it is more like a falsey check. If you wanted to only include knowledge values, undefined,

01:05

traditionally we would need to do an explicit knowledge check combined with eternity operator. Fortunately, JavaScript now comes with a knowledge coalescing operator that does exactly that. So if the left hand side is naah undefined, it goes to the default value and for everything else, whether it is empty or non empty, as long as it is a string, it uses the provided value. And we can repeat this example with numbers as well. If the left hand side is an NA or undefined, then the right hand side default value is used for everything else like the number 10 or the number zero, it really doesn't matter.

01:39

It's not non-law undefined and therefore the left hand side value is what is used. JavaScript is fairly resilient when it comes to undefined properties, except traditionally it hasn't been resilient enough to demonstrate that. Consider a simple Jamie object that has a name and a CAT member, and then the cat itself is an object that has a name and a toys member which points to an array. And of course we can use wages, access methods, for example, to access the cat name or the cat's first toy. However, we can also access properties that do not exist. For example, Jamie does not have a dog and the JavaScript at runtime will not throw an error

02:13

and simply give us back the special value undefined. However, if he overextend our welcome and try to read the property off of that undefined, then the jow skip runtime will throw an error and exit the stack. Similarly, get address is not a property that exists on Jamie and if he try to get it, the JavaScript runtime gives us undefined but doesn't throw an error. However, then if we try to invoke it, then the JavaScript runtime suddenly says, Hey, you're doing something wrong. And the same for cat hobbies as well. The cat has no hobbies. JS skip runtime is fine. It gives us undefined, but if we try to access like it's first hobby,

02:47

then again the JavaScript runtime will throw an error and exit the program. Modern JavaScript comes with the optional chain operator that allows you to safely use knowledge values without JavaScript throwing an error. Consider the simple data structure for people. We have John with a name and an address, and then we have Jane that only has a name and has not provided us with her address. We have the simple log person function that takes a person object and is designed to log the person name and the person country based on their address. Now of course this function is going to work perfectly fine.

03:19

When we passing John, we see the name John and the country France. However, if you log Jane, the Taos kept on time is going to throw an error because Jane does not have an address and therefore we are trying to look up country from an undefined address. Now of course we can handle national or undefined values explicitly by first checking, Hey, does the person have an address? If they don't, then just return undefined, otherwise read the person address country. And now instead of throwing an error and exiting the program, we get a more reasonable log of undefined. Fortunately with modern JavaScript,

03:54

we don't need to write Aries like this anymore because we can actually use the optional chaining operator where instead of simple dot we use question mark dot. And in terms of behavior, it is exactly the same. If personal address is going to be null or undefined, then we are going to get undefined. Otherwise we are going to get address country. We could see the value of this operator even right now, but it becomes even more significant when we have optional of optional of optional. For example, if a person could potentially be undefined as well, we simply add the question mark dot over there,

04:27

and now we have a much neater syntax, then the nested turny that you might need to write. Otherwise, of course, if the value is going to be there, this is going to have no effect. So we could pretty much go crazy if you wanted to and we still get the same program output as we did before. The JavaScript optional tuning operator actually supports three syntax forms. So in addition to property access, it's supposed to index access and function in vocation. Let's take a trip down memory lane and visit our old friend Jamie again. And of course we can look up Jamie's cat name or the cat's toys, but as we know, Jamie does not have a dog.

04:59

And thanks to optional training we can look up the dog's name and instead of throwing an error, the Taos kept on time, gives us back a polite undefined. Similarly, Jamie does not have a get address function and we can actually use optional chaining question mark.to optionally invoke the method that doesn't exist. And again, instead of throwing an error, the JS kept on time, gives us the polite, undefined, Jamie's cat does have toys, however, she doesn't have hobbies. So hobbies is undefined and we can actually use the optional chaining question mark dot along with an index operator to look up a member from an array that

05:34

potentially doesn't exist. And of course, all of this works as you would expect without any error as we can see in the demo console. I hope you enjoyed this tutorial. As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36