Hướng dẫn javascript question mark operator
The conditional or question mark operator, represented by a But there is more to it than meets the eye. There are three main uses for the We'll look at each of these in detail, starting with the most common way you'll see the The term ternary means composed of three items or parts. The Starting with The ternary operator is basically a shortcut for a traditional Let's compare a ternary operator with a longer Here, the ternary operator occupies only one line of code, whereas the Using a ternary operator is much more effective, right? 2. Optional ChainingIn 2020, an awesome new feature known as Optional Chaining was introduced. To understand how it works, imagine this scenario. Let's say you have code that calls on an object property that doesn't exist, which triggers an error at run time. This may be because of a missing or undefined value in your database or from an API: A common error –TypeError: Cannot read property ‘salary’ of undefined Thanks to Optional Chaining, you can just insert
a With that, it will just return Optional Chaining is truly a life-changing feature for JavaScript developers. 3. Nullish CoalescingIn some cases, you have to set a default value for a missing property name or value. For example, let's say we are creating a Weather App in which we are fetching the temperature, humidity, wind speed, pressure, time of sunrise and sunset, and the picture of the city. We inputted a place, let's say Bangalore, but for some reason, its image is not there in the database. When the app fetches and displays the data, the picture will be blank, which can look ugly. What we can do, in that case, is set a default picture for those cities which don't have an image, Bangalore in our case. This way, when the app displays the data, the default picture will be there for the cities without images. You can do this using the But if you use Consider a scenario where a variable has the value of 0 or an empty string. If we use ( Instead of the logical OR ( Let's learn with an example. With Logical OR (|| )Here, we have '0' and 'default string' in variable value1. If we log its value in the console, we will get 'default string', which is weird. Instead of the default
string, we should be getting 0, as zero is not undefined or null. So, ' Similarly, it's the same with value2. Output for '|| ' With Nullish CoalescingBut if we
replace ' ?? 'Nullish Coalescing works exactly like the logical OR operator, except you will
get the right side value when the left side value is In other words, ConclusionNow hopefully you understand how the Try them them out and let me know how it goes. Happy learning! Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started |