5

I'm working on a react native project, I found a solution on internet to my problem but I don't understand one line from a function

componentDidUpdate(propsOld) { // line 1
    const { fill } = this.props;  // line 2
    const { fill:fillOld } = propsOld; // line 3

    if (fill !== fillOld) { // line 4
      Animated.timing(this.anim, { toValue:fill, duration:2000 // line 5 }).start();
    }
}

The line that I don't understand is the line 3:

const { fill:fillOld } = propsOld;

I understand the use of curly braces when there is a single variable or multiple variables seperated by comma ',',

Would anyone please explain to me the meaning when they are separated by colon ':' ?

M Reza
  • 18,350
  • 14
  • 66
  • 71
Souhaieb
  • 559
  • 8
  • 12
  • Possible duplicate of [What does ':' (colon) do in JavaScript?](https://stackoverflow.com/questions/418799/what-does-colon-do-in-javascript) – Andrew Fan Jan 22 '19 at 15:21
  • Possible duplicate of [Use of Colon in object assignment destructuring Javascript](https://stackoverflow.com/questions/51959013/use-of-colon-in-object-assignment-destructuring-javascript) –  Jan 22 '19 at 15:23

2 Answers2

8

basically that is renaming a variable when destructuring the object.

if you have an object like this:

const obj = {
    prop1: 'prop1',
    prop2: 'prop2',
    prop3: 'prop3',
}

and you want to get your variable prop2, you can do it like this:

const { prop2 } = obj;

but what if you already defined something with the same name? a block like this where you have prop4 defined and you want to get that variable when destructuring?

const prop4 = 'something';
const obj = {
    prop1: 'prop1',
    prop2: 'prop2',
    prop3: 'prop3',
    prop4: 'else'
}

you can not do: const { prop4 } = obj; because prop4 already exist and also it is a const

so basically you can rename it like this:

const { prop4: prop4duplicated } = obj;

so basically, on your code:

const { fill } = this.props;
const { fill:fillOld } = propsOld;

it is generating 2 variables, fill and fillOld, that is because fill already exists, then it is being renamed to fillOld

Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19
2

Using a colon instead of a comma is that it created an alias for fill. So fill can now be referenced as fillOld. So if I wanted bill to be known as fred I would do { bill:fred }

Oriol Roma
  • 329
  • 1
  • 5
  • 9