Note for the course Modern JavaScript
-
4 concepts:
-
declarations: create a new identifier
-
initialization: first assign a value to a variable
-
scope: one of [global, function, block(new)]
-
hoisting: JS will go to upper scope to find an undefined variable
-
-
var
- function scoped
- undefined
-
let
- block scoped {}, including for loop or if statement before {}
- reference error
-
const
- like let expect that it never change
const tyler = {
name: "Tyler McGinnis",
location: "Eden, Utah"
};
// use : for renaming
let { name: who, location } = styler;
// usage:
// api can use this pattern too
function register (props) {
var { onChangeEmail, email, onChangePassword, password, submit } = props;
return (
<div>
<span>Email:</span>
<input type='text' onChange={onChangeEmail} value={email} />
<span>Password:</span>
<input type='text' onChange={onChangePassword} value={password} />
<button onClick={submit}>Submit</button>
</div>
)
const csv = "1997,Ford, F350,Must Sell!!";
let [year, make, model, description] = csv.split(",");
// usage:
Promise.all([() => "profile", () => "repos"])
.then([profile, repos] => {
return {
profile,
repo
}
})
function formatMessage(name, id, avatar) {
return {
name,
id,
avatar,
timestamp: Date.now(),
save() {
// save
}
};
}
function objectify(key, value) {
return {
[key]: value
};
}
function makeGreeting(name, email, id) {
return `Hello, ${name}. We've emailed you at ${email}. Your user id is ${id}.`;
}
function makeTemplate(name, email, id) {
return `
<div>
<title>${name}</title>
<p>email</p>
</div>
`
// Arrow function will use 'this' from where it was called // TIP: "||" will let it run both of two expressions
api.fetchRepos(lang).then(repos => {
this.setState(
() =>
console.log("repos", repos) || {
repos
}
);
});
function isRequired(name) {
throw new Error(name + "is required.");
}
// isRequired is an possible way to write validates
function calculatePayment(price = isRequired("price"), salesTax = 0.12) {
// math
}
Compiling: arrow function, destructuring... Polyfills: fetch, includes
TIP: fetch is optional, axios is more comfortable
// use Promise.all
// yarn add babel-polyfill
webpack.config.entry: ["babel-polyfill", "whatwg-fetch", ...]
class Demo {
static propTypes = {};
static defaultProps = {};
state = {};
handleChange = () => {};
}
every async function you write will return a promise, and every single thing you await will ordinarily be a promise
async function handleGetUser() {
try {
var user = await getUser();
console.log(user);
} catch (error) {
console.log("Error in handleGetUser", error);
}
}