3

I would like to do something like having cyclic dependencies. In order to do that, I have to resort to something like this:

// x.js

let y

exports.setY = function(_y) {
  y = _y
}

// y.js

const x = require('./x')

x.setY(exports)

This sort of cyclic dependency problem happens all the time in database models, this referencing that, that referencing this. Ignore any ideas you might have on whether or not this specific use case of cyclic dependencies is a good idea, I'm more wondering if there is a way to convert a variable to a const in JavaScript after it has been declared. As in the let y, after it is set, set it to a const.

Is anything like this possible? I would like to do this to get performance benefits as the key thing, I don't care about compile time checking benefits in this situation. Is there a way to make these two variables be compiled so they are maximally efficient?

4
  • No, a variable can only be declared once. Commented Mar 4, 2021 at 8:57
  • I don't think so you can do that javascript doesn't allow that change but what you can do is you can assign its value to a new const variable. Commented Mar 4, 2021 at 8:57
  • There's no magic tricks you can do with dynamically compiling with new Function? Commented Mar 4, 2021 at 8:57
  • Maybe something tricky with eval? Within a specific scope of course, like a module's scope. Commented Mar 4, 2021 at 9:07

1 Answer 1

3

You could put your value in an object and freeze it:

Object.freeze()

From site:

The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed.

  const test = { name: "" };
  function setTestName(name) {
      test.name = name;
      Object.freeze(test);
  }

Why you should use it is discussed here: Why would I need to freeze an object in JavaScript?

Sign up to request clarification or add additional context in comments.

2 Comments

A freezes forbids changes in the object. const forbids reassignments. test = 5 is still possible in your code.
Does freeze offer performance benefits?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.