JavaScript, as it continues to evolve, is constantly introducing new features to improve code management, especially when working with complex and nested objects.
In addition to the already known tools such as Optional Chaining (?.
) and Optional Chaining Assignment (??=
), a recent proposal under discussion, the ECMAScript Safe Assignment Operator Proposal, aims to make the language even safer and more readable in conditional assignment situations.
🔗 Do you like Techelopment? Check out the site for all the details!
What is Optional Chaining (?.) ?
Optional Chaining (?.
) was introduced to simplify access to properties of deeply nested objects or arrays, which may not exist or have null
or undefined
values. The operator allows access to these properties without the risk of generating TypeErrors.
Here is a typical example:
let user = {
profile: {
name: 'Shania'
}
};
// Safety access to 'name'
let userName = user?.profile?.name; // 'Shania'
If user
or user.profile
were null
or undefined
, accessing userName
would return undefined instead of causing an error.
Advantages of Optional Chaining
-
Error prevention: Avoid errors such as
TypeError: Cannot read property of undefined
. -
More concise code: Reduces the need for numerous
&&
orif
statement checks. - Safe access to methods or properties: Can also be used to call methods or access array elements, without explicit checks.
What is Optional Chaining Assignment (??=) ?
Optional Chaining Assignment (??=
) is an extension of the Optional Chaining concept, introduced to simplify the assignment of default values to variables that could be null
or undefined
.
With the syntax ??=
, we can assign a value only if the variable in question is null
or undefined
. For example:
let settings = null;
// Assign a default object only if settings is null or undefined
settings ??= { theme: 'dark', notifications: true };
console.log(settings); // { theme: 'dark', notifications: true }
In this case, settings was null
, so a default value was assigned. If settings had already had a value other than null
or undefined
, the assignment would not have occurred.
Difference with OR Assignment Operator (||=
)
A similar operator is ||=
, which assigns a value to a variable only if it is "falsy", that is, if its value is one of false
, 0
, ""
, null
, or undefined
. In contrast, the ??=
operator works exclusively with null
or undefined
.
Here is a comparative example:
let count = 0;
count ||= 10; // count remains 10 because 0 is considered "falsy"
console.log(count); // 10
count = 0;
count ??= 10; // perform assignment because count is not null or undefined
console.log(count); // 0
ECMAScript Safe Assignment Operator Proposal
The ECMAScript Safe Assignment Operator Proposal is a proposal currently under discussion that builds on the concept of safe assignment. The idea behind this proposal is similar to the existing conditional assignment operators (??=
and ||=
), but with the goal of further improving the safety of the language in assignment operations.
Goal of the Proposal
The main idea of this proposal is to create an operator that not only performs conditional assignment, but does so in a "safe" way. This means that the operator would not allow assignments to be made that do not meet certain conditions or safety criteria.
The proposal provides a mechanism that allows assignments to be made only if the variable is "safe", that is, not only not null
or undefined
, but also conforms to a certain validity context. The operator would act similarly to a "safe guard", applicable to ensure that assignments respect consistency criteria in the code.
Theoretical example
Suppose the proposal includes a new operator ?=
(similar to ??=
, but with more thorough checks):
let age = -1;
// Safe assignment: assign the value only if it is "safe" (for example, a positive number)
age ?= 18;
console.log(age); // Returns 18 only if -1 is considered unsafe, otherwise it keeps the original value
In this theoretical example, the ?= operator would have the function of checking not only whether age is null or undefined, but also whether it is a valid value in the context of the application (for example, an age cannot be negative).
How to avoid try/catch
The proposal also aims to avoid the need for try/catch
blocks to handle errors when assigning variables or properties. The central idea is that the "safe" assignment operator performs checks and validation implicitly, without having to resort to more complex workarounds like try/catc
h blocks.
Let's see a theoretical example of how the Safe Assignment Operator could work to avoid try/catch
.
Suppose we have a function that calls an API to get information about a user. This API might return an error, missing data, or invalid values, and we want to handle this behavior without using an explicit try/catch
block. Also, in case of an error or invalid response, we want to use a default value.
Without Safe Assignment Operator: Using try/catch
Normally, we would use try/catch
to handle errors when calling the API:
async function fetchUserData() {
try {
let response = await fetch('https://api.example.com/user');
let data = await response.json();
if (!data || !data.name) {
throw new Error('Username not available');
}
return data;
} catch (error) {
console.error(error.message);
return { name: 'Unknown user' }; //Fallback value on error
}
}
let user = await fetchUserData();
console.log(user.name); // 'Unknown user' if call fails
In this code:
- If the API call fails or
data.name
is not available, we usetry/catch
to catch the error and return an object with a fallback name.
With Safe Assignment Operator: Without try/catch
Now let's simulate the behavior of the (theoretical) Safe Assignment Operator to avoid explicit error handling with try/catch
. The theoretical operator ?=
allows to assign only if the value is safe and valid. If the API returns an error or an invalid value, we will avoid the assignment without needing to block the execution.
Here's how it could work:
let user = { name: 'Unknown user' }; //default value
// API call
let fetchedUser = await fetch('https://api.example.com/user')
.then(res => res.json())
.catch(() => null); // If there is an error, we return null
// We assign the name only if fetchedUser exists and has a valid 'name' property
user.name ?= fetchedUser?.name;
console.log(user.name); // 'Unknown user' if fetchedUser is null or name is invalid
How it works:
-
let fetchedUser = ...
: We make an API call that can fail. If the call fails, the.catch()
block returnsnull
instead of throwing an exception. -
user.name ?= fetchedUser?.name
: This is where the theoretical Safe Assignment Operator comes into play. The user name is assigned only iffetchedUser
is notnull
orundefined
and if it has a valid name property. Otherwise, the assignment fails anduser.name
remains unchanged (the default value isUnknown user
).
What's different from try/catch?
-
No explicit
try/catch
block: No need to manually catch the error. -
Safe assignment: With the Safe Assignment Operator,
user.name
is updated only iffetchedUser?.name
is a valid value. In case of an error or empty response, there is no risk of errors or unwanted assignments. -
Cleaner code: No need to write explicit logic to check if
fetchedUser
or its fields are valid.
Potential Impact
If this proposal were adopted, it could have a major impact on JavaScript development, allowing for even more robust code and preventing errors arising from unsafe assignments or assignments that are inconsistent with logical requirements.
Follow me #techelopment
Official site: www.techelopment.it
Medium: @techelopment
Dev.to: Techelopment
facebook: Techelopment
instagram: @techelopment
X: techelopment
telegram: @techelopment_channel
youtube: @techelopment
whatsapp: Techelopment
References
https://github.com/arthurfiorette/proposal-safe-assignment-operator?tab=readme-ov-file