skip to Main Content
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


  1. 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.

    Login or Signup to reply.
  2. 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 an array.

    Refer the code below:

    const object4 = {
      message:'Good Job',
      price:799
    }
    
    const {message,price}=object4;
    
    console.log(message)    // Outputs - Good Job 
    console.log(price)      // Outputs - 799  
    
    const [a,b]=[1, 2];     // Assigning via array
    
    console.log(a)          // Outputs - 1  
    console.log(b)          // Outputs - 2  
    
    const {c,d}={c:3, d:4}; // Assigning via object
    
    console.log(c)          // Outputs - 3  
    console.log(d)          // Outputs - 4  
    Login or Signup to reply.
  3. The error you got refers to 2 (not 1!). This 2 is not expected after the comma, since the comma is here a separator for multiple declarations, like you would have here:

    const {a,b} = 1, {c,d} = 2;
    

    or

    let {a, b} = 1, c
    

    These are valid syntax, but not what you intended. Here 1 is coerced into an object (a Number instance), and the values of its undefined a and b keys are assigned to the variables a and b, and so they will be undefined. In the second example, c will just be defined with no initial value (so undefined). Again, it does not form a "tuple" with 1: 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 and b. For that you should use an array literal and array destructuring syntax:

    const [a, b] = [1, 2];
    
    Login or Signup to reply.
  4. 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.

    const [a, b] = [1, 2];
    
    console.log(a); // Output: 1
    console.log(b); // Output: 2
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search