JavaScript ========== References: - https://www.typescriptlang.org/docs/ - ChatGPT 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: .. code-block:: typescript type Point = { x: number; y: number }; const [selectedPoints, setSelectedPoints] = useModelState("selected_points"); const [dotSize, setDotSize] = useModelState("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. .. code-block:: javascript !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: .. code-block:: javascript const props = { name: "Sam", age: 30 }; const name = props.name; const age = props.age; You can use destructuring: .. code-block:: javascript const { name, age } = props; Arrow Functions in Event Handlers --------------------------------- Instead of defining a separate function, .. code-block:: javascript function setCount(c) { return c + 1; } simply define within the function as long as it is a one-liner: .. code-block:: jsx Ternary Operator ---------------- Based on true/false, render one or the other. .. code-block:: jsx {isLoggedIn ? : } Nullish Coalescing (??) ----------------------- Have a fallback if the input is ``null`` or ``undefined``: .. code-block:: javascript const max = user.maxPoints ?? 3; Default Parameter ----------------- Instead of: .. code-block:: javascript function greet(name) { name = name || "stranger"; return "Hi " + name; } Do: .. code-block:: javascript const greet = (name = "stranger") => `Hi ${name}`; Shorthand Object Properties -------------------------- Instead of: .. code-block:: javascript const user = { name: name, age: age }; Do: .. code-block:: javascript const user = { name, age }; Use ``...`` to clone or merge: .. code-block:: javascript const newArr = [...oldArr, newItem]; const newObj = { ...oldObj, updated: true };