JavaScript Variables

The traditional way of defining variables in JavaScript was to use the var keyword. A variable assignment would look like this:

var name = 'Matt';

In ES6, two new ways of variable assignments were introduced. They are let and const. There is a difference between var and these two new keywords though.

var vs let and const

The difference between var and let and const is related to scope. With var variables, the scope is global if defined outside of any functions, or the scope is specific to a function if the variable is defined inside of the function.

var x = '1';

function test() {
	var y = '2';
	console.log(x); // Outputs `undefined`
	console.log(y); // Outputs `2`
}

console.log(x); // Outputs `1`
console.log(y); // Outputs `undefined`

let and const behave in the same way, expect with one additional difference. let and const are scoped to a block. Have a look at the following example:

function test() {
	let x = '1';

	if (x == '1') {
		let y = '2';
		console.log(x); // Outputs `1`
		console.log(y); // Outputs `2`
	}

	console.log(x); // Outputs `1`
	console.log(y); // Outputs `undefined`
}

Take note that variable assignments created outside a block (such as the if block above) can be used within that block, but any assignments in the block are limited to that specific block and child blocks it may define.

Difference between const and let

As the name describes, const defines constant. A value that doesn’t change. Where as let defines variables that can be changed.

const name = 'Matt';

// This will result in an error.
name = 'Nick';

let surname = 'Geri';

// This will _not_ result in an error.
surname = 'Wilson';

However, where the const definition is an object or array, the values inside the object can be changed. And arrays can be added and subtracted from. You cannot however try and assign a new object or array to a const definition.

const vehicle = {
	make: 'Toyota',
	model: 'Corolla'
};

// This works as expected.
vehicle.model = 'Tacoma';
vehicle.speed = 120;

// This does not work.
vehicle = {
	make: 'Ford',
	model: 'Raptor'
};

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *