ES6/ES2015 For Newbies Lesson 2: Blockscope with Const and Let & Template String

Share:
Source Code

ES5 variable scopes

In ES5, variables are scoped to the closest outer function where they’re declared:

function myFunc() {
	var foo = true;

	if (foo) {
		var car = 'tesla';
		var website = 'google.com';
	}

	console.log(car);	
	console.log(website); 
}

myFunc();

In the above snippet, the variables car and website are declared inside the if loop, but due to functional scope nature of ES5, the values can be called or modified any way you please due to them being declared within the myFunc() function. This is a bad idea, because it’s very easy to overwrite variables when your codebase gets complicated.

Blockscope level variable declaration with ES6

With ES6, you can now enjoy what many other programming languages have been doing for years: block scope level variable declaration.  Let’s take a look at how we can achieve that by using the let and const.

// Block scoped Let declaration
function myFunc() {
        // block scope level variable, only available within myFunc()
	let foo = true;

	if (foo) {
		// block scope level variable, only available within this if loop
		let car = 'tesla';
		let website = 'google.com';

		console.log(car);	// tesla
		console.log(website); // google.com
	}

	console.log(car);	// Undefined
	console.log(website); // Undefined
}

myFunc();

We declared a variable by the keyword let to indicate that this variable should only be available within the block {} it is wrapped in.  In the example above, car and website are only accessible within the if loop and are no longer defined once we attempt to console.log it from the outside!

Constants

ES6 also introduced a new keyword: const.

// Constants, it follows the same scope rule as let
const pi = 3.14;	// Declaring a constant, cannot be changed, must be initialized upon declaration
pi = 5.12;	// Error, you cannot set a constant variable after it's been first declared

const myArr = [];	//Constants are declared as a reference to a value, you can still modify it, but you cannot reassign it
myArr.push(10);	// LEGAL!
console.log(myArr);
  • Constants follow the same scope rule as let
  • When you declare a const, you must initialize it to a value
  • You cannot change a constant, however you can still modify it since it’s declared as a reference to a value, example: pushing an element to a const array

Template Strings

Does the following look familiar?

var name = 'John';
var age = 8;
var school = 'foo school';

console.log('my friend ' + name + ' is ' + age + ' years old and he goes to ' + school);

when you need to output the value of a variable alongside a string, you would use the + operator to piece them together. That is terrible for readability and prone to bugs/errors in my opinion.

a better/cleaner way to do this would be with template strings:

let username = 'pentacode';
let age = 5;
console.log(`my friend ${username} is ${age} years old.`);

see the difference? First we replaced single quote () with back tick (`), you can find the button to the left of the 1 button on your keyboard. Then when we need to reference a variable, we simply wrap it in ${variable_name} and that’s it! No more opening/closing single quotes, no more plus signs, and hello readability!

You know what else is cool? You can do line breaks without \n:

// Creating line break is easy
let className = 'foo';
let balance = 400;

const outputDIV = `<div class="${className}">
		      Balance: ${balance}
		   </div>`;

simply by putting your content in a new line and it’ll output it exactly the way you formatted it. This is very helpful if you do DOM building and manipulations.

And last but not least, you can also interpolate the value you put in between ${} not just variables!

// Express interpolation
let x = 10;
let y = 20;
function sayHi() { return 'HI!'; }
console.log(`The sum of x+y is ${x+y}`);
console.log(`${sayHi()} viewers!`);

anything you put in between ${} it will be evaluate it!

Without a doubt, Template String is my favorite feature from ES6, I can’t imagine how much of a pleasure it is to write beautiful to read code using it.

[frames playlist=’3′]

Comments Or Questions? Discuss In Our Discord

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

More from PentaCode