Variables
Using let
let allows you to declare variables that can be changed later.
js
let bookTitle = 'Persepolis'
console.log(bookTitle)console
PersepolisThe order of the lines matters.
js
console.log(bookTitle)
let bookTitle = 'Persepolis'console
ReferenceError: Cannot access 'bookTitle' before initializationRedefining variables
With let, we can redefine the variable.
js
let bookTitle = 'Persepolis'
console.log(bookTitle)
bookTitle = 'The Kite Runner'
console.log(bookTitle)console
Persepolis
The Kite RunnerUsing const
We can define a variable with const just as with let.
js
const libraryName = 'Central Library'
console.log(libraryName)console
Central LibraryHowever, because we used const (which is short for "constant"), we cannot change its value.
js
const libraryName = 'Central Library'
console.log(libraryName)
libraryName = 'Quantum Codex' // throws an errorconsole
TypeError: Assignment to constant variable.Referencing between variables
A variable which points at another variable does not update its value.
js
let user1 = 'BookishBen99'
let user2 = user1
console.log('User 1:', user1)
console.log('User 2:', user2)
user1 = 'pageturner_mia'
// notice that user2 does not change
console.log('User 1:', user1)
console.log('User 2:', user2)console
User 1: BookishBen99
User 2: BookishBen99
User 1: pageturner_mia
User 2: BookishBen99
Corndel