const object4={
message:'Good Job',
price:799
}
const {message,price}=object4;
console.log(message)
console.log(price)
In this code we are assigning the value 'Good Job'
to the variable message
and 799
to price
.
When I try to do the below code it shows an error:
const {a,b}=1,2;
console.log(a)
the output for this line is
SyntaxError: Unexpected number
What should I do?
4
Answers
You’re trying to destructure from numeric literals (1 and 2). Destructuring works with objects or arrays, not individual numbers.
You can assign individual variables to both and then have to print.
Yes, you can assign values to multiple variables at a single glance. The syntax you have used in your second attempt is wrong. You’re assigning the values to multiple variables using object restructuring, Therefore, the values must come from an
object
or anarray
.Refer the code below:
The error you got refers to
2
(not1
!). This2
is not expected after the comma, since the comma is here a separator for multiple declarations, like you would have here:or
These are valid syntax, but not what you intended. Here
1
is coerced into an object (aNumber
instance), and the values of its undefineda
andb
keys are assigned to the variablesa
andb
, and so they will beundefined
. In the second example,c
will just be defined with no initial value (soundefined
). Again, it does not form a "tuple" with1
: the comma is a separator for separate declarations.However, it looks like you intended the comma to combine two values to be assigned in
a
andb
. For that you should use an array literal and array destructuring syntax:The problem is using object destructuring with primitive values. Object destructuring requires an object on the right-hand side. To assign multiple values to variables at once, use array destructuring instead.