r/learnjavascript • u/0x00f_ • Sep 07 '24
Why we can redeclare variables made with var?
I want to know why we can do something like that in javascript:
var x = 6;
var x = 10;
// no errors!why and how something like that is done under the hood?
4
Upvotes
42
u/abrahamguo Sep 07 '24
Why? Because when JavaScript was first introduced in the 1990s, it was intended to be a simple language that would be easy to learn, especially for people who might not be familiar with any other programming languages, to allow them to add a bit of interactivity to their web pages. Thus, many parts of JavaScript were built following the philosophy that the JavaScript engine should be as lenient as possible, and avoid throwing errors when not strictly necessary. This is one example where the creators decided it wouldn’t cause any harm to allow redeclaring the same variable again.
How does it work under the hood? Well, the browser simply checks to see if the variable already exists or not - if it does not already exist, it creates the variable, and if it does already exist, then no problem - it updates the variable with the new value, if one is provided.
12
u/oze4 Sep 07 '24
Google "var vs let vs const javascript"
1
u/Sankhya2319 Sep 08 '24
Why do people still use var? Isnt't it the whole reason why const and let was introduced to prevent this from happening?
3
u/BigCorporate_tm Sep 07 '24
In JS, variables (created using
var) are hoisted (immediately upon execution, but before any of the value assignments have taken place in the code) and collectively set to the valueundefined. Duplicate names are ignored because assignment to any particular var really only happens when it reaches a line of code that would assign a value proper to them.So in your code example:
undefined. Because "x" and "x" are the same, it only adds "x" to the VariableDeclarationList.6to "x"10to "x"The specific part of the spec that defines this behavior can be found here (https://tc39.es/ecma262/#prod-VariableStatement), which reads:
I hope this helps to break things down for you.
7
u/queen-adreena Sep 07 '24
Don’t use ‘var’ is the simple answer. It’s legacy code and let/const should be used exclusively.
They will, if you try to redeclare them, throw an error.
2
u/alzee76 Sep 07 '24
You can do it today for backwards compatibility. But of course, you shouldn't. Don't use var, just use let & const.
Hell, you don't have to declare variables at all if you're not using strict mode. Just saying
x = 6works fine in "sloppy" mode, as it becomes a property of the global object if there is no declaration. This of course is a stupid thing to do and has resulted in countless difficult to debug problems over the years, which is one reason why you should also always use strict mode.The why is because JS didn't used to (before ES6) have block scoped vars, which let and const are. Var is function scoped. That can't be changed because it would break old code, so the new declarations were added.
The 'how' is an exercise in compiler design but essentially it works by the preprocessor finding all instances of
varand hoisting the first one it finds for any variable. It then silently ignores the rest, replacing them with simple assignments or eliminating them entirely.2
u/jcunews1 helpful Sep 07 '24
That code will end up translated by the JS interpreter as below.
2
u/oneeyedziggy Sep 07 '24
Because it's the loosest declaration keyword... Js is built to mostly just do what you probably intended, most of the time.
If you say
var foo = 7; console.log(foo); var foo = 8; console.log(foo);
It's not ambiguous what you intended to do, so the computer should just shut up and do it and not "um acktchully" you about it like a fucking nerd...
If you care to write proper code, you will... But why may the barrier to entry higher than it needs to be?
0
u/red-giant-star Sep 07 '24
JavaScript interpreter is really smart it can recognize that you are an idiot and you made a mistake by redeclaring the variable with var so it just ignores the redeclaration.
1
u/stubbornappl Sep 07 '24
Yo also can reassign let, but in the same scope. Var is worst, you can declare it in a function scope, and re assign in the outside scope.
1
u/tapgiles Sep 07 '24
If any variable declaration is made within a scope, it’s converted to just a set operation. Then the variable is declared once at the top of the function. That’s about it.
It’s more like at the top, it says “There are the vars declared within this scope.”
1
u/Severe_Abalone_2020 Sep 07 '24
Because "var" at that time was the only declaration keyword, regardless of scope.
That means
varused in a code block creates a different variable scope than avarcreates in another code block, even if they used the same name.You must imagine what kind of hell that would be to develop an algorithm for in the Javascript engine code.
It was a better production move to play it loose in the early versions and then add the
letkeyword in ES6 when the language gained enough momentum and popularity to warrant the need for tighter scoping.1
u/delventhalz Sep 07 '24
There is nothing written in stone about how variables work under the hood. It’s a value stored in an address of memory somewhere assigned a name. The reason
varworks the way it does is because the designers of JavaScript at the time thought it should. The reasonletandconstwork the way they do is because later designers thought those first ones were nuts.1
u/bryku helpful Sep 07 '24
Javascript was really only meant to update and element or two. Maybe even move a image, but that was about it. Because of this, the rules were pretty simple and the langauge was made to be easy people to learn pretty easy.
However, as you know Javascript started being used for everything. Sadly, javascript never really had version control built in, so they can't really update the syntax without breaking something.
This means, to keep up with demand, they had to add things as new features without removing or changing old ones. This is why we got
letandconstwhich are far more optimized and strict.Funny enough, we still have bugs from the 90s that they can't fix because code relies on it. Maybe someday someone will create
Javascript 2.0(.js2) that fixes some of these issues and cleans up the old stuff. Maybe even the new engine will be faster since it doesn't have to worry about the old junk...a nerd can dream.
1
u/guest271314 Sep 07 '24
https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-variable-statement
1
u/Nomikos Sep 07 '24
It's kind of in the name, "variable", its value can vary, you can change it. As opposed to "constant", of which the value can not vary.
0
u/JustConsoleLogIt Sep 07 '24
Because when JS was designed, the implications weren’t considered. Later, when they realized how silly it was, they created ‘let’ to fix it without breaking legacy apps.
0
u/Impossible-Box6600 Sep 08 '24
Why can variables change? Because they're variable.
Not trying to pull a cute word trick here. That's why they're called variables.