An exploration of JavaScript's variable declaration keywords
8th
January 2020, 00:13
With the creation of ECMAScript, JavaScript's days of being derided as a "loose" scripting language have come to a halt. Well, not really, but at least proponents of a variable definition stronger than the traditionally-used keyword var have had their prayers answered in the form of let and const, in 2015.
This post is maybe five years too late, but what the hell. Today, we're going to take a look at those.
You can access a before even declaring it. Although, I really can't think of a reason why you'd want to.
If you declare a variable twice using var, it will take the most recent value assigned to it.
In this case, it's 10.
Let's try this again, explicitly declaring a again, and setting the value to undefined.
So far so good.
But what if the second time, you didn't specify a value?
In this case, it's 5. JavaScript uses the most recent value assigned to a.
JavaScript assigns the default value of undefined to all variables that haven't been declared, or declared but not assigned a value. This is known as hoisting.
A variable can be declared using var inside a block...
... then redefined outside of the block.
Just for good measure, try this!
You'll notice that you can access i outside of that For loop! That's because the For loop is a block.
var can be used to declare a variable outside of a function, then accessed within that function.
However, if var is used to define a variable inside of a function, it cannot be accessed outside of it.
This is the error that will be produced.
You can use var to redeclare a outside of the function and assign a value to it.
Any variable declared using var can be redeclared. This can lead to confusing scenarios. The looseness of JavaScript can be a boon in the sense that it's very forgiving, but in large-scale scripts, this can make errors hard to detect.
If JavaScript is the only language you have ever used, you probably won't think much about this. But if you learned other languages before this, var's behavior will seem really nonstandard and inconsistent to you. It's predictable enough; you just need to understand the rules behind it.
In this next part, we'll take a look at how the let keyword is used. let was introduced in ECMAScript, tightening the functionality of JavaScript's variable declaration.
If you declare a variable more than once using let, it'll produce an error.
Unlike var, if you try to access a variable before it is declared, you'll get an error. Hoisting does not apply.
Unlike var, a variable declared in a block using let cannot be accessed outside of that block.
This is the error that will be produced. Variables declared using let are block-scoped.
Again, any variable declared using let cannot be accessed outside of the block it was declared in.
Where functions are concerned, let behaves just like var.
Now try this...
When you try to access a at the end, you get 10 instead of 0. That's because a is now declared as a variable using let, within function x(), thus the value of that a can't be accessed.
Any variable declared using let cannot be redeclared, though its value may be reassigned.
let is stricter than var and is subject to more limitations. This is a good thing in the sense that rectifying (or better yet, avoiding altogether) the resultant reference and syntax errors will in turn help the programmer avoid logic errors down the road.
Now we come to the const keyword. Its rules are the strictest, and it should be used only in cases where the variable's assigned value is not expected to be changed.
The const keyword
It functions almost exactly like the let keyword, with one major difference - its value cannot be reassigned.
If you try this using the let or var keyword, this is legitimate and will be allowed.
For const, you get an error. You can't reassign it some other value.
In fact, if you try to declare a variable using const, without an initial value...
...you get this error.
Needless to say, this wouldn't work either.
There is a way to get around this rule, though. Objects!
Say you declare an object variable using const. Let's call it obj, with properties a and b.
Now if you did this, there would be an error.
But if you do this, it works!
That's because it's the properties of obj whose values you're reassigning, not obj itself. Cool, huh?
I've been using var in JavaScript for a long time now out of sheer habit. Because I almost never use it in a way that would introduce problems, so far it hasn't given me many. But as times change, so must programming habits evolve.
Tags
See also
This post is maybe five years too late, but what the hell. Today, we're going to take a look at those.
The keyword var
This is used to declare variables. They can be declared just about anywhere.
var a;
console.log(a);
console.log(a);
undefined
var a = 5;
console.log(a);
console.log(a);
5
You can access a before even declaring it. Although, I really can't think of a reason why you'd want to.
console.log(a);
var a;
var a;
undefined
If you declare a variable twice using var, it will take the most recent value assigned to it.
var a = 5;
var a = 10;
console.log(a);
var a = 10;
console.log(a);
In this case, it's 10.
10
Let's try this again, explicitly declaring a again, and setting the value to undefined.
var a = 5;
var a = undefined;
console.log(a);
var a = undefined;
console.log(a);
So far so good.
undefined
But what if the second time, you didn't specify a value?
var a = 5;
var a;
console.log(a);
var a;
console.log(a);
In this case, it's 5. JavaScript uses the most recent value assigned to a.
5
JavaScript assigns the default value of undefined to all variables that haven't been declared, or declared but not assigned a value. This is known as hoisting.
undefined
A variable can be declared using var inside a block...
var a = 5;
if (a > 5)
{
var b = a;
}
else
{
var b = a + 1;
}
console.log(b);
if (a > 5)
{
var b = a;
}
else
{
var b = a + 1;
}
console.log(b);
6
... then redefined outside of the block.
var a = 5;
if (a > 5)
{
var b = a;
}
else
{
var b = a + 1;
}
var b = 10;
console.log(b);
if (a > 5)
{
var b = a;
}
else
{
var b = a + 1;
}
var b = 10;
console.log(b);
10
Just for good measure, try this!
for (var i = 0; i < 5; i++)
{
}
console.log(i);
{
}
console.log(i);
You'll notice that you can access i outside of that For loop! That's because the For loop is a block.
5
var can be used to declare a variable outside of a function, then accessed within that function.
var a = 10;
function x()
{
a = 0;
}
x();
console.log(a);
function x()
{
a = 0;
}
x();
console.log(a);
0
However, if var is used to define a variable inside of a function, it cannot be accessed outside of it.
function x()
{
var a = 0;
}
x();
console.log(a);
{
var a = 0;
}
x();
console.log(a);
This is the error that will be produced.
Uncaught ReferenceError: a is not defined
You can use var to redeclare a outside of the function and assign a value to it.
function x()
{
var a = 0;
}
x();
var a = 5;
console.log(a);
{
var a = 0;
}
x();
var a = 5;
console.log(a);
5
What we've learned
var is function-scoped. Thus if a variable is declared inside a function, it cannot be accessed outside of it.Any variable declared using var can be redeclared. This can lead to confusing scenarios. The looseness of JavaScript can be a boon in the sense that it's very forgiving, but in large-scale scripts, this can make errors hard to detect.
If JavaScript is the only language you have ever used, you probably won't think much about this. But if you learned other languages before this, var's behavior will seem really nonstandard and inconsistent to you. It's predictable enough; you just need to understand the rules behind it.
In this next part, we'll take a look at how the let keyword is used. let was introduced in ECMAScript, tightening the functionality of JavaScript's variable declaration.
The let keyword
Like var, let is used to declare variables. In its simplest form, it's used similarly.
let a;
console.log(a);
console.log(a);
undefined
let a = 5;
console.log(a);
console.log(a);
5
If you declare a variable more than once using let, it'll produce an error.
let a = 5;
let a = 10;
console.log(a);
let a = 10;
console.log(a);
Uncaught SyntaxError: Identifier 'a' has already been declared
Unlike var, if you try to access a variable before it is declared, you'll get an error. Hoisting does not apply.
console.log(a);
let a;
let a;
Uncaught ReferenceError: Cannot access 'a' before initialization
Unlike var, a variable declared in a block using let cannot be accessed outside of that block.
let a = 5;
if (a > 5)
{
let b = a;
}
else
{
let b = a + 1;
}
console.log(b);
if (a > 5)
{
let b = a;
}
else
{
let b = a + 1;
}
console.log(b);
This is the error that will be produced. Variables declared using let are block-scoped.
Uncaught ReferenceError: b is not defined
Again, any variable declared using let cannot be accessed outside of the block it was declared in.
for (let i = 0; i < 5; i++)
{
}
console.log(i);
{
}
console.log(i);
Uncaught ReferenceError: i is not defined
Where functions are concerned, let behaves just like var.
let a = 10;
function x()
{
a = 0;
}
x();
console.log(a);
function x()
{
a = 0;
}
x();
console.log(a);
0
function x()
{
let a = 0;
}
x();
console.log(a);
{
let a = 0;
}
x();
console.log(a);
Uncaught ReferenceError: a is not defined
Now try this...
let a = 10;
function x()
{
let a = 0;
}
x();
console.log(a);
function x()
{
let a = 0;
}
x();
console.log(a);
When you try to access a at the end, you get 10 instead of 0. That's because a is now declared as a variable using let, within function x(), thus the value of that a can't be accessed.
10
What we've learned
let is block-scoped. Thus if a variable is declared inside a block, it cannot be accessed outside of it.Any variable declared using let cannot be redeclared, though its value may be reassigned.
let is stricter than var and is subject to more limitations. This is a good thing in the sense that rectifying (or better yet, avoiding altogether) the resultant reference and syntax errors will in turn help the programmer avoid logic errors down the road.
Now we come to the const keyword. Its rules are the strictest, and it should be used only in cases where the variable's assigned value is not expected to be changed.
The const keyword
It functions almost exactly like the let keyword, with one major difference - its value cannot be reassigned.
If you try this using the let or var keyword, this is legitimate and will be allowed.
let a = 5;
console.log(a);
a = 10;
console.log(a);
console.log(a);
a = 10;
console.log(a);
5
10
10
For const, you get an error. You can't reassign it some other value.
const a = 5;
console.log(a);
a = 10;
console.log(a);
console.log(a);
a = 10;
console.log(a);
5
Uncaught TypeError: Assignment to constant variable.
Uncaught TypeError: Assignment to constant variable.
In fact, if you try to declare a variable using const, without an initial value...
const a;
...you get this error.
Uncaught SyntaxError: Missing initializer in const declaration
Needless to say, this wouldn't work either.
for (const i = 0; i < 5; i++)
{
}
{
}
Uncaught TypeError: Assignment to constant variable.
There is a way to get around this rule, though. Objects!
Say you declare an object variable using const. Let's call it obj, with properties a and b.
const obj = {a: 5, b: 10};
console.log(obj.a);
console.log(obj.b);
console.log(obj.a);
console.log(obj.b);
5
10
10
Now if you did this, there would be an error.
const obj = {a: 5, b: 10};
obj = {a: 10, b: 5};
console.log(obj.a);
console.log(obj.b);
obj = {a: 10, b: 5};
console.log(obj.a);
console.log(obj.b);
Uncaught TypeError: Assignment to constant variable.
But if you do this, it works!
const obj = {a: 5, b: 10};
obj.a = 10;
obj.b = 5;
console.log(obj.a);
console.log(obj.b);
obj.a = 10;
obj.b = 5;
console.log(obj.a);
console.log(obj.b);
That's because it's the properties of obj whose values you're reassigning, not obj itself. Cool, huh?
10
5
5
In Conclusion
let and const introduce some rigidity into JavaScript, where it had previously been way too flexible for the comfort level of many programmers. It's possible to use var the same way too, but you'd have to be very disciplined. Maybe even extraordinarily disciplined. And when there are a lot of moving parts in your project, it may not be worth the effort.I've been using var in JavaScript for a long time now out of sheer habit. Because I almost never use it in a way that would introduce problems, so far it hasn't given me many. But as times change, so must programming habits evolve.
Kind and constant regards,