Old
var pi = 3.14159;
New
const pi = 3.14159;
let radius = 5;
Const
Short for constant – constant variables.const
is used for values you never want reassigning.
const pi = 3.14159;
pi = 3.14 // Will throw a TypeError
You can change and add properties to an object that’s stored as a constant. But, you can’t assign a new value, even a new object to that variable. For example, you can modify an array that’s assigned as a constant. You just can’t assign a NEW value (like a new array) to that variable.
Passes successfully
const student = {
firstName: "Rhonda",
lastName: "Salamon"
}
student.lastName = "Gertz";
Throws an error
const animal = {
type: "Dog",
name: "Rover"
}
animal = {
type: "Cat",
name: "Grumpy"
}
Let
Using the var keyword in for loops can cause unexpected behavior. var usage should be avoided from now on. let
works like var
, allowing you to re-assign variables, but unlike var
it has block level scoping.
for ( let i = 0; i < 10; i++ ) {
console.log(i);
}
Const & Let
const should be your first choice when creating a variable.
While you can use any of these to create a variable, using const as your first choice will help you prevent errors like overwriting the value in a variable that shouldn’t change.
function secondsWorked(hours) {
let totalTime;
const minutesInHour = 60;
const minutesInSecond = 60;
totalTime = hours * minutesInHour * minutesInSecond;
}
console.log( secondsWorked(40) );