Const in JavaScript: when to use it and is it necessary? - javascript

I've recently come across the const keyword in JavaScript. From what I can tell, it is used to create immutable variables, and I've tested to ensure that it cannot be redefined (in Node.js):
const x = 'const';
const x = 'not-const';
// Will give an error: 'constant 'x' has already been defined'
I realise that it is not yet standardized across all browsers - but I'm only interested in the context of Node.js V8, and I've noticed that certain developers / projects seem to favor it heavily when the var keyword could be used to the same effect.
When is it appropriate to use const in place of var?
Should it be used every time a variable which is not going to be
re-assigned is declared?
Does it actually make any difference if var is used in place of
const or vice-versa?

There are two aspects to your questions: what are the technical aspects of using const instead of var and what are the human-related aspects of doing so.
The technical difference is significant. In compiled languages, a constant will be replaced at compile-time and its use will allow for other optimizations like dead code removal to further increase the runtime efficiency of the code. Recent (loosely used term) JavaScript engines actually compile JS code to get better performance, so using the const keyword would inform them that the optimizations described above are possible and should be done. This results in better performance.
The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error, var should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with const. If under different circumstances the information should change, use var to indicate that, even if the actual change doesn't appear in your code.

2017 Update
This answer still receives a lot of attention. It's worth noting that this answer was posted back at the beginning of 2014 and a lot has changed since then. ecmascript-6 support is now the norm. All modern browsers now support const so it should be pretty safe to use without any problems.
Original Answer from 2014
Despite having fairly decent browser support, I'd avoid using it for now. From MDN's article on const:
The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8). As of Safari 5.1.7 and Opera 12.00, if you define a variable with const in these browsers, you can still change its value later. It is not supported in Internet Explorer 6-10, but is included in Internet Explorer 11. The const keyword currently declares the constant in the function scope (like variables declared with var).
It then goes on to say:
const is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the let statement, constants declared with const will be block-scoped.
If you do use const you're going to have to add in a workaround to support slightly older browsers.

For why to use const, Tibos's answer's great.
But you said:
From what I can tell, it is used to create immutable variables
That is wrong. Mutating a variable is different from reassigning:
var hello = 'world' // Assigning
hello = 'bonjour!' // Reassigning
With const, you can not do that:
const hello = 'world'
hello = 'bonjour!' // Error
But you can mutate your variable:
const marks = [92, 83]
marks.push(95)
console.log(marks) // [92, 83, 95] -> the variable has been mutated.
So, any process that changes the variable's value without using the = sign is mutating the variable.
Note: += for example is ... reassigning!
var a = 5
a += 2 // Is the same as a = a + 2
So, the bottom line is: const doesn't prevent you from mutating variables; it prevents you from reassigning them.

To integrate the previous answers, there's an obvious advantage in declaring constant variables, apart from the performance reason: if you accidentally try to change or redeclare them in the code, the program will respectively not change the value or throw an error.
For example, compare:
// Will output 'SECRET'
const x = 'SECRET'
if (x = 'ANOTHER_SECRET') { // Warning! Assigning a value variable in an 'if' condition
console.log (x)
}
with:
// Will output 'ANOTHER_SECRET'
var y = 'SECRET'
if (y = 'ANOTHER_SECRET') {
console.log (y)
}
or
// Will throw TypeError: const 'x' has already been declared
const x = "SECRET"
/* Complex code */
var x = 0
with
// Will reassign y and cause trouble
var y = "SECRET"
/* Complex code */
var y = 0

const is not immutable.
From the MDN:
The const declaration creates a read-only reference to a value. It
does not mean the value it holds is immutable, just that the variable
identifier cannot be reassigned.

var: Declare a variable. Value initialization is optional.
let: Declare a local variable with block scope.
const: Declare a read-only named constant.
Example:
var a;
a = 1;
a = 2; // Reinitialize possible
var a = 3; // Re-declare
console.log(a); // 3
let b;
b = 5;
b = 6; // Reinitialise possible
// let b = 7; // Redeclare not possible
console.log(b);
// const c;
// c = 9; // Initialization and declaration at the same place
const c = 9;
// const c = 9; // Redeclare and initialization is not possible
console.log(c); // 9
// NOTE: Constants can be declared with uppercase or lowercase, but a common
// convention is to use all-uppercase letters.

