const
and let
declaration keywords.=
assignment operator. If a variable hasn't been assigned, it's value will be undefined
.const
: The value of a constant can't be re-assigned later:// Names rarely change -> use const
const name = 'Harry Potter';
let
: The value may be re-assigned later:// Flags and indicators often change -> use let
let systemStatus = 'idle';
var
: This keyword is the classic (ES5) method of declaring a variable and should be avoided.Of the three ways you can declare a new variable, we recommend this order:
const
first;let
;
var
.const
and let
are Block ScopedBlocks include if
/else
statements:
let hungry = true;
if (hungry) {
let lunch = 'Pizza';
}
console.log(lunch) // error: `lunch` is only available inside if statement
Instead:
let hungry = true;
let lunch;
if (hungry) {
lunch = 'Pizza';
}
console.log(lunch) // Pizza!
let str = 'idle'; // Bad
let systemStatus = 'idle'; // Good
// System status: idle | pending | active
let systemStatus = 'pending';
undefined
until they are assigned a value. const
and let
are only used the first time you declare the variable.const
are still changeable, they just can't be reassigned entirely.const hobbies = ['pinball', 'coding', 'disc golf'];
hobbies[1] = 'programming'; // no error
There are more but we don't need to know about them.
true
and false
.undefined
.const price = 20;
const gst = 1;
const total = price + gst;
console.log(total); // 21
46
is actually something like 46.000001
;const firstName = 'Tony'; // single quotes
const lastName = "Grimes"; // double quotes
const fullName = `${firstName} ${lastName}`; // using backticks and template literals
console.log(fullName); // 'Tony Grimes'
const fakeNumber = '42';
const hungry = true;
if (hungry) {
console.log('Time for lunch!');
}
true
or false
with no quotes;const foodInStomach = null;
console.log(foodInStomach); // null
null
with no quotes;null
means "nothing";undefined
const colours = ['red', 'green', 'blue'];
console.log(colours[1]); // 'green'
[ ]
);index
starting at 0
;const person = {
name: 'Tony Grimes',
age: 46,
mentalAge: 12,
hungry: true,
hobbies: ['pinball', 'coding', 'disc golf']
}
key
:value
pairs surrounded by curly braces;key
/value
pairs and that's it;// Traditional ES5 syntax
const greet = function() {
console.log("Hello!");
}
greet(); // 'Hello!'
// Newer ES6 syntax
const farewell = () => {
console.log("Goodbye!");
}
farewell(); // 'Goodbye!'