Javascript - What is the output: Read-Only Bindings?

Question

What is the output of the following code?

// moduleFile.js    starts here 
export var message = "Message from moduleFile"; 

export function setMessage(newText) { 
    message = newText; 
} 
// moduleFile.js    ends here 

// file.js 
import { message, setMessage } from "./moduleFile.js" 
console.log(message);          

setMessage ("New Message"); 
console.log(message);        

message = "This is another message";      


Click to view the answer

Message from moduleFile
New Message
message = "This is another message";      // error

Note

ES6 import statements only produce read-only bindings to the corresponding variables, functions, or classes.

Therefore, the module that imports them cannot change its value.

But the module that exports an identifier can make changes to it. For example,

In the above example, we import two bindings from the module, message and setMessage.

The function setMessage() can change the value of the variable message but when you try to directly change the value it throws an error.

Related Quiz