Reputation: 5111
I have a following variable:
const x = ['item']
Then I tried using Babel's real-time compiler and it gave me the following compiled code:
"use strict";
var x = ["item"];
Now when I try to assign something else (x = {}
) to the variable x
, it throws me the error. I don't see anywhere like how can't I change x
in the compiled code! In general, var
are editable right?
Can anyone help me understand this?
Upvotes: 0
Views: 252
Reputation: 116110
If I try the babel output, I can assign a new value to x and it just works. The reason for that, is that the outputted code is ECMAScript 5, and doesn't have the concept of consts. You can try it out by changing const to var in the 'JavaScript Demo: Statement - Const' example on MDN.
So, babel will compile (or "transpile") it as an assignable variable, because there is no other way. But in the process of doing that, it verifies your original code to see if you don't do an assignment to x, and throws an error if you do.
Babel checks whether you use it as a constant in the compilation process, but in the final code, x being constant is no longer enforced, so you could easily break this by modifying the outputted code.
For comparison, the same goes for any compiler. If you take a hex editor and modify an executable, you can also break anything the compiler did when making the executable. In fact that is true for the output of every program if you modify it after the program is done (think of images, documents, ...)
Upvotes: 3
Reputation: 13
You are correct. var is editable in general. I believe you are facing this issue during the compilation. During babel compilation, it is doing this safety check for const variables. Same thing happens in typescript as well.
Upvotes: 0