Created
September 25, 2023 15:27
-
-
Save dsmabulage/212630be980fdd0b45b5f0cea3bcb179 to your computer and use it in GitHub Desktop.
Null Operators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| console.log(null || 'default value'); // 'default value' | |
| console.log(undefined || 'default value'); // 'default value' | |
| console.log(false || 'default value'); // 'default value' | |
| console.log('' || 'default value'); // 'default value' | |
| console.log(0 || 'default value'); // 'default value' | |
| console.log(NaN || 'default value'); // 'default value' | |
| console.log('Hello' || 'default value'); // 'Hello' | |
| console.log(null || 100); // 100 | |
| console.log(undefined || 100); // 100 | |
| console.log(false || 100); // 100 | |
| console.log('' || 100); // 100 | |
| console.log(0 || 100); // 100 | |
| console.log(null ?? 'default value'); // 'default value' | |
| console.log(undefined ?? 'default value'); // 'default value' | |
| console.log(false ?? 'default value'); // false | |
| console.log('' ?? 'default value'); // '' | |
| console.log(0 ?? 'default value'); // 0 | |
| console.log(0 ?? 100); // 0 | |
| console.log(10 ?? 100); // 10 | |
| const jamie = { | |
| name: 'Jamie', | |
| cat: { | |
| name: 'Pixel', | |
| toys: ['floppy fish'], | |
| }, | |
| }; | |
| console.log(jamie.cat.name); // Jamie | |
| console.log(jamie.cat.toys[0]); // floppy fist | |
| console.log(jamie.dog); // undefined | |
| console.log(jamie.dog.name); // error - cannot react property of undefined | |
| console.log(jamie.getAddress); // undefined | |
| console.log(jamie.getAddress()); // Error | |
| console.log(jamie.cat.hobbies); // undefined | |
| console.log(jamie.cat.hobbies[0]); // Error | |
| 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 | |
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment