Work Hard! Stay Revelant!
Javascript Notes 1
var, let and const
var
- Scope: Global or function.
- Variables declared by
varcan be redifined or updated.
var bar = "foo1";
var bar = "foo2";
bar = "foo3";
- Problems: As in the above example, you don’t know if
barhas been declared somewhere else and it can be a total surprise! - Hoisting: top of the code and initialized to
undefined
let
- Scope: block
- Variables declared by
letcan be updated but not re-declared within its scoped.
let bar = "foo";
bar = "new foo";
This won’t work
let bar = "foo";
let bar = "new foo"; // error: Identifier 'bar' has already been declared
Re-declaration outside of scope will be allowed (WTF?!):
let bar = "foo";
if (someCondition) {
let bar = "some foo";
}
console.log(bar); // "some foo"
- Hoisting: does not initialize variables to
undefined.
Const
- Scope: block
- Can’t be re-declared or updated.
- Must be initialized at the time of declaration.
- Objects property can be updated, although the object itself cannot.
const contact1 = {
emailAddress: "dummy@example.com",
firstName: "Dummy"
}
contact1.firstName = "John"; // This is ok.
- Hoisting: same as
let. Hoisted to the top but does not initialize declarations.