Is there a way to handle null in spread operator, without specifying if and else?
In following scenario, I want to spread assignedStudents
only when it's not undefined.
If I do it without using if else, I get the error:
TypeError: Invalid attempt to spread non-iterable instance
To handle this, I am using if else, but thinking there is a better/elegant way of doing this.
let questions;
if (assignedStudents) {
questions = [
...assignedStudents,
{
questionId: randomId,
question: ''
}
];
} else {
questions = [
{
questionId: randomId,
question: ''
}
];
}
Is there a way to handle null in spread operator, without specifying if and else?
In following scenario, I want to spread assignedStudents
only when it's not undefined.
If I do it without using if else, I get the error:
TypeError: Invalid attempt to spread non-iterable instance
To handle this, I am using if else, but thinking there is a better/elegant way of doing this.
let questions;
if (assignedStudents) {
questions = [
...assignedStudents,
{
questionId: randomId,
question: ''
}
];
} else {
questions = [
{
questionId: randomId,
question: ''
}
];
}
Share
Improve this question
asked Oct 13, 2020 at 4:46
SimsonsSimsons
12.7k49 gold badges159 silver badges283 bronze badges
2
-
3
You can initialise
assignedStundents
to an empty array, for example. – VLAZ Commented Oct 13, 2020 at 4:49 - ECMASrcipt2020 has the null coalesce operator (??) which checks for null and undefined and returns the right hand operator if that is the case. you may check that out – ritesh sangani Commented Oct 13, 2020 at 6:32
3 Answers
Reset to default 17Do you mean something like this using the nullish coalescing operator
const questions = [
...(assignedStudents ?? []),
{
questionId: randomId,
question: ""
}
]
Of course, this won't protect you if assignedStudents
is non-iterable (like a Number
or Object
). It's not as fancy but if you only want to act on an array, check it with Array.isArray()
const questions = [
...(Array.isArray(assignedStudents) ? assignedStudents : []),
{
questionId: randomId,
question: ""
}
]
Since you've tagged this question with typescript, you should be marking assignedStudents
as a nullable array, eg
assignedStudents?: Something[]
in which case the above isn't a problem any more.
There are so many ways to do it.
Your current approach has a flaw, let's say when assignedStudents is not nullish but non-iterable, you will still get an error.
Example, assignedStudents is -1, if-statement will go through and it will be an error.
The safest way should be to check if assignedStudents is an array, if it is not, then spread an empty array.
questions = [
...(assignedStudents instanceof Array ? assignedStudents : []),
{
questionId: randomId,
question: ""
}
]
you may use this expression [...(this.options || [])], where options is array