2

I have set:

const [c, d ] = ["h", "i"]

in the browser console. It returns undefined.

After that, when I type c it returns "h", and when I type d it returns "i".

To me it looks like an object where I have set the value of c and d according to ["h", "i"] 's order

I have been learning Javascript for the past 9 months. I am not sure what am I missing? Why it's behaving like this?

  • You're using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), you're not actually setting one array to another. – Nick Parsons Dec 22 '19 at 13:58
  • you can invent all the code writing you want, but do not expect that they can match the syntax rules of any language, even javascript – Mister Jojo Dec 22 '19 at 14:00
  • Why do you need to enter this into the console? )) – AlexDevTime Dec 22 '19 at 14:01
  • I was learning react hooks and I saw this in "useState" and when creating a new hook with the instructor. I was confused by this "const [state, setstate] = useState(false); –  Dec 22 '19 at 14:05

4 Answers4

2

You are using destructuring - a great feature to directly get named access to nested properties of an Object or an Array:

const car= {
    color: 'blue',
    power: '120HP',
    brand: 'an awesome one'
};

// Object Destructuring
const { colorOfCar, powerOfCar, brandOfCar} = car;

You are then directly able to work with each of these variable names. It is more or less short for:

const colorOfCar = car.color;
const powerOfCar = car.power;
const brandOfCar = car.brand;

Hoping it is helpful!

Update: An Array can be destructured the following way:

const rgb = [255, 200, 0];

// Array Destructuring
const [red, green, blue] = rgb;

Short for:

const red = rgb[0];
const green= rgb[1];
const blue= rgb[2];
Kennuel
  • 169
  • 7
1

You are using destructuring assignment. Then variable c = arr[0], d = arr[1]

If you need to copy array:

const newArr = arr.concat();
AlexDevTime
  • 166
  • 4
0

If you are trying to set one array to equal another array all you need is:

const c = ["h", "i"];
const d = c;
jpmc
  • 1,147
  • 7
  • 18
0

This statement

const [c, d ] = ["h", "i"]

is destructuring, which is not an array assignment. It doesn't read as

"an array having the elements c and d will be assigned the values of h and i"

but it reads as

"The array having the values of h and i are destructured into variables called c and d, respectively."

Hence, the result is not an array, nor an object, but two variables. You can use babeljs.io to check the equivalent of your code:

"use strict";

var c = "h",
    d = "i";
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175