Home > Net >  After the import a variable became a constant
After the import a variable became a constant

Time:06-13

package.json

{
  "type": "module"
}

users.js

let users = ["Jack", "Mary"];

export default users;

index.js

import users from './users.js';

users = [];

After executing index.js I get an error:

users = [];
      ^

TypeError: Assignment to constant variable.

Why? The users was clearly defined as a variable not a constant.

CodePudding user response:

  import users from './users.js';

is similar to

const users = ...

in that you cannot assign the value afterward. It's not quite the same because the values can change, but they can only be changed from inside the module. so inside users.js

let users = [];

export const setUser(newUsers) {
  users = newUsers
}

export {users, setUser);

index.js

import {users, setUser} from './users.js'

console.log(users);
console.log(setUser(["a", "b", "c"]));

CodePudding user response:

As @pilchard explained, to accomplish my task I need to change this array inside the module. That's because values that I import are read-only outside the module. Docs.

users.js

let users = ["Jack", "Mary"];

function emptyUsers() {
    users = [];
}

export { users, emptyUsers };

index.js

import { users, emptyUsers } from "./users.js"
console.log(users); // ["Jack", "Mary"]

emptyUsers(); // instead of users = [];
console.log(users); // []

users.push('Ricky'); // Also I can still change the values of the imported array
console.log(users); // ['Ricky']

CodePudding user response:

try to import as different name:

import users as u from "./users.js"
  • Related