Introduction to ES6
Now that you're starting to write more of your own JavaScript code, we'd like to introduce you to ES6. This is a quick look at the syntax you'll use at Bootcamp. There are some things to start using now during Foundations, but most of it is to give you an idea of what's ahead. You'll learn it more in-depth later on.
What is ES6?
Programming languages evolve as systems and applications change. JavaScript released version 6, called ES6, in 2015; it was the second major revision to JavaScript. ES6 introduced the ability to write shorter syntax, which improved the organisation and structure of code. Some of the tutorials/links in Foundations may use older syntax. The following is not an extensive list of changes ES6 introduced, just some key ones we focus on.
Declare variables with let or const
You still declare variables in the same format but don't use the var keyword. Instead, you will use let or const.
Older method: var can be reassigned and changed, and it's accessible anywhere in your code (inside a function, anywhere globally). Either of these can cause significant problems.
var trickvar treat = 'candy'{var spooky = 'scary skeletons'}// spooky is still visible here outside of the { } blockfor (var i = 0; i < 12; i++) {console.log(i)}// i is still visible here outside of the { } block
ES6: declare variables using let or const. Using let means the variable may change. Using const means the variable won't change.
Think of it like "let it change", and "constantly the same".
Key benefits:
- Using
constmeans less chance of variables being overwritten. - Both
letandconstare referred to as 'block scoped'. 'Block' means anything inside of a pair of curly brackets { }. Anyletorconstvariables declared inside a block are only accessible inside that block. This reduces the chances of accidental assignments. - The browser knows which variables may change (
let) or not (const), which helps speed up compiling.
Const
- Use when you don't want the value to be altered, i.e. read-only. It can't be redeclared, can't be changed through reassignment, and if you try, you'll get an error.
- You must assign a value. Otherwise, you'll get an error.
const halloween // error - halloween must be assigned a valueconst date = 30date = 31
Note: there is a way to modify a const variable but don't focus on that now. You'll learn it later on at Bootcamp.
Let
- Don't need to assign a value when declaring.
- Values can be reassigned.
// halloween is declared here but not assigned tolet halloween// jack_o_lantern is declared _and_ assigned herelet jack_o_lantern = 'turnip'// jack_o_lantern is _reassigned_ here and has the value 'pumpkin' nowjack_o_lantern = 'pumpkin'console.log(jack_o_lantern) // LOG: pumpkin{let spooky = 'scary skeletons'}// let is block-scoped, so spooky cannot be accessed here outside of the block
From now on, use
letorconst. If you know that the variable won't change, useconst. If the variable might change, uselet. When in doubt, useconstbecause if it isn't the right keyword, you'll get an error message, and you can then fix it. That won't happen withlet.
Arrow functions
A simpler way to write a function. There are many different ways to write these, but we just focus on using them when there is only one statement inside the body { }.
Regular functions are what you've learnt so far, i.e. function keyword, name, parameters, curly brackets containing statement(s) and at least one return keyword.
function regularFunction(x, y) {return x + y}regularFunction(8, 3) // 11
You'll continue to use regular functions but will sometimes use arrow functions instead.
Arrow functions:
- You don't need to use the
functionkeyword (and in some circumstances, thereturnkeyword or curly brackets). - A fat arrow (=>) separates the parameter(s) from the body.
Example: single expression - if the function returns a value and there is nothing else in the body, remove the { } and the return keyword.
const arrowFunction = (x, y) => x + yarrowFunction(3, 7) // 10
When a function like array.forEach(...) takes a function as an argument, it can be
convenient to write an arrow function inline.
const classicMovieMonsters = ['Dracula','Frankenstein','The Mummy','The Wolf Man',]classicMovieMonsters.forEach((monster) => {console.log(monster)})// LOG: Dracula// LOG: Frankenstein// LOG: The Mummy// LOG: The Wolf Man
Using a keyword function achieves the same outcome here, but is a little more verbose.
const dances = ['Monster Mash', 'Transylvania Twist', 'Thriller']dances.forEach(function (dance) {console.log(dance)})// LOG: Monster Mash// LOG: Transylvania Twist// LOG: Thriller
At Dev Academy we usually write named functions with the function keyword and anonymous functions as arrow expressions.
Spread operators for arrays
The spread operator looks like this: ...
Three small dots, but they can do a lot! Use the spread operator to:
- Concatenate two (or more) arrays together.
- Get the values of an array instead of using a for loop or other similar methods.
- Copy all of the values of an array, or just some values, and put them into another array.
- Pass an array of arguments into a function.
It works by spreading (i.e. expanding) the array in place and passing the elements in as if it were a comma-separated list.
const hamburger = ['bun', 'patty', 'ketchup']const cheeseburger = [...hamburger, 'cheese', 'pickle slices']console.log(cheeseburger) // LOG: ['bun', 'patty', 'ketchup', 'cheese', 'pickle slices']
Template literals
Easily create strings using backticks ( ` ` ) instead of quotes ( ' ' ) or ( " " ) and say goodbye to the concatenation operator (+).
Older method:
const sentence = 'Stringing me along'const slash = "Remember you had to use a backslash? e.g. it's alright"function welcome(monster, age) {return 'Welcome, ' + monster + '. You are ' + age + ' years old.'}console.log(welcome('The Mummy', 3311))// LOG: Welcome, The Mummy. You are 3311 years old.
ES6: can define a string using backticks (` `), and you can use both single or double quotes inside without having to insert backslashes. Find the backtick key top left of your keyboard, on the same key as the tilde (~) character.
const sentence = `Ooh look, a string!`const multiline = `You can easily do multiline strings!Also, because backticks are used instead of single/double quotes,you don't need to worry about backslashes!"Fantastic!" cried the students.`
You can easily put variables and expressions inside of strings using ${} syntax. This is called interpolation. The ${} syntax is a template that the browser replaces with the proper value at runtime.
Stretch, if you want to deep dive
We'll learn about Promises, This, Objects, Classes, Destructuring, and Modules in Bootcamp when we're learning more advanced ideas. If you want to know these more complex things now, please feel free to do further research.
function welcome(monster, age) {return `Welcome, ${monster}. You are ${age} years old.`}console.log(welcome('Dracula', 999))// LOG: Welcome, Dracula. You are 999 years old.
Recap
- Use
letorconstto declare variables. - It's useful to practise arrow functions where you have either a single-line statement (i.e. returns a value and there's nothing else in the function body { }) or inside a built-in method (map, filter, reduce, etc.). For anything else, write out functions with the
functionkeyword. - The rest is nice to know. They're great to understand now, but it's OK not to just yet!