What is the correct way of declaring and using constants in Lightning Components.

I am seeing different behaviours depending on organisations I am in.

Basic way of having pass-by-value and immutable variables in JS is:

let state = [1,2,3] const initState = Object.assign([], state)

However, after assigning both to different aura attributes, I am seeing somehow initState getting modified too, which should be impossible in first place for two reasons - it's a constant AND it's been cloned.

Does Lightning framework does something to override this behaviour?

Edit: The most obvious solution could be using unbound expressions in default parameter on aura:attribute:

<aura:attribute type="Object[]" name="data"/>
<aura:attribute type="Object[]" name="initData" default="{#v.data}"/>

Unfortunately that doesn't seem to work. Possibly because it assigns initial state of undefined and stop further assignments.

  • I think we need to see more source code. I will tell you this: const doesn't protect an object's properties from being modified; it literally only protects the reference from being updated. You can use const in a function and it works as const should, but it doesn't do what I think you think it does. Including some simple code we can copy-paste in to a component that demonstrates your problem would be ideal. – sfdcfox May 15 '17 at 12:27
  • @sfdcfox I realised one thing tomorrow - Object.assign() is a shallow clone - only surface properties are copied by value, deeper ones are copied by reference. It's a known issue with JS. – dzh May 16 '17 at 1:34

We copy the attributes from the default values when we create new instances of the components. Otherwise, a change to one instance would effect changes in others.

If you do not want an attribute changed, make it a function call value.

<aura:attribute type="Integer" name="initData" default="{!1+1}"/>

This should prevent anyone from being able to change initData

cmp.set("v.initData", 5); // Ignored.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.