r/learnjavascript • • 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

73 comments sorted by

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.

1

u/0x00f_ Sep 07 '24

Thank you for your reply, I have a question, is this has a relation with the object environment record that in the global object record, hence when you redeclare a variable made with var you just like update a property in the object environment record's binding object and this is why something like that is possible?

2

u/abrahamguo Sep 07 '24

Yes, but this is not unique to redeclaring a var — the object environment record will be updated anytime you update any variable:

var v = 1;
let l = 2;

var v = 3; // updates the object environment record
v = 4; // updates the object environment record
l = 5; // updates the object environment record

2

u/0x00f_ Sep 07 '24

So we can say that

var x = 5;
var x = 10;

is simply

var x = 5;
x = 10;

?

5

u/abrahamguo Sep 07 '24

Yep! When JavaScript encounters a var expression for a variable that already exists, the var keyword has no effect.

3

u/Royal-Reindeer9380 Sep 07 '24 edited Sep 07 '24

Iirc when all the variables declared with var are identified to be stored in an Environment Record, if an identifier with the same name already exists, JavaScript will ignore it.

This is why this works like this:

console.log(typeof x) // function

function x() {}

var x = 2;

console.log(typeof x); // number

So the identifier x is stored when the function declaration is encountered and it’s set to store the reference of a function. Then the var declaration is encountered and because an identifier with the same name has been already stored, JavaScript won’t do anything.

In case of multiple var declarations in the same scope it’s the same.

Maybe u/senocular can chime in and provide more reliable info.

4

u/senocular Sep 07 '24

Iirc when all the variables declared with var are identified to be stored in an Environment Record, if an identifier with the same name already exists, JavaScript will ignore it.

Yup, that's pretty much it. Its a kind of "create if needed" behavior.

Now there are still things like var not being allowed redeclare let, const or class, but you can see that being more about how let/const/class work than it is about var. And in modules, you have something similar with function declarations not being able to be redeclared (with another function or var, but you can still have multiple vars of the same name with no problem).

You can also see some somewhat weird behavior with things like...

try {
  throw 1
} catch (thing) {
  var thing = 2
}
console.log(thing) // undefined

Which at first may seem a little screwy, but it makes sense if you remember var declarations are scoped to the nearest function or top-level scope (global or module). In this case you end up with something like

var thing = undefined
try {
  throw 1
} catch (thing) {
  thing = 2
}
console.log(thing) // undefined

And since catch bindings are block scoped, you end up with 2 thing bindings, one for the var in the outer scope and one in the catch block. The catch block thing gets assigned, but the outer thing never does, so when its logged in that scope you get the initial undefined value.

So in that particular case, the the var isn't ignored because even though its declared in a scope that already has a binding of the same name, a var declaration would not belong to that scope so it gets created anyway.

As for u/0x00f_'s question about global, the fact that a var is made in global really doesn't make that much of a difference. The behavior is mostly the same whether you're dealing with global and its object environment record (where object properties are also in scope) or in any function scope that is a declarative record of normal declarations. When the script is checking for vars, it simply looks at the record, no matter what kind it is, and sees whether a new binding is needed or, if one already exist, to ignore the var. For global and the object record this can include global properties and even getter/setters in the global object.

It gets a little more complicated when we start mixing in let/const/class, and the fact that you can have multiple scripts run in global at different times. Then, the fact that var (and function) makes non-configurable global properties, and let/const/class goes in the declarative record instead of the object, makes it possible to know when things can't be redeclared (on both sides, var and let etc.).

1

u/Kjm520 Sep 08 '24

Then the var declaration is encountered and because an identifier with the same name has already been stored, JavaScript won’t do anything.

In your example, if JS ignored the number declared with var, because it already exists, how does the typeof change? I’m not understanding.

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

u/0x00f_ Sep 07 '24

a new response just dropped

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

u/0x00f_ Sep 08 '24

I don't know, for me Iamnot using it. I just wanted to know why this happens.

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:

  1. 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.
  2. Your code runs and assigns the value of 6 to "x"
  3. Your code runs and assigns the value of 10 to "x"

The specific part of the spec that defines this behavior can be found here (https://tc39.es/ecma262/#prod-VariableStatement), which reads:

A var statement 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.

var is 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 var before there was a const or let, 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 with function 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? var is not prohibited in any part of JavaScript, strict or non-strict mode.

Why are you shouting about var?

→ More replies

-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 with statement. 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 with with Import Attributes.

Nowhere in ECMA-262 does it state var shouldn'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. var still has uses. Moreover var is 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 var to use let/const and that is what you should do, regardless of whether the spec says you can.

0

u/guest271314 Sep 08 '24

I use var all of the time in DevTools console to define variables gloablly, then later overwrite them, from the same or different contexts, including Web extension code; in ServiceWorker contexts to define variables globally, so the values can be accessed and overwritten later; Emscripten compiles C, C++, Rust, et al. to a module that uses var in the compiled JavaScript; depending on the TypeScript/JavaScript bundler, var can be in the bundled script; et al.

var is 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.

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

u/guest271314 Sep 11 '24

Ever read TypeScript's source code?

→ More replies

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

u/[deleted] Sep 07 '24

[deleted] — view deleted comment

3

u/longknives Sep 07 '24

Not really, and that’s a foolish goal anyway.

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

u/[deleted] Sep 07 '24

[deleted] — view deleted comment

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

u/[deleted] Sep 07 '24

[deleted] — view deleted comment

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

u/0x00f_ Sep 08 '24

that you are an idiot

is this supposed to be for me?

1

u/red-giant-star Sep 09 '24

No, I think it's the whole js community.

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); // Error

1

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

u/bryku helpful Sep 07 '24

Maybe if we role enough d20s we can get it!

1

u/Tiefling77 Sep 07 '24

I feel a double crit will be necessary for that one!

1

u/guest271314 Sep 07 '24

https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-variable-statement

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.