-1

I am doing a tutorial, and there is some code there that i am not sure i understand:

const Numbers = (props) => {
    return (
        <div className="card text-center innline">
            { Numbers.list.map((number, i) => 
                <span key={i}>{number}</span> 
            )}
        </div>
    );
};
Numbers.list = _.range(1,10);

I understand correctly that a constant can not be modified after creation, but what is the Number.list doing on the last line of the code. Is it adding a list to the Numbers function, or are those to separate objects?

Gargod
  • 29
  • 1
  • 3
  • 1
    Possible duplicate of [Why can I change value of a constant in javascript](https://stackoverflow.com/questions/23436437/why-can-i-change-value-of-a-constant-in-javascript) – JJJ Jan 10 '19 at 08:32
  • JJJ i am not asking about why i cant change a constant, i am asking what happens in the code. Van answered it for me – Gargod Jan 10 '19 at 12:42
  • The duplicate explains the exact same thing. – JJJ Jan 10 '19 at 14:58

3 Answers3

1

const keyword will create an immutable binding not an immutable variable, i.e. if you assign a new property it won't return an error but if you try to assign a new value to the variable like Numbers = {} then it will return an error.

So it is possible to assign a property like above code row Numbers.list = _.range(1,10);.

And in the code above, running Numbers() to execute the function after assigning Numbers.list will be successful and correctly returning a jsx container with 10 span elements. However, if you run Numbers() without assigning the list property beforehand, it'll throw an error as Numbers.list is undefined.

Van
  • 636
  • 3
  • 14
0

Javascript constants can't be reassigned, but the value inside it can be edited, especially if those are objects.

The row:

Numbers.list = _.range(1,10);

doesn't reassign Numbers, but it's assigning a value to Numbers.list.

0xc14m1z
  • 3,675
  • 1
  • 14
  • 23
0

JavaScript functions are objects and act as such. Numbers.list = ... adds list property to Numbers. Numbers is a function that has Numbers.list array property, which is an object, too.

const Numbers = ... assigns Numbers with function (object) reference and prevents a variable from being reassigned. It doesn't prevent an object from modifications, unless an object has been frozen with Object.freeze.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565