JavaScript
References:
What’s different about TypeScript
TypeScript is mostly used in combination with JavaScript, especially when working with React.
The main difference is the explicit existence of types in TypeScript, which are checked before being compiled into browser-compatible JavaScript.
For example:
type Point = { x: number; y: number };
const [selectedPoints, setSelectedPoints] = useModelState<Point[]>("selected_points");
const [dotSize, setDotSize] = useModelState<number>("dot_size");
Here, Point
and number
are TypeScript types. They do not exist at runtime.
Optional Chaining
Optional chaining is a safe way to access a property when the object might be null
or undefined
.
For example, if arr
is undefined, arr.length
gives an error, while arr?.length
returns undefined
.
Logical NOT Operator (!)
The !
operator in JavaScript returns the opposite boolean value of its operand. It’s commonly used to convert values to their boolean equivalent and invert them.
!true // false
!false // true
!0 // true (0 is falsy)
!5 // false (5 is truthy)
!undefined // true
!"hello" // false (non-empty strings are truthy)
Destructuring
Instead of:
const props = { name: "Sam", age: 30 };
const name = props.name;
const age = props.age;
You can use destructuring:
const { name, age } = props;
Arrow Functions in Event Handlers
Instead of defining a separate function,
function setCount(c) {
return c + 1;
}
simply define within the function as long as it is a one-liner:
<button onClick={() => setCount(c => c + 1)}>+</button>
Ternary Operator
Based on true/false, render one or the other.
{isLoggedIn ? <Dashboard /> : <Login />}
Nullish Coalescing (??)
Have a fallback if the input is null
or undefined
:
const max = user.maxPoints ?? 3;
Default Parameter
Instead of:
function greet(name) {
name = name || "stranger";
return "Hi " + name;
}
Do:
const greet = (name = "stranger") => `Hi ${name}`;
Shorthand Object Properties
Instead of:
const user = { name: name, age: age };
Do:
const user = { name, age };
Use ...
to clone or merge:
const newArr = [...oldArr, newItem];
const newObj = { ...oldObj, updated: true };