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?
12
u/oze4 Sep 07 '24
Google "var vs let vs const javascript"
3
u/tsunami141 Sep 07 '24
Holy hell
4
u/oze4 Sep 07 '24
What?
1
u/daBEARS40 Sep 07 '24
It’s a “Google en passant” meme from the chess subreddit
So many people are confused when a pawn moves a weird way that it became a meme and grew from there
1
1
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?
1
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 value undefined. 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:
The all of the named variables, in this case "x", are added to the VariableDeclarationList and assigned to
undefined. Because "x" and "x" are the same, it only adds "x" to the VariableDeclarationList.Your code runs and assigns the value of
6to "x"Your code runs and assigns the value of
10to "x"
The specific part of the spec that defines this behavior can be found here (https://tc39.es/ecma262/#prod-VariableStatement), which reads:
A
varstatement declares variables that are scoped to the running execution context's VariableEnvironment. Var variables are created when their containing Environment Record is instantiated and are initialized to undefined when created. Within the scope of any VariableEnvironment a common BindingIdentifier may appear in more than one VariableDeclaration but those declarations collectively define only one variable. A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer's AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.
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.
1
u/guest271314 Sep 07 '24
Don’t use ‘var’ is the simple answer.
That's not the question.
varis still defined in ECMA-262.4
u/Deep-Cress-497 Sep 07 '24
So is
with, but you shouldn't use that either.-1
u/guest271314 Sep 07 '24
shouldn't
?
Says who?
Not the specification.
2
u/queen-adreena Sep 08 '24
Someone doesn’t know the difference between “shouldn’t” and “can’t”.
1
u/guest271314 Sep 08 '24
I didn't know I had to listen to you and the rest of these people on this board when they say I shouldn't do something in programming. Maybe that's because I don't have to listen to you people and your "shouldn't" speeches - without examples for the people who don't know better. I know better. I was writing code with
varbefore there was aconstorlet, so I'm well-suited to make that determination.You just shout "shouldn't" and don't even know why you are shouting.
1
u/queen-adreena Sep 08 '24
0
u/guest271314 Sep 08 '24
Could be. Smart enough to dismiss somebody in the bleachers shouting what somebody else "shouldn't" do, without examples of why.
2
u/queen-adreena Sep 08 '24
The main reason would be that under "use strict" the use of the
withfunction is blocked.And if you're a programmer in 2024 still coding without strict mode, you should just retire already.
0
u/guest271314 Sep 08 '24
I thought you were shouting about
var?If you are using ECMA-262 Modules you're using strict mode.
Guess what?
varis not prohibited in any part of JavaScript, strict or non-strict mode.Why are you shouting about
var?→ More replies (0)-1
u/guest271314 Sep 07 '24
So is
with, but you shouldn't use that either.import json from "./package.json" with {"type": "json"}4
u/Deep-Cress-497 Sep 07 '24
Seems like you're one of the lucky 10000 today!
An old no-longer-recommended feature in JS is the
withstatement. This was added pretty early on, and was decided as a horrible idea.The idea is that you could put an object into the statement to access all of its properites as variables. While this seemed like a good idea, it causes numerous problems, and is no longer recommended for use.
You can learn more about it at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with
It is this that I am referring to, not the import
with😆-3
u/guest271314 Sep 07 '24
Yes, I know.
with()can still be used.And there is now
withwith Import Attributes.Nowhere in ECMA-262 does it state
varshouldn't be used.it causes numerous problems, and is no longer recommended for use.
Any built-in can cause numerous problems unless you understand what you are doing.
varstill has uses. Moreovervaris still defined in ECMA-262, is not deprecated.3
u/MatthewMob helpful Sep 08 '24
It is not the specs job to define best practices, nor what you should do with your code, it is the specs job to define how browsers behave so that conforming code does not break.
As part of that they will obviously include legacy syntax long, long after they have fallen out of use as older systems must still be able to function correctly.
Just because the spec says you "must be able to" that is a very different statement from "you should", and in this case you shouldn't.
var still has uses.
Such as? There is always a way to refactor code that uses
varto uselet/constand that is what you should do, regardless of whether the spec says you can.0
u/guest271314 Sep 08 '24
I use
varall of the time in DevToolsconsoleto define variables gloablly, then later overwrite them, from the same or different contexts, including Web extension code; inServiceWorkercontexts to define variables globally, so the values can be accessed and overwritten later; Emscripten compiles C, C++, Rust, et al. to a module that usesvarin the compiled JavaScript; depending on the TypeScript/JavaScript bundler,varcan be in the bundled script; et al.
varis still in ECAM-262. Thus, use it.There is no central committee of "best practices". That is an entirely opinionated and subjective concept.
CommonJS is not in ECMA-262 at all, yet Node.js gets accomodations and exceptions in more than one domain for Node.js API's and patterns, and I don't read where developers in general say stop using CommonJS.
Not that I follow what people say about matters of style, or anything else, anyway.
2
u/ungemutlich Sep 08 '24
Thank you. Exactly. Having to refresh the console as a sacrifice to Best Practices because one must never use var is ridiculous.
As someone whose coding is mostly one-off scripts and personal learning projects, it's so annoying having to jump through hoops created by people who can't imagine programming in situations other than their job on a big team.
People can't help themselves answering a "why" question with telling the person what to do, as if mere knowledge of "var" is a danger to be prevented. But actually you'd be better for knowing that function scope exists as an alternative to block scope and for understanding why (function(){})() was a pattern.
1
0
u/guest271314 Sep 08 '24
Who said "best practices"?
There's no central best practices committee who gets to dictate what is "best practices" to everybody else.
I didn't know I was obliged to listent ot people shout "best practices" from the bleachers.
Because I'm not obliged.
No more than the people who use CommonJS because of Node.js are obliged to stop using
require()because that's not in ECMA-262 at all.In other words, people selectively pick and choose what "best practices" they shout about - unless it's about their sacred cow.
Fuck a king or queen and all of their loyal subjects
I'll pull my penis out and I piss on their shoes in public
People, we the pirates, the pride of this great republic
No matter what you order, muhfucka, we're what you're stuck wit
Ooh La La, Run The Jewels
0
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 = 6 works 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.
why and how something like that is done under the hood?
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 var and hoisting the first one it finds for any variable. It then silently ignores the rest, replacing them with simple assignments or eliminating them entirely.
0
Sep 07 '24
[deleted]
3
1
u/alzee76 Sep 07 '24
Except when you need to change the value of the variable, because it's a variable which needs to vary, as the name implies. ;)
0
Sep 07 '24
[deleted]
2
u/alzee76 Sep 07 '24
for (let x = 0; x < arbitrary_val; x += arbitrary_const)Can you do that some other way? Sure. Is there a good reason to? Not really. Other simple examples abound.
0
Sep 07 '24
[deleted]
2
u/alzee76 Sep 07 '24 edited Sep 07 '24
Only in a trivially easy case, and the first argument to array.from must be arraylike or iterable.
For example
for (let x = 0; x < 100; x += 3)Of course there are many more that are simple mathematical expressions like this that will be ugly or complicated looking, not to mention things that are not simple arithmetic expressions in the afterthought or condition, but complex expressions or function calls.
You can rewrite any of them to not use let of course. The question is why??
There are other good reasons to use let for readability, like constructing dynamic strings.
2
u/jcunews1 helpful Sep 07 '24
That code will end up translated by the JS interpreter as below.
var x = 6;
x = 10;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
1
u/bryku helpful Sep 07 '24
Funny enough, I think this was actually why they allowed var to be redeclared. It was a new language that was meant to be used by programmers and non programmers, so they had to make it easy and flexible.
1
u/red-giant-star Sep 07 '24
But if you do it using let it slaps you instead and says This is not allowed
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
No you can’t. What makes you say that? Got some example code so I can see what you mean?
1
u/stubbornappl Sep 09 '24
// VAR var name = 'John Doe'; function logName() { console.log(name); // John Doe name = 'Steve Smith'; console.log(name); // Steve Smith var age = 30; } logName(); console.log(name); // Steve Smith console.log(age); // 30 // LET let name = 'John Doe'; function logName() { console.log(name); // John Doe name = 'Steve Smith'; console.log(name); // Steve Smith let age = 30; } logName(); console.log(name); // Steve Smith console.log(age); // Error // CONST const name = 'John Doe'; function logName() { 'use strict'; console.log(name); // John Doe name = 'Steve Smith'; console.log(name); // Steve Smith (with use-strict it will be an error because const can not be reassigned) const age = 30; country = 'USA'; // Error, country is not defined (with use-strict) } logName(); console.log(name); // John Doe console.log(age); // Error1
u/tapgiles Sep 09 '24
Have you actually tried running these?
In the "var" example, it breaks on
console.log(age);because no age variable has been declared with that name in that scope. Because a var declared inside a function is not accessible from outside its body. Same as any other variable.And for the "const" example, it breaks on
name = 'Steve Smith';because you can't assign a const to have a different value.And again, I'm saying these things after running them in a browser, not just guesswork or anything.
1
u/stubbornappl Sep 09 '24
you are right, bad explanation from me. What ir really mean you cant declare two times let name = ... in the same scrope, while you can with var
1
u/tapgiles Sep 09 '24
Okay. Yeah that’s never been any kind of problem for me, but that’s how it works, yes.
1
u/stubbornappl Sep 09 '24
You can declare a var on the top of the file, and then use the same name below, and the first value goes away. Depends where you use it. I still work with people that only use var ..
1
u/tapgiles Sep 10 '24
The value doesn't go away. You always access the one in the closest scope to the one you're accessing from. All of this goes for "let" and "const" as well.
You can also just not put "var" and it would access the existing declared variable if that's what you wanted to do. Or if you declare a variable with the same name but don't set its value, it would not change that first declaration's value anyway.
To be clear, I just don't declare the same variable more than once. It's just unnecessary, and has the potential to confuse later down the line. But the fact this is possible doesn't inherently cause any problems.
Some devs like the other feature that you can declare the same variable in different scopes and they will be different variables in memory. That feature also has the potential to confuse a developer, just as the non-scoped "var" multiple-declarations does. Just confuse in a slightly different way.
I just don't choose to use the "let" scoping feature, is all. That feature is the only practical difference between "var" and "let". I don't want to use that feature, so I don't use "let." It's fine for someone to code like that. 🤷
I get that if more people are working on a project you probably want everyone to be writing in the same style. But that's all it is--a style. A choice. Not based on scientific proof of the "better-than-var-ness" or anything. It's not inherently better or worse, they just work a little differently to each other.
1
u/stubbornappl Sep 10 '24
what I mean with lose the value is that if I declare "var variable = 1" and below declare "var variable = 2", it will not throw any error and "value 1" will get lost, while if you use let it will throw "SyntaxError: Identifier 'variable' has already been declared" (copy from console, ahah). Yes, there is a big problem if this happen, maybe the file it's starting to be to big or something like that, didn't try it using multiple files with IIFE.
1
u/tapgiles Sep 11 '24
I just don't have scopes within scopes nested to that degree that I lose track, I guess. Again--you're using a feature to avoid making mistakes. I just don't make those mistakes, so I don't need that feature anyway.
You understand my point, right? Demonising a feature of the language based on "it doesn't have this feature I like to use" doesn't make any sense. Because if you don't want to use that feature there is no problem in using syntax that doesn't have that feature.
I understand why you want to use such-and-such a feature. That doesn't mean anything that doesn't have that feature is "the worst" and people shouldn't use it. You can choose not to use that syntax, but it's a choice, it's not like a moral imperative or based on any objective judgement that the syntax should never be used or something.
If that wasn't what you meant, that's how it came across... and in that case I don't know what your point was 😅
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 var used in a code block creates a different variable scope than a var creates 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 let keyword 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 var works the way it does is because the designers of JavaScript at the time thought it should. The reason let and const work 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 let and const which 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.
2
u/Tiefling77 Sep 07 '24
I share your dreams…
1
1
u/guest271314 Sep 07 '24
Within the scope of any VariableEnvironment a common BindingIdentifier may appear in more than one VariableDeclaration but those declarations collectively define only one variable. A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer's AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.
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.
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.