Let / Const Variables
let greeting;
const newUser = true;
if (newUser) {
// let variables can be reassigned...
greeting = “Nice to meet you!”;
} else {
greeting = “Welcome back!”;
}
// ...while const variables cannot
newUser = false; // Uncaught TypeError: Assignment to constant variable.
// function component declared with const (arrow function)
const Header = () => {
// local variable declared with const
const username = “Bob”;
return <header>Welcome back, {username}!</header>;
}
Code Artistry © 2020
Template Literals
const username = “Fred”;
// connecting strings with the + operator is hard to read and not intuitive
const greeting = “Hi “ + username + “, how are you?”;
// template literals (``) are a breeze and much easier to write
const username = “Anna”;
// dynamic values are inserted with the ${} syntax
const greeting = `Hi ${username}, how are you?`;
function UserCard({ id, name }) {
// if user id is an odd number...
const isOddUser = id % 2 !== 0;
// ...give user a dark background
return <div className={idOddUser ? ‘dark-bg’ : ‘’}>{name}</div>
}
<UserCard id={1} name=”Bob” /> // displays UserCard with dark background applied
Code Artistry © 2020
Arrow Functions
// normal function (function declaration)
function capitalize(word) {
return word.toUpperCase();
}
// arrow function
const capitalize = () => {
return word.toUpperCase();
}
// arrow function with all 3 shorthands
const capitalize = word => word.toUpperCase();
// arrow function used for component
const UserList = ({ users }) => {
return (
<ul>
// arrow function used with .map()
// note that arrow functions can return JSX with a set of parentheses as below
{users.map((user, index) => (
<UserCard key={index} {...user} />
))}
</ul>
);
}
Code Artistry © 2020
Powerful Array Methods
// Goal: turn array of users into array of usernames
const users = [
{ name: “Bob”, id: 1 },
{ name: “Jane”, id: 2 },
{ name: “Fred”, id: 3 }
];
const usernames = [];
// for-loop - verbose + hard to read = imperative (code for computers)
for (let i = 0; i < users.length; i++) {
usernames[i] = users[i]
}
usernames; // [“Bob”, “Jane”, “Fred”]
// .map() - concise + readable = declarative (code for humans)
const usernames = users.map(user => user.username);
usernames; // [“Bob”, “Jane”, “Fred”]
function UserList() {
const users = [
{ name: “Bob”, id: 1 },
{ name: “Jane”, id: 2 },
{ name: “Fred”, id: 3 }
];
// filter out user with id of 2, then map over the rest to display their names
return (
<ul>
{users
.filter(user => user.id !== 2)
.map(user => <li key={id}>{user.name}</li>)
}
</ul>
);
};
Code Artistry © 2020
Default Parameters
// without default parameters
function sayHi(name) {
return “Hi” + name;
}
sayHi(); // “Hi undefined”
// with default parameters
function sayHi(name = ‘Bob’) {
return “Hi” + name;
}
sayHi(); // “Hi Bob”
// with default parameters using an arrow function
const sayHi = (name = ‘Jane’) => “Hi” + name;
sayHi(): // “Hi Jane”
// if no value provided to username prop, default value of ‘guest’ is used
const Header = ({ username = “guest” }) => {
return <header>Welcome, {username}!</header>;
}
<Header /> // displays: Welcome, guest!
Code Artistry © 2020
Destructuring
const user = {
name: “Reed”,
username: “ReedBarger”,
email: “
[email protected]”,
details: {
title: “Programmer”
}
};
// object property access without destructuring
console.log(`${user.name}, ${user.email}`); // logs: Reed,
[email protected]// object destructuring for less repetition
const { name, email } = user;
console.log(`${name}, ${email}`); // logs: Reed, [email protected]
// object destructuring with nested object “details”
const { username, details: { title } } = user;
console.log(`${username}, ${title}`); // logs: ReedBarger, Programmer
function App() {
return (
<div>
<h1>All Users</h1>
<UserList users={[‘Bob’, ‘Jane’, ‘Fred’]} />
</div>
);
}
}
function UserList({ users }) {
return (
<ul>
{users.map((user, index) => (
<li key={index}>{user}</li>
))}
</ul>
);
}
Code Artistry © 2020
Spread Operator
// Merge default empty data with user data from a sign up form with spread operator
const user = {
name: “”,
email: “”,
phoneNumber: “”,
};
const newUser = {
name: “ReedBarger”,
email: “[email protected]”,
};
/*
the object that is spread in last overwrites the previous object’s values
if the properties have the same name
*/
const mergedUser = { ...user, ...newUser };
mergedUser; // { name: “ReedBarger”, email: “[email protected]”, phoneNumber: “” };
function App() {
const name = {
first: “Reed”,
last: “Barger”
};
return (
<div>
// spread in name object, as compared to:
// <UserGreeting
// first={name.first}
// last={name.last}
// />
<UserGreeting {...name} />
</div>
);
}
}
Code Artistry © 2020
Short Conditionals
let age = 26;
let greeting;
// if-else conditions are sometimes unnecessary, especially for situations like
// this where we are just giving a variable one or another value based on
// a condition
if (age > 18) {
greeting = “Hello, fellow adult”:
} else {
greeting = “Hey kiddo”;
}
// ternaries do the same thing, but greatly shorten our code
const greeting = age > 18 ? ‘Hello, fellow adult’ : ‘Hey kiddo’;
greeting; // ‘Hello, fellow adult’;
const Navbar = () => {
const isAuth = true;
return (
<div>
// if user is authenticated, show auth links, otherwise a login link
{isAuth ? <AuthLinks /> : <Login />}
// if user is authenticated, show their profile. If not, show nothing.
{isAuth && <UserProfile/>}
</div>
);
}
Code Artistry © 2020
Promises + Async/Await
// async code; ‘done’ is logged after position data, doesn’t follow code order
navigator.geolocation.getCurrentPosition(position => {
console.log(position);
}, error => {
console.error(error);
});
console.log(“done”);
// async code handled with a promise; we get the right result: position, then done logged
const promise = new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
promise
.then(position => console.log(position))
.catch(error => console.error(error))
.finally(() => console.log(‘done’));
// async code with async/await looks like synchronous code; the most readable way
// of working with promises
async function getPosition() {
// async/await works in functions only (for now)
const result = await new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
const position = await result;
console.log(position);
console.log(‘done’);
}
getPosition();
// fetching data from an API with basic promise syntax (notice use of arrow functions)
window.fetch(‘http://jsonplaceholder.typicode.com/posts’)
.then(response => response.json())
.then(data => console.log(data));
// fetching same data from API with async/await
async function getPostData() {
const response = await window.fetch(‘http://jsonplaceholder.typicode.com/posts’)
const data = await response.json();
console.log(data);
}
getPostData();
Code Artistry © 2020
ES Modules
// file: utils/getLocalTime.js
const getLocalTime = () => new Date().toLocaleTimeString();
export default getLocalTime;
// file: app.js
import getLocalTime from ‘./utils/getLocalTime.js’
const App = () => {
return (
<div>
<header>The time is {getLocalTime()}</header>
...
</div>
);
}
// file: App.js
const App = () => <div>hello world!</div>
// file: styles.css
html, body {
margin: 0;
padding: 0;
}
h1 {
color: cornflowerblue;
}
// file: index.js
import React from ‘react’;
import ‘./styles.css’
import ReactDOM from “react-dom”;
import App from “./App”;
const rootElement = document.getElementById(“root”);
ReactDOM.render(<App />, rootElement);
Code Artistry © 2020
View Example React App
- Features all 10 concepts
- Play around with the code
- Try rewriting the app yourself
Hope this cheatsheet was helpful!
Visit CodeArtistry
Code Artistry © 2020