skip to Main Content

In javascript(node JS), I have made a config.js file like below for export a name variable

Config.js

export let name ="ayush";

and I am importing the name variable in index.js file

index.js

import {name} from "./config.js";

name ="Rishabh"

console.log(name);

But I am getting Type Error:assignment to constant variable.

I have declared a variable as Let , then why still I am getting above error.

I am trying to change the variable name in another file. but I am getting the error, not able to understand what javascript concept is missing like (import is only read only).

2

Answers


  1. Remember in your index.js file you are reassigning name variable imported from config.js file which is not allowed.

    You should use an object instead of a primitive value, because properties of an object can be modified even when the object itself is imported as a constant.

    Do this for Config.js

    export let config = {
      name: "ayush"
    };
    

    Then do this for index.js

    import { config } from "./config.js";
    
    config.name = "Rishabh"; // modify the property of the object
    
    console.log(config.name); // logs "Rishabh"
    

    Try this I hope it will work.

    Login or Signup to reply.
  2. In JavaScript, imported bindings are read-only. You cannot change their value in the module where they are imported.

    This is because exporting mutable variables can lead to unpredictable behavior and bugs.

    If you want to share a common object, which also need to be mutable, export a const object and modify the properties of it instead.

    config.js

    export const obj = {
        name: 'xxx'
    };
    

    index.js

    import {obj} from "./config.js";
    
    obj.name ="Rishabh";
    
    console.log(name);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search