You have great answers, but let's keep it simple.
const should be used when you have a defined constant (read as: it won't change during your program execution).
For example:
const pi = 3.1415926535
If you think that it is something that may be changed on later execution then use a var.
The practical difference, based on the example, is that with const you will always assume that pi will be 3.14[...], it's a fact.
If you define it as a var, it might be 3.14[...] or not.
For a more technical answer, Tibos' is academically right.

In my experience, I use const when I want to set something I may want to change later without having to hunt through the code looking for bits that have been hard coded, e.g., a file path or server name.
The error in your testing is another thing though. You are trying to make another variable called x, and this would be a more accurate test:
const x = 'const';
x = 'not-const';

Personal preference really. You could use const when, as you say, it will not be re-assigned and is constant. For example if you wanted to assign your birthday. Your birthday never changes so you could use it as a constant. But your age does change so that could be a variable.

Summary:
const creates an immutable binding, meaning a const variable identifier is not reassignable.
const a = "value1";
You cannot reassign it with
a = "value2";
However, if the const identifier holds an object or an array, the value of it can be changed as far as we are not reassigning it.
const x = { a: 1 }
x.a = 2; // Is possible and allowed
const numbers = [1, 2];
numbers.push(3); // Is possible and allowed
Please note that const is a block-scoped just like let which is not same as var (which is function-scoped).
In short, when something is not likely to change through reassignment use const, else use let or var, depending on the scope you would like to have.
It's much easier to reason about the code when it is dead obvious what can be changed through reassignment and what can't be. Changing a const to a let is dead simple. And going const by default makes you think twice before doing so. And this is in many cases a good thing.

The semantics of var and let
var and let are a statement to the machine and to other programmers:
I intend that the value of this assignment change over the course of execution. Do not rely on the eventual value of this assignment.
Implications of using var and let
var and let force other programmers to read all the intervening code from the declaration to the eventual use, and reason about the value of the assignment at that point in the program's execution.
They weaken machine reasoning for ESLint and other language services to correctly detect mistyped variable names in later assignments and scope reuse of outer scope variable names where the inner scope forgets to declare.
They also cause runtimes to run many iterations over all codepaths to detect that they are actually, in fact, constants, before they can optimise them. Although this is less of a problem than bug detection and developer comprehensibility.
When to use const
If the value of the reference does not change over the course of execution, the correct syntax to express the programmer's intent is const. For objects, changing the value of the reference means pointing to another object, as the reference is immutable, but the object is not.
"const" objects
For object references, the pointer cannot be changed to another object, but the object that is created and assigned to a const declaration is mutable. You can add or remove items from a const referenced array, and mutate property keys on a const referenced object.
To achieve immutable objects (which again, make your code easier to reason about for humans and machines), you can Object.freeze the object at declaration/assignment/creation, like this:
const Options = Object.freeze(['YES', 'NO'])
Object.freeze does have an impact on performance, but your code is probably slow for other reasons. You want to profile it.
You can also encapsulate the mutable object in a state machine and return deep copies as values (this is how Redux and React state work). See Avoiding mutable global state in Browser JS for an example of how to build this from first principles.
When var and let are a good match
let and var represent mutable state. They should, in my opinion, only be used to model actual mutable state. Things like "is the connection alive?".
These are best encapsulated in testable state machines that expose constant values that represent "the current state of the connection", which is a constant at any point in time, and what the rest of your code is actually interested in.
Programming is already hard enough with composing side-effects and transforming data. Turning every function into an untestable state machine by creating mutable state with variables just piles on the complexity.
For a more nuanced explanation, see Shun the Mutant - The case for const.

The main point is that how to decide which one identifier should be used during development.
In JavaScript here are three identifiers.
var (Can redeclared and reinitialize)
const (Can't redeclared and reinitialize, and can update array values by using push)
let (can reinitialize, but can't redeclare)
'var': At the time of coding when we talk about code standards, then we usually use the name of an identifier which is one that is easy to understand by other users and developers.
For example, if we are working thought many functions where we use some input and process this and return some result, like:
Example of variable use
function firstFunction(input1, input2)
{
var process = input1 + 2;
var result = process - input2;
return result;
}
function otherFunction(input1, input2)
{
var process = input1 + 8;
var result = process * input2;
return result;
}
In above examples both functions producing different-2 results, but using same name of variables. Here we can see 'process' & 'result' both are used as variables and they should be.
Example of constant with variable
const tax = 10;
const pi = 3.1415926535;
function firstFunction(input1, input2)
{
var process = input1 + 2;
var result = process - input2;
result = (result * tax)/100;
return result;
}
function otherFunction(input1, input2)
{
var process = input1 + 8;
var result = process * input2 * pi;
return result;
}
Before using 'let' in JavaScript we have to add ‘use strict’ on the top of the JavaScript file
Example of let with constant & variable
const tax = 10;
const pi = 3.1415926535;
let trackExecution = '';
function firstFunction(input1, input2)
{
trackExecution += 'On firstFunction';
var process = input1 + 2;
var result = process - input2;
result = (result * tax)/100;
return result;
}
function otherFunction(input1, input2)
{
trackExecution += 'On otherFunction'; # Can add current time
var process = input1 + 8;
var result = process * input2 * pi;
return result;
}
firstFunction();
otherFunction();
console.log(trackExecution);
In above example you can track which one function executed when & which one function not used during specific action.

First, three useful things about const (other than the scope improvements it shares with let):
It documents for people reading the code later that the value must not change.
It prevents you (or anyone coming after you) from changing the value unless they go back and change the declaration intentionally.
It might save the JavaScript engine some analysis in terms of optimization. E.g., you've declared that the value cannot change, so the engine doesn't have to do work to figure out whether the value changes so it can decide whether to optimize based on the value not changing.
Your questions:
When is it appropriate to use const in place of var?
You can do it any time you're declaring a variable whose value never changes. Whether you consider that appropriate is entirely down to your preference / your team's preference.
Should it be used every time a variable which is not going to be re-assigned is declared?
That's up to you / your team.
Does it actually make any difference if var is used in place ofconst` or vice-versa?
Yes:
var and const have different scope rules. (You might have wanted to compare with let rather than var.) Specifically: const and let are block-scoped and, when used at global scope, don't create properties on the global object (even though they do create globals). var has either global scope (when used at global scope) or function scope (even if used in a block), and when used at global scope, creates a property on the global object.
See my "three useful things" above, they all apply to this question.

It provides:
a constant reference, e.g., const x = [] - the array can be modified, but x can't point to another array; and
block scoping.
const and let will together replace var in ECMAScript 6/2015. See discussion at JavaScript ES6 Variable Declarations with let and const

When it comes to the decision between let and const (both block scoped), always prefer const so that the usage is clear in the code. That way, if you try to redeclare the variable, you'll get an error. If there's no other choice but redeclare it, just switch for let. Note that, as Anthony says, the const values aren't immutable (for instances, a const object can have properties mutated).
When it comes to var, since ES6 is out, I never used it in production code and can't think of a use case for it. One point that might consider one to use it is JavaScript hoisting - while let and const are not hoisted, var declaration is. Yet, beware that variables declared with var have a function scope, not a block scope («if declared outside any function, they will be globally available throughout the program; if declared within a function, they are only available within the function itself», in HackerRank - Variable Declaration Keywords). You can think of let as the block scoped version of var.

'const' is an indication to your code that the identifier will not be reassigned.
This is a good article about when to use 'const', 'let' or 'var': JavaScript ES6+: var, let, or const?

I am not an expert in the JavaScript compiling business, but it makes sense to say, that V8 makes use of the const flag.
Normally after declaring and changing a bunch of variables, the memory gets fragmented, and V8 is stopping to execute, makes a pause some time of a few seconds, to make garbage collection, or garbage collection.
If a variable is declared with const, V8 can be confident to put it in a tightly fixed-size container between other const variables, since it will never change.
It can also save the proper operations for that datatypes since the type will not change.

My opinions:
Q. When is it appropriate to use const in place of var?
A. Never!
Q: Should it be used every time a variable which is not going to be re-assigned is declared?
A: Never! Like this is going to make a dent in resource consumption...
Q. Does it actually make any difference if var is used in place of const or vice-versa?
A: Yes! Using var is the way to go! Much easier in dev tools and save from creating a new file(s) for testing. (var in not in place of const - const is trying to take var's place...)
Extra A: Same goes for let. JavaScript is a loose language - why constrict it?!?

Related

Why is var not deprecated?

Lately after ES6 released, many sources suggested that I use "const" and "let" instead of "var", and that I should stop using "var" in my JavaScript.
What I wonder is, if "var" has no advantage over "let" in all points of view, then why didn't they just fix var, or even deprecate "var" instead of letting them go along side each other?
Backwards compatibility.
You're right in saying there is no real advantage to using var over let - if you define them at the start of a function their meaning is basically identical.
You're right that there is no real reason to write new code using var (except maybe this, if relevant).
There are pages on the internet that are decades old though, and no one is going to rewrite them. There is nothing really to gain by removing var from the language. For languages like HTML and Javascript that are interpreted - backward compatability is absolutely mandatory.
That is also why they chose not to simply redefine var. Take the following example code;
// THIS IS AN EXAMPLE OF BAD CODE. DO NOT COPY AND PASTE THIS.
if (logic) {
var output = "true"
} else {
var output = "false"
}
console.log(output)
If var was changed to behave like let then the console.log would cause a reference error because of the scope difference.
I believe sometimes you need to redeclare a variable to write less code.
One example is this function that generates a unique id:
function makeUniqueId(takenIds) {
do {
var id = Number.parseInt(Math.random() * 10);
} while (takenIds.includes(id))
}
Which may be invoked like that
makeUniqueId([1,2,3,4,5,6,7])
Here I declare id variable simply inside do block and it get's "hoisted" to the function scope. That would cause an error if I used let, because while block wouldn't see the variable from the do block. Of course I could declate let before do..while, but that would create the same function scoped variable with extra line of code.
Another example is when you copypaste code to devtools console and every time variables get redeclared.
One more example. What if you want to keep your variable declarations close to their usages but still treat them as function globals? If you use let in this fashion, you'll get rather confusing expirience in dev tools (all those Block, Block scopes).
But var 'keeps' them together in one 'Local' list:
Everything has their own advantages and disadvantages using var const and let is dependent on their use cases.
var
Variable declarations are processed before the execution of the code.
The scope of a JavaScript variable declared with var is its current execution context.
The scope of a JavaScript variable declared outside the function is global.
let
The let statement allows you to create a variable with the scope limited to the block on which it is used.
const
const statement values can be assigned once and they cannot be reassigned. The scope of const statement works similar to let statements.
I hope you understand.

In TypeScript, when do you use "let" and when do you use "const"?

In TypeScript, when do you use "let" and when do you use "const"?
const stands for constant, and it means the variable cannot be reassigned at a later time.
let is similar to var except that it is block scoped, which means it can be declared inside of a for loop and will be local to the body of that for loop (and therefor does not exist outside of it)
The latter is different from a var variable which can be declared anywhere but is always local to the function scope.
In general it is good practice to try and define your variables as const as much as possible.
As I meanwhile do almost exclusivey functional programming I find the destinction between const and let pretty useless.
I never ever reassign values to names. Never - regardless of the language.
Having said that I find the usage problematic due to 2 reasons.
const is longer than let (no seriously!)
const sort of communicates back: Hey! I am constant but that is not true (well it is, but ...) I had multiple times collegues that were totally surprised
that this is possible
const x = { foo: "bar" }
x["foo"] = "Not bar!"
Sure the name and its reference is const but the object referenced is not. Granted in Typescript you can at least create
type ROO = Readonly<SomeType>
const x: ROO = someReferenceValue
x.someProp = "A wanna be a bar!" //compile error
So for Typescript const finally could mean const

const vs var for function assignments in JavaScript [duplicate]

Are there any limits to what types of values can be set using const in JavaScript, and in particular, functions? Is this valid? Granted it does work, but is it considered bad practice for any reason?
const doSomething = () => {
...
}
Should all functions be defined this way in ES6? It does not seem like this has caught on, if so.
There's no problem with what you've done, but you must remember the difference between function declarations and function expressions.
A function declaration, that is:
function doSomething () {}
Is hoisted entirely to the top of the scope (and like let and const they are block scoped as well).
This means that the following will work:
doSomething() // works!
function doSomething() {}
A function expression, that is:
[const | let | var] = function () {} (or () =>
Is the creation of an anonymous function (function () {}) and the creation of a variable, and then the assignment of that anonymous function to that variable.
So the usual rules around variable hoisting within a scope -- block-scoped variables (let and const) do not hoist as undefined to the top of their block scope.
This means:
if (true) {
doSomething() // will fail
const doSomething = function () {}
}
Will fail since doSomething is not defined. (It will throw a ReferenceError)
If you switch to using var you get your hoisting of the variable, but it will be initialized to undefined so that block of code above will still not work. (This will throw a TypeError since doSomething is not a function at the time you call it)
As far as standard practices go, you should always use the proper tool for the job.
Axel Rauschmayer has a great post on scope and hoisting including es6 semantics: Variables and Scoping in ES6
Although using const to define functions seems like a hack, it comes with some great advantages that make it superior (in my opinion)
It makes the function immutable, so you don't have to worry about that function being changed by some other piece of code.
You can use fat arrow syntax, which is shorter & cleaner.
Using arrow functions takes care of this binding for you.
example with function
// define a function
function add(x, y) { return x + y; }
// use it
console.log(add(1, 2)); // 3
// oops, someone mutated your function
add = function (x, y) { return x - y; };
// now this is not what you expected
console.log(add(1, 2)); // -1
same example with const
// define a function (wow! that is 8 chars shorter)
const add = (x, y) => x + y;
// use it
console.log(add(1, 2)); // 3
// someone tries to mutate the function
add = (x, y) => x - y; // Uncaught TypeError: Assignment to constant variable.
// the intruder fails and your function remains unchanged
It has been three years since this question was asked, but I am just now coming across it. Since this answer is so far down the stack, please allow me to repeat it:
Q: I am interested if there are any limits to what types of values can be
set using const in JavaScript—in particular functions. Is this valid?
Granted it does work, but is it considered bad practice for any
reason?
I was motivated to do some research after observing one prolific JavaScript coder who always uses const statement for functions, even when there is no apparent reason/benefit.
In answer to "is it considered bad practice for any reason?" let me say, IMO, yes it is, or at least, there are advantages to using function statement.
It seems to me that this is largely a matter of preference and style. There are some good arguments presented above, but none so clear as is done in this article:
Constant confusion: why I still use JavaScript function statements by medium.freecodecamp.org/Bill Sourour, JavaScript guru, consultant, and teacher.
I urge everyone to read that article, even if you have already made a decision.
Here's are the main points:
Function statements have two clear advantages over [const] function
expressions:
Advantage #1: Clarity of intent When scanning through
thousands of lines of code a day, it’s useful to be able to figure out
the programmer’s intent as quickly and easily as possible.
Advantage #2: Order of declaration == order of execution
Ideally, I want to declare my code more or less in the order that I
expect it will get executed.
This is the showstopper for me: any value declared using the const
keyword is inaccessible until execution reaches it.
What I’ve just described above forces us to write code that looks
upside down. We have to start with the lowest level function and work
our way up.
My brain doesn’t work that way. I want the context before the details.
Most code is written by humans. So it makes sense that most people’s
order of understanding roughly follows most code’s order of execution.
There are some very important benefits to the use of const and some would say it should be used wherever possible because of how deliberate and indicative it is.
It is, as far as I can tell, the most indicative and predictable declaration of variables in JavaScript, and one of the most useful, BECAUSE of how constrained it is. Why? Because it eliminates some possibilities available to var and let declarations.
What can you infer when you read a const? You know all of the following just by reading the const declaration statement, AND without scanning for other references to that variable:
the value is bound to that variable (although its underlying object is not deeply immutable)
it can’t be accessed outside of its immediately containing block
the binding is never accessed before declaration, because of Temporal Dead Zone (TDZ) rules.
The following quote is from an article arguing the benefits of let and const. It also more directly answers your question about the keyword's constraints/limits:
Constraints such as those offered by let and const are a powerful way of making code easier to understand. Try to accrue as many of these constraints as possible in the code you write. The more declarative constraints that limit what a piece of code could mean, the easier and faster it is for humans to read, parse, and understand a piece of code in the future.
Granted, there’s more rules to a const declaration than to a var declaration: block-scoped, TDZ, assign at declaration, no reassignment. Whereas var statements only signal function scoping. Rule-counting, however, doesn’t offer a lot of insight. It is better to weigh these rules in terms of complexity: does the rule add or subtract complexity? In the case of const, block scoping means a narrower scope than function scoping, TDZ means that we don’t need to scan the scope backwards from the declaration in order to spot usage before declaration, and assignment rules mean that the binding will always preserve the same reference.
The more constrained statements are, the simpler a piece of code becomes. As we add constraints to what a statement might mean, code becomes less unpredictable. This is one of the biggest reasons why statically typed programs are generally easier to read than dynamically typed ones. Static typing places a big constraint on the program writer, but it also places a big constraint on how the program can be interpreted, making its code easier to understand.
With these arguments in mind, it is recommended that you use const where possible, as it’s the statement that gives us the least possibilities to think about.
Source: https://ponyfoo.com/articles/var-let-const
There are special cases where arrow functions just won't do the trick:
If we're changing a method of an external API, and need the object's reference.
If we need to use special keywords that are exclusive to the function expression: arguments, yield, bind etc.
For more information:
Arrow function expression limitations
Example:
I assigned this function as an event handler in the Highcharts API.
It's fired by the library, so the this keyword should match a specific object.
export const handleCrosshairHover = function (proceed, e) {
const axis = this; // axis object
proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // method arguments
};
With an arrow function, this would match the declaration scope, and we won't have access to the API obj:
export const handleCrosshairHover = (proceed, e) => {
const axis = this; // this = undefined
proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // compilation error
};

Why single var is good in javascript?

Can anyone tell me why use one var declaration for multiple variables and declare each variable on a newline consider is a good programming behavior?
// bad
var items = getItems();
var goSportsTeam = true;
var dragonball = 'z';
// good
var items = getItems(),
goSportsTeam = true,
dragonball = 'z';
It is not considered 'good' or 'bad'. It's a matter of preference.
The guy who built the code quality tool JSLint, Douglas Crockford likes it.
One 'advantage' it might have is that it avoids the possibility of variable hoisting. In JavaScript all var declarations move to the top of their scope automatically.
Here is why Crockford thinks the second option is better:
In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be declined with the vars option.
It's a preference, I wouldn't say good or bad. Yes JSLint complains about it, I don't really like how it complains about for loop variables being inline as well. The reason that it was put in JSLint was to prevent possible hoisting confusions.
Also in some cases declaring all of your variables at the top will lead to a slightly smaller file. Consider the following:
var a = 10;
a++;
var b = 20;
After Google Closure being run over it
var a=10;a++;var b=20;
As opposed to this if we pull b's declaration to the top.
var a=10,b;a++;b=20;
The main benefit (aside from style preference, I guess) is that it will prevent you from writing code that suffers from unintended variable hoisting consequences.
Take this example:
var foo = function(){alert('foo');}
function bar(){
foo();
var foo = function(){alert('foobar')};
foo();
}
bar();
By reading this code, the intent of bar appears to be as follows:
Call the outer foo function to alert the string 'foo'.
Create a local variable, foo.
Call the local foo function to alert the string 'foobar'.
In reality, what happens is this:
The local variable foo is hoisted to the top of the bar function.
foo now actually refers to the local variable instead of the outer variable of the same name. But since the local hasn't been assigned yet, its value is undefined. Hence, when you try to invoke foo, you'll get a TypeError.
Nothing. Because you threw an error. That's it. Your code broke.
The arguments for Crockfords preference have been well made and are valid. I am just beginning to return to the first format now however, as I believe that for experienced developers who understand variable hoisting and are not likely to fall foul to it, there are 2 advantages that I can think of:
When new variables are added to the list of definitions, diffing is made easier. This means you are likely to experience fewer merge conflicts (simple though they may be to resolve) and less cognitive load when analysing diffs. For similar reasons I have also been converted to dangling commas, which I would never have expected xD
As #ldsenow identified, it can make searching for variable definitions more simple. You will always be able to search for var <name> and get the result you want and nothing else.

will javascript delete my var despite global reference

window.global_array = new Array();
window.example = function()
{
var x = new Object();
x['test_property'] = 3;
global_array.push(x);
}
Javascript gurus, please answer three questions:
will javascript delete x at the end of scope when example() returns, or preserve it inside global_array.
can I safely assume javascript works like 'everything is a reference' in python?
are all VMs created equal or will GC rules vary by implementation.
Yes. x will be deleted, because its scope is limited to the function body (you used the var keyword, which ensures this. Variables declared without var will be global, even when within a function body). However, the value x had will continue to be present in global_array.
Not entirely. Objects (arrays, too!) are passed as references, primitive values (like numbers) will be copied.
GC will vary by implementation, but this should be none of your concern. JavaScript implementations will behave the same, unless there is a bug.
Since x is referencing an object, the assignment (through push()) is increasing the reference count. When x going out of scope at the end of the function, this would not decrease the reference count to 0, so the object will still be there - its only reference now from within global_array.

Categories

Resources