- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- Remember language
Nullish coalescing assignment (??=)
The nullish coalescing assignment ( ??= ) operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish ( null or undefined ).
Description
Nullish coalescing assignment short-circuits , meaning that x ??= y is equivalent to x ?? (x = y) , except that the expression x is only evaluated once.
No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :
Neither would the following trigger the setter:
In fact, if x is not nullish, y is not evaluated at all.
Using nullish coalescing assignment
You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values , ??= also applies the default value if the property has value null .
Specifications
Specification |
---|
Browser compatibility
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- Nullish coalescing operator ( ?? )
Advanced JavaScript Operators – Nullish Coalescing, Optional Chaining, and Destructuring Assignment
Hi Everyone! In this article, I'm going to teach you how to use three advanced JavaScript operators: the Nullish Coalescing, Optional Chaining, and Destructuring Assignment operators.
These three operators will help you write clearer and less error-prone code.
The Nullish Coalescing Operator
When you’re inspecting JavaScript code, you may find an expression using a double question mark ( ?? ), as in the code below:
The double question mark is a logical operator that returns the expression on the right-hand side of the mark when the expression on the left-hand side is null or undefined
This operator is also known as the nullish coalescing operator. It’s a new feature introduced in JavaScript ES2020 that allows you to check for null or undefined values in a more concise way.
Nullish Coalescing Operator Syntax
The syntax for the nullish coalescing operator is very simple. It consists of two question marks ?? placed between two operands.
Here’s an example:
The code above assigns the firstName variable value as the value of the username variable.
When the firstName value is null or undefined , then the value Guest will be assigned to the username variable instead:
You can also write it this way:
As you can see, you don’t need an if-else statement to check for null or undefined values.
Why JavaScript Needs This Operator
The nullish coalescing operator was created as an improved alternative to the OR operator || .
The OR operator was originally created to provide a default or fallback value when the left-hand expression is falsy, or evaluates to false .
But after some real-world uses, it’s clear that there are times when developers want to return values that are considered falsy, such as 0 and an empty string ( "" )
The use of the OR operator will prevent you from returning any falsy values at all. Consider the following example:
By using the nullish coalescing operator, you will only replace exactly null and undefined values with the right-hand value.
The nullish coalescing operator can be used with any type of value, including numbers, strings, and objects.
Nullish Coalescing Operator Use Cases
The nullish coalescing operator is useful in a variety of situations where you need to check for null or undefined values and provide a default value.
Here are several examples of common use cases:
Handling Missing Function Arguments
When a function is called, it’s possible that some of the arguments may be omitted.
The Nullish Coalescing Operator can be used to provide default values for a missing argument as follows:
Accessing Object Properties
When working with objects, it’s possible that a property may not exist or is undefined .
The Nullish Coalescing Operator can be used to safely access object properties and provide a default value when the property is missing:
Choosing Between a Variable and a Constant
You may want to select a value from a variable or a constant if the variable is null or undefined :
As you can see, the Nullish Coalescing Operator is a great feature that can make your code more concise and reliable.
Using ?? with the || and && Operators
For safety reasons, the double question mark can’t be used together with JavaScript OR ( || ) and AND ( && ) operators without parentheses () separating the operators.
For example, the following code tries to see if either firstName or lastName variable can be used as the value of username before using "Guest" as its value:
This is because JavaScript won’t be able to determine which operator it needs to evaluate first. You need to use parentheses to clearly indicate the priority of the evaluations.
The following code will first evaluate the expressions inside the parentheses:
And that’s how you combine the nullish coalescing operator with either AND or OR operator.
The Optional Chaining Operator
Like the nullish coalescing operator, the optional chaining operator is a modern addition to JavaScript that offers a better way to do things.
The optional chaining operator ?. gives you a safe way to access properties and methods of an object, avoiding an error in the process.
One of the most common problems in JavaScript is that you can get an error when you access a property of an undefined value.
For example, suppose you have a car object as follows:
In the example above, accessing the manufacturer property returns undefined , but when you try to access the address property of the manufacturer property, JavaScript returns an error.
Even though this is how JavaScript works, a better way to handle the non-existent property would be to just return an undefined back, just like when we try to access the manufacturer property.
This is why the optional chaining operator was created. The operator returns either the value of the property, or undefined when the property is null or undefined .
To use the operator, just add a question mark in front of the dot . notation:
The optional chaining operator can be added anytime you use the dot notation to access a property or method.
This operator allows you to avoid the TypeError that occurs when accessing a property or calling a method from a non-existent property:
Note that the optional chaining operator only checks the value before it. If the car variable can be null , then you need to add the operator after when accessing the car object as well.
See the following example:
And that’s how the optional chaining operator works. It’s really useful when you’re working with objects in your project.
Next, let’s learn about the destructuring assignment.
Destructuring Assignment Operator
The destructuring assignment is a special operator that allows you to "unpack" or "extract" the values of JavaScript arrays and objects. It has become one of the most useful features of JavaScript language for two reasons:
- It helps you to avoid code repetition.
- It keeps your code clean and easy to understand.
Let’s see how you can destructure an array and an object next.
Destructuring Arrays
Here’s how you normally assign an array values to variables:
The code above works, but you need two lines of code to get two elements from an array. Using the destructuring assignment, you can assign array elements into variables in one short line:
The above code will return the same value for firstIndex and secondIndex variable. No matter how many elements you have, the destructuring will start from the zero index.
To create a destructuring assignment, you need to add square brackets [] after the let / const keyword. When you add square brackets after the assignment ( = ) operator, it’s an array. If you add them before the assignment operator, it’s a destructuring assignment.
You can also use the rest operator … to copy the rest of the values after your assignment. Take a look at the following example:
The rest variable will contain an array with values of ['Jack','Aston'] .
You can also put default values for these variables when the extracted value is undefined:
You can also immediately assign the return of a function into assignments. This is frequently used in libraries like React:
The variable a will return "John" and b will return "Jack".
Finally, you can also ignore some variables by skipping the assignment for that index:
Destructuring assignment makes unpacking array values easier and shorter, with less repetition.
Object Destructuring
Just like arrays, you can destructure objects the same way, but instead of using the square brackets ( [] ) you need to use the curly brackets ( {} ):
You can use the colon delimiter ( : ) to assign the property into a different name. The example below assign the value of firstName into name :
Note that you still only create two variables: name and lastName . The firstName is assigned to name , so it won’t create a separate variable.
Just like arrays, you can destructure an object returned by a function immediately:
Also, you can destructure an object from the function parameters, exactly when you define the function:
The destructuring assignment is a useful addition to JavaScript that makes it easier to unpack values from objects and arrays. You’re going to use it frequently when you code using a library like React.
JavaScript is constantly improving every year, and the three operators explained in this article are a great addition that can help you produce more concise and readable code.
If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book Beginning Modern JavaScript here .
The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.
Here's my promise: You will actually feel like you understand what you're doing with JavaScript.
Until next time!
Read more posts .
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
Staging Ground badges
Earn badges by improving or asking questions in Staging Ground.
Succinct/concise syntax for 'optional' object keys in ES6/ES7? [duplicate]
There are already a lot of cool features in ES6/ES7 for defining Javascript objects. However, the following pattern is common in Javascript:
Is there a way to define the object all at once with both optional and required keys?
- ecmascript-6
- ecmascript-2016
- ecmascript-next
- Why not just use a ternary? optionKey1: someCondition ? value : undefined ? – Andrew Li Commented Dec 19, 2017 at 17:21
- @FelixKling I think that's a largely theoretical distinction because there is not a 'whole' ES6 or ES7 standard implemented in Node/browser environments and most people are using transpilers anyway. – Andrew Mao Commented Dec 20, 2017 at 18:49
- 1 Well, it defines the scope for answers. We don’t know what you are using. Also I don’t want people to misuse the term ES7 for experimental features. – Felix Kling Commented Dec 20, 2017 at 18:53
- 1 @FelixKling I'm asking about any standard of Ecmascript; obviously existing supported standards is better. If this can be done with experimental features, okay. If it can be done with ES6 or ES7, better. If it is possible with ES5, super! – Andrew Mao Commented Dec 20, 2017 at 18:55
- 4 I would love to see something like { key?: optionalValue } or with property shorthand: { optionalValue? } – cimak Commented Nov 14, 2020 at 23:31
4 Answers 4
You can use object spread to have an optional property:
let flag1 = true; let flag2 = false; // extra cases added by Abdull let optionalKey8 = 8; let optionalKey9 = undefined; let optionalKey10 = false; let optionalKey11 = null; let optionalKey12 = "twelve"; const obj = { requiredKey1: 1, requiredKey2: 2, ...(flag1 && { optionalKey3: 3 }), ...(flag2 && { optionalKey4: 4, optionalKey5: 5 }), // ignored ...(flag1 && { optionalKey6: 6, optionalKey7: 7 }), ...(optionalKey8 && { optionalKey8 }), ...(optionalKey9 && { optionalKey9 }), // ignored ...(optionalKey10 && { optionalKey10 }), // ignored ...(optionalKey11 && { optionalKey11 }), // ignored ...(optionalKey12 && { optionalKey12 }) }; console.log(obj);
- 3 Note: this will make turn any getters into static values. – Ryan King Commented Feb 25, 2020 at 22:36
- 7 As a note, you don't need the parentheses. eg. ...flag1 && { optionalKey1: 5 }, is fine too. – MattCochrane Commented Jun 8, 2020 at 11:25
- 1 @RyanKing ah, optional getter ;) o'c you can't destruct getter ;) – zb' Commented Apr 13, 2021 at 12:05
- 1 I receive an error in the false value, I solved with this: ...(flag2 && { optionalKey2: 6, optionalKey3: 7 }) as {}, – juanjinario Commented Jul 21, 2021 at 8:24
- 1 @Abdull - thanks for the edit. I made updates, and mentioned you in a comment. – Ori Drori Commented Apr 3, 2023 at 9:30
To indicate optional key, you can assign to it null , if the condition is false
const someCondition = true; const obj = { requiredKey1: 1, requiredKey2: 2, optionalKey1: someCondition ? 'optional' : null }; console.log(obj);
- 29 Good answer, but worth noting that by doing this, optionalKey1 still appears as one of the keys of the object if the condition is false (and has the value null), whereas OPs original snippet will create an object that lacks the key entirely if the condition is false. – CRice Commented Dec 19, 2017 at 17:32
- I think, assigning null to the property is more understandable that it is optional and does not have value than checking for the existence – Suren Srapyan Commented Dec 19, 2017 at 17:53
- 1 I personalyl would like to get some sort of error, and generally whatever behavior a language (and JavaScript in particular) would give me when trying to access an inexistent property, rather than making it nullable, since it's not ever going to have a value, unlike what nullable values are used for - it it needs to exists, it exists. If it doesn't need to exits, it doesn't - I think that makes more sense. – Gal Grünfeld Commented Dec 1, 2020 at 18:39
- @SurenSrapyan adding an optional member with null value doesn't make it optional. It means that the object has an actual member whose assigned value is null which actually is a value . You may thing that null is not a value, but it is. Therefore this doesn't make a member optional. An optional member would be one, that wouldn't be returned by the Object.entries(obj) function. If at least you'd assign it a value of undefined which would mean that the member is undefined and doesn't have a value assigned to it. Object.entries(obj) would still see the member though. – Robert Koritnik Commented Aug 8, 2022 at 14:20
- One workaround to fix the optional member with null would be removing it in the next line: Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]); @SurenSrapyan If you add this line, that will make this answer also one of the options. – Avtar Nanrey Commented Dec 21, 2023 at 14:51
You can declare the variable by passing it through the below function
Then declare the variable as follows
- 1 That removes all properties with falsy values, which is probably not desired – Bergi Commented Dec 21, 2023 at 8:32
the following pattern is common in Javascript
It should not. Having many objects of different shapes can incur a performance penalty. Records should always contain the same keys. So just use
- The pattern is really useful in objects you pass as options. – krulik Commented Dec 10, 2019 at 10:24
- 2 @krulik Option object parameters usually can deal totally fine with undefined properties, not distinguishing them from non-existing properties. – Bergi Commented Dec 10, 2019 at 11:56
Not the answer you're looking for? Browse other questions tagged javascript object ecmascript-6 ecmascript-2016 ecmascript-next or ask your own question .
- The Overflow Blog
- What launching rockets taught this CTO about hardware observability
- The team behind Unity 6 explains the new features aimed at helping developers
- Featured on Meta
- Preventing unauthorized automated access to the network
- Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
- Feedback Requested: How do you use the tagged questions page?
- Proposed designs to update the homepage for logged-in users
Hot Network Questions
- Why does Windows 11 display a different ethernet MAC (hardware) address than Linux?
- Is this baseboard installation a good job?
- How to measure objects in Blender 4.2
- Graduate Instance colour by constant interpolation
- Raise the Dead rote
- Card design with long and short text options
- Expected number of cards that are larger than both of their neighbors
- Why is pqxdh of Signal not secure against active adversaries while PQ3 of iMessage is?
- Would radar/sonar/other spy technology be able to penetrate space station walls?
- What challenge did Jesus put before the rich young man in Mtt19?
- Can every finite metric space be approximated by a distinct distance space?
- Bash script not renaming file
- How to distinguish contrast from simultaneity when using the connective "while"?
- why does this tumbling tetrahedra result depend on n?
- Bragg's Law: Don't Waves have to Overlap to Interfere?
- Advisor won't let me push back against reviewer comments
- How to check die temperatures on an Apple Silicon Mac?
- What separates numbers from other mathematical objects and what justifies e.g. the quaternions to be called a number system?
- Question about two density matrices
- What does Rich mean?
- Reference on why finding a feasible solution to the Set Partitioning problem is NP-Hard?
- What expressions (verbs) are used for the actions of adding ingredients (solid, fluid, powdery) into a container, specifically while cooking?
- Are there any sane ways to make or explore the properties of FOOF (dioxygen difluoride)?
- On the martingale betting scheme
Home » JavaScript Tutorial » JavaScript Logical Assignment Operators
JavaScript Logical Assignment Operators
Summary : in this tutorial, you’ll learn about JavaScript logical assignment operators, including the logical OR assignment operator ( ||= ), the logical AND assignment operator ( &&= ), and the nullish assignment operator ( ??= ).
ES2021 introduces three logical assignment operators including:
- Logical OR assignment operator ( ||= )
- Logical AND assignment operator ( &&= )
- Nullish coalescing assignment operator ( ??= )
The following table shows the equivalent of the logical assignments operator:
Logical Assignment Operators | Logical Operators |
---|---|
x ||= y | x || (x = y) |
x &&= y | x && (x = y) |
x ??= y | x ?? (x = y); |
The Logical OR assignment operator
The logical OR assignment operator ( ||= ) accepts two operands and assigns the right operand to the left operand if the left operand is falsy:
In this syntax, the ||= operator only assigns y to x if x is falsy. For example:
In this example, the title variable is undefined , therefore, it’s falsy. Since the title is falsy, the operator ||= assigns the 'untitled' to the title . The output shows the untitled as expected.
See another example:
In this example, the title is 'JavaScript Awesome' so it is truthy. Therefore, the logical OR assignment operator ( ||= ) doesn’t assign the string 'untitled' to the title variable.
The logical OR assignment operator:
is equivalent to the following statement that uses the logical OR operator :
Like the logical OR operator, the logical OR assignment also short-circuits. It means that the logical OR assignment operator only performs an assignment when the x is falsy.
The following example uses the logical assignment operator to display a default message if the search result element is empty:
The Logical AND assignment operator
The logical AND assignment operator only assigns y to x if x is truthy:
The logical AND assignment operator also short-circuits. It means that
is equivalent to:
The following example uses the logical AND assignment operator to change the last name of a person object if the last name is truthy:
Optional chaining '?.'
The optional chaining ?. is a safe way to access nested object properties, even if an intermediate property doesn’t exist.
The “non-existing property” problem
If you’ve just started to read the tutorial and learn JavaScript, maybe the problem hasn’t touched you yet, but it’s quite common.
As an example, let’s say we have user objects that hold the information about our users.
Most of our users have addresses in user.address property, with the street user.address.street , but some did not provide them.
In such case, when we attempt to get user.address.street , and the user happens to be without an address, we get an error:
That’s the expected result. JavaScript works like this. As user.address is undefined , an attempt to get user.address.street fails with an error.
In many practical cases we’d prefer to get undefined instead of an error here (meaning “no street”).
…and another example. In Web development, we can get an object that corresponds to a web page element using a special method call, such as document.querySelector('.elem') , and it returns null when there’s no such element.
Once again, if the element doesn’t exist, we’ll get an error accessing .innerHTML property of null . And in some cases, when the absence of the element is normal, we’d like to avoid the error and just accept html = null as the result.
How can we do this?
The obvious solution would be to check the value using if or the conditional operator ? , before accessing its property, like this:
It works, there’s no error… But it’s quite inelegant. As you can see, the "user.address" appears twice in the code.
Here’s how the same would look for document.querySelector :
We can see that the element search document.querySelector('.elem') is actually called twice here. Not good.
For more deeply nested properties, it becomes even uglier, as more repetitions are required.
E.g. let’s get user.address.street.name in a similar fashion.
That’s just awful, one may even have problems understanding such code.
There’s a little better way to write it, using the && operator:
AND’ing the whole path to the property ensures that all components exist (if not, the evaluation stops), but also isn’t ideal.
As you can see, property names are still duplicated in the code. E.g. in the code above, user.address appears three times.
That’s why the optional chaining ?. was added to the language. To solve this problem once and for all!
Optional chaining
The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined .
Further in this article, for brevity, we’ll be saying that something “exists” if it’s not null and not undefined .
In other words, value?.prop :
- works as value.prop , if value exists,
- otherwise (when value is undefined/null ) it returns undefined .
Here’s the safe way to access user.address.street using ?. :
The code is short and clean, there’s no duplication at all.
Here’s an example with document.querySelector :
Reading the address with user?.address works even if user object doesn’t exist:
Please note: the ?. syntax makes optional the value before it, but not any further.
E.g. in user?.address.street.name the ?. allows user to safely be null/undefined (and returns undefined in that case), but that’s only for user . Further properties are accessed in a regular way. If we want some of them to be optional, then we’ll need to replace more . with ?. .
We should use ?. only where it’s ok that something doesn’t exist.
For example, if according to our code logic user object must exist, but address is optional, then we should write user.address?.street , but not user?.address?.street .
Then, if user happens to be undefined, we’ll see a programming error about it and fix it. Otherwise, if we overuse ?. , coding errors can be silenced where not appropriate, and become more difficult to debug.
If there’s no variable user at all, then user?.anything triggers an error:
The variable must be declared (e.g. let/const/var user or as a function parameter). The optional chaining works only for declared variables.
Short-circuiting
As it was said before, the ?. immediately stops (“short-circuits”) the evaluation if the left part doesn’t exist.
So, if there are any further function calls or operations to the right of ?. , they won’t be made.
For instance:
Other variants: ?.(), ?.[]
The optional chaining ?. is not an operator, but a special syntax construct, that also works with functions and square brackets.
For example, ?.() is used to call a function that may not exist.
In the code below, some of our users have admin method, and some don’t:
Here, in both lines we first use the dot ( userAdmin.admin ) to get admin property, because we assume that the user object exists, so it’s safe read from it.
Then ?.() checks the left part: if the admin function exists, then it runs (that’s so for userAdmin ). Otherwise (for userGuest ) the evaluation stops without errors.
The ?.[] syntax also works, if we’d like to use brackets [] to access properties instead of dot . . Similar to previous cases, it allows to safely read a property from an object that may not exist.
Also we can use ?. with delete :
The optional chaining ?. has no use on the left side of an assignment.
For example:
The optional chaining ?. syntax has three forms:
- obj?.prop – returns obj.prop if obj exists, otherwise undefined .
- obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined .
- obj.method?.() – calls obj.method() if obj.method exists, otherwise returns undefined .
As we can see, all of them are straightforward and simple to use. The ?. checks the left part for null/undefined and allows the evaluation to proceed if it’s not so.
A chain of ?. allows to safely access nested properties.
Still, we should apply ?. carefully, only where it’s acceptable, according to our code logic, that the left part doesn’t exist. So that it won’t hide programming errors from us, if they occur.
Lesson navigation
- © 2007—2024 Ilya Kantor
- about the project
- terms of usage
- privacy policy
- JS Tutorial
- JS Exercise
- JS Interview Questions
- JS Operator
- JS Projects
- JS Examples
- JS Free JS Course
- JS A to Z Guide
- JS Formatter
Nullish Coalescing Assignment (??=) Operator in JavaScript
This is a new operator introduced by javascript. This operator is represented by x ??= y and it is called Logical nullish assignment operator. Only if the value of x is nullish then the value of y will be assigned to x that means if the value of x is null or undefined then the value of y will be assigned to x.
Let’s discuss how this logical nullish assignment operator works. Firstly we all know that logical nullish assignment is represented as x ??= y , this is derived by two operators nullish coalescing operator and assignment operator we can also write it as x ?? (x = y) . Now javascript checks the x first, if it is nullish then the value of y will be assigned to x .
Example 1 :
Example 2 :
Supported browsers
Similar Reads
- Web Technologies
- javascript-operators
Please Login to comment...
- Free Music Recording Software in 2024: Top Picks for Windows, Mac, and Linux
- Best Free Music Maker Software in 2024
- What is Quantum AI? The Future of Computing and Artificial Intelligence Explained
- Noel Tata: Ratan Tata's Brother Named as a new Chairman of Tata Trusts
- GeeksforGeeks Practice - Leading Online Coding Platform
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
DEV Community
Posted on Aug 15, 2021 • Updated on Aug 16, 2021
Optional chaining '?.' in JavaScript 💪🔥
Hey readers 👋.
In this article, we’ll learn about the optional chaining (?.) that simplifies the way to access values through nested objects.
What the heck is Optional chaining? 🥴
The optional chaining ?. is a recent addition to the language which is a secure way to access nested object properties, even if an intermediate property doesn’t exist.
With the optional chaining if a certain property doesn't exist then undefined is returned immediately.
The optional chaining ?. syntax has three forms:
obj?.prop – returns obj.prop if obj exists, otherwise undefined.
obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined.
obj.method?.() – calls obj.method() if obj.method exists, otherwise returns undefined
To understand the concept better let's have a look at a few of the use cases.
- Let's see what happens if we try to access a property that doesn't exist without the use of optional chaining.
We get an error. That’s the expected result. JavaScript works like this. As restaurant.closingHours is undefined, an attempt to get restaurant.closingHours.mon.close fails with an error.
- In order to avoid this error, we first need to check if this property exists. The obvious solution would be to check the value using if or the conditional operator ? , before accessing its property.
It works, there’s no error. But it makes our code more unreadable and messier. It gets more offended pretty quickly when we have a deeply nested object with lots of optional properties.
- Now, let's attempt to access the property by using optional chaining.
We see the code is short and clean, there’s no duplication at all.
Note: Only if the property that is before ?. that's mon here exists then this close property will be read and if not then immediately undefined will be returned.
In other words, the ?. checks the left part for null/undefined and allows the evaluation to proceed if it’s not so.
Something “exists” here means if it’s not null and not undefined.
- Let's see one more example:
By using the ?. operator instead of just . , JavaScript knows to implicitly check to be sure user.first is not null or undefined before attempting to access user.first.last . If user.first is null or undefined, the expression automatically short-circuits, returning undefined.
Combining with the nullish coalescing operator
In a nutshell, the nullish coalescing operator, written as ?? is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
We can set a default value if our optional chaining returns something unwanted.
Since the city property is not provided and evaluates to the undefined courtesy of the optional chaining operator, the nullish coalescing operator then kicks in and defaults to the right-hand side operand "Unknown city" because the left-hand side operand is evaluated to undefined.
Optional chaining on the left-hand side of an assignment
Optional chaining is invalid when used on the left-hand side of an assignment. This results in an error.
Optional chaining with function calls
We can use optional chaining when attempting to call a method that may not exist.
For example, ?.() is used to call a function that may not exist.
Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found:
The ?.[] syntax also works, if we’d like to use brackets [] to access properties instead of dot .
Optional chaining can be used often when we are fetching responses from an API. We may not be 100% sure if a certain object exists in our API response. With optional chaining, we can check to see if something exists and handle an error gracefully.
Wrapping Up!
Optional chaining in JavaScript is very useful - we can access values without checking if the parent object exists. Instead of returning an error, it will return null or undefined.
Also if you got any questions feel free to ping me on Twitter
Top comments (0)
Templates let you quickly answer FAQs or store snippets for re-use.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .
Hide child comments as well
For further actions, you may consider blocking this person and/or reporting abuse
Cara Penggunaan Axios di ReactJS - GET dan POST Request
ramadhan.dev - Oct 15
How to use Poetry in Django project
TheHormat - Oct 14
Understanding State Variables in React: Why and How
Bhargav Ditani - Oct 14
Unity in React.js: From 20 Seconds to 1.2 Seconds loading time
Nikola Perišić - Oct 14
We're a place where coders share, stay up-to-date and grow their careers.
How to declare the optional function parameters in JavaScript?
JavaScript is a versatile language that offers various methods to enhance the flexibility and adaptability of your code, especially when dealing with function parameters. Optional parameters in functions make your functions more flexible and easier to work with, allowing you to specify arguments that may or may not be passed when the function is called. In this article, we will delve into how you can declare optional function parameters in JavaScript, making your journey into web development smoother and more efficient.
Understanding Optional Parameters
Optional parameters allow functions to be called with fewer arguments than defined in the function’s declaration. This feature can significantly simplify your code, making it more readable and maintainable. Let’s explore the various methods to achieve this in JavaScript.
Using Default Parameter Values
One of the most straightforward methods to declare optional parameters is assigning default values directly in the function signature. This feature was introduced in ES6 (ECMAScript 2015) and provides a clean and concise way to handle undefined parameters.
This method ensures that if the username parameter isn’t provided, it defaults to 'New User' .
Leveraging the Logical OR Operator (||)
Before ES6, a typical pattern to assign default values to parameters involved using the logical OR operator within the function body.
This technique checks if username is truthy; if not, it defaults to 'New User' . However, this approach can lead to unintended results with falsy values like 0 , null , or '' (empty string).
Using the arguments.length Property
Another way to handle optional parameters is by checking the arguments.length property, which returns the number of arguments passed to the function.
This method is more verbose and less preferred compared to default parameters.
Destructured Parameter with Default Value Assignment
With ES6, you can also use destructuring assignment in function parameters to specify default values, offering a more powerful and flexible way to deal with optional parameters, especially when dealing with objects.
This approach is beneficial when your function needs to accept multiple parameters encapsulated within an object.
Passing undefined vs. Other Falsy Values
It’s important to note that passing undefined to a function with default parameters will trigger the default value, whereas other falsy values ( null , 0 , false , NaN , '' ) will not. This distinction is crucial for understanding how default values work compared to other methods like the logical OR operator.
Antipatterns in Declaring Optional Parameters
Overusing arguments object without default parameters.
Before ES6 introduced default parameter values, a common approach was to rely heavily on the arguments object to manually check for and assign default values to parameters. This method can lead to verbose and hard-to-read code.
Why to avoid : This approach clutters the function with manual checks and makes it difficult to immediately understand the function’s parameters and their default values.
Misusing the Logical OR Operator for All Types of Default Values
Using the logical OR operator ( || ) to set default values works well for strings and numbers but can lead to unexpected results with boolean parameters or other falsy values that are valid inputs.
Why to avoid : This misuse fails to distinguish between a false value passed intentionally and the absence of a value, leading to incorrect assignment and potentially buggy behavior.
Not Using Default Parameters for ES6 and Beyond
Ignoring the default parameter syntax available in ES6 and continuing to use older patterns for default values is a missed opportunity for cleaner, more readable code.
Why to avoid : This not only makes the code more verbose than necessary but also overlooks the improved readability and functionality provided by ES6 features.
Relying on Undefined to Trigger Default Parameters
Explicitly passing undefined to trigger a default parameter can be confusing and lead to code that’s harder to understand, especially for those new to JavaScript.
Why to avoid : While technically correct, it’s clearer and more intuitive to omit the argument altogether if you wish to use the default value.
Final Thoughts
Declaring optional parameters in JavaScript functions enhances their flexibility and usability. Whether you’re using ES6 features like default parameter values and destructuring assignments or older patterns like the logical OR operator and the arguments.length property, understanding these techniques is vital for writing effective and efficient JavaScript code.
By mastering optional parameters, you’ll be able to create more versatile and robust functions, improving the overall quality of your web applications. Remember, the choice of method depends on your specific needs and the JavaScript version you’re working with, so choose the one that best fits your scenario.
Happy coding!
How to set focus on an input field after rendering in React
Passing props to child components in react function components, how to loop inside react jsx, how to validate an email address in javascript, what is the difference between typeof and instanceof in javascript, how to conditionally add attributes to react components.
COMMENTS
You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values, ??= also applies the default value if the property has value null.
In this article, I'm going to teach you how to use three advanced JavaScript operators: the Nullish Coalescing, Optional Chaining, and Destructuring Assignment operators. These three operators will help you write clearer and less error-prone code.
With ES5: function myFunc (a,b) { b = b || 0; // b will be set either to b or to 0. This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''.
To indicate optional key, you can assign to it null, if the condition is false const someCondition = true; const obj = { requiredKey1: 1, requiredKey2: 2, optionalKey1: someCondition ? 'optional' : null }; console.log(obj);
In this tutorial, you'll learn about JavaScript logical assignment operators, including logical OR assignment operator (||=), logical AND assignment operator (&&=), and nullish assignment operator (??=).
The optional chaining ?. is not an operator, but a special syntax construct, that also works with functions and square brackets. For example, ?.() is used to call a function that may not exist. In the code below, some of our users have admin method, and some don’t:
Declaring optional function parameters in JavaScript means defining function parameters that aren’t required when the function is called. You can assign default values to these parameters using the = syntax, so if no argument is provided, the default value is used instead.
Only if the value of x is nullish then the value of y will be assigned to x that means if the value of x is null or undefined then the value of y will be assigned to x. Let’s discuss how this logical nullish assignment operator works.
With the optional chaining if a certain property doesn't exist then undefined is returned immediately. The optional chaining ?. syntax has three forms: obj?.prop – returns obj.prop if obj exists, otherwise undefined.
One of the most straightforward methods to declare optional parameters is assigning default values directly in the function signature. This feature was introduced in ES6 (ECMAScript 2015) and provides a clean and concise way to handle undefined parameters.