Front End Knowledge Dictionary

Salah satu penyeselan terbesarku, pindah dari Macbook Pro M1 Pro ke Macbook Air M3. Ternyata laptopnya tidak kuat dengan cara kerjaku.
Salah satu penyeselan terbesarku, pindah dari Macbook Pro M1 Pro ke Macbook Air M3. Ternyata laptopnya tidak kuat dengan cara kerjaku.

JavaScript Fundamental

var
let
const
function scoped
block scoped
block scoped
can be redeclared
can’t be redeclared
can’t be redeclared
can be reassigned
can be reassigned
can’t be reassigned
can be empty when init
can be empty when init
can’t be empty when init
accessing before declaration become undefined
accessing before declaration become ReferenceError
accessing before declaration become ReferenceError
added to window object if declared in global scope
Debounce
Throttling
delay the execution of event until certain amount of time passed
limit rate of event within a certain timeframe
for handling event that have pause (e.g. typing)
for handling continuous event (e.g. scrolling)
localStorage
sessionStorage
Cookie
only client can use
only client can use
client or server (Set-Cookie) can use
until deleted
until tab closed
until specified time
5MB
5MB
4kb
same-origin
same-origin
same-origin
only persistent on current tab
sent to server for every http request
WebSocket
EventSource (server-sent events)
WebSocket protocol (ws://)
HTTP protocol (http://)
Two-way (client ↔ server)
One-way (client ← server)
Text and binary
Text

Testing

  • Unit testing: function or component
  • Integration testing: module or service
  • End-to-end testing: entire flow

Worker

  • background thread that allow us to run JS in background parallel with main thread
  • 3 types:
    • web worker
      • run script in background
      • use case: heavy computation, data processing
    • service worker
      • network proxies between network and our web
      • use case: enable offline functionality, caching, push notification
    • shared worker
      • sharing between window or frame (must same domain)
      • use case: coordinating task between component in our web

this

value of this in regular function (function() {}) refer to based on how they being called:
  • top level function: the global object (window / undefined)
    • function printThis() { console.log(this) } printThis() // window object if run browser, undefined in NodeJS
  • called as a method of object: the object itself
    • const obj = { printThis: function() { console.log(this) } // Also same with this syntax printThis() { console.log(this } } obj.printThis() // Object { printThis: f }
  • using apply / call / bind: the passed object
    • const obj = { number: 1, printThis: function() { console.log(this) } } obj.printThis.bind({ number: 2 })() // Object { number: 2 }
  • in constructor: the newly created object
    • function Person() { this.name = "person" console.log(this) // Object { name: "person" } } class Animal { constructor() { this.species = "cat"; console.log(this) // Object { species: "cat" } } }
  • DOM event listener: the element object
    • document.getElementById("button").addEventListener("click", function() { console.log(this) // "button" element })

Closure

Closure: a function that still have access to it's lexical scope when he defined
Lexical scope: it's own scope & scope of it's parent function
Benefit: to hide the implementation details and maintaining state in encapsulation

Hosting

Hoisting: mechanism where variable and function declaration are moved to the top of their containing scope during compile phase
If we try console.log the value, based on their variable type
  • var: undefined
  • let & const: ReferenceError (Temporal Dead Zone)
  • function expression & arrow function: depends on their variable type
  • function declaration (function (){}): can be called

Promise

Promise.all
Promise.allSettled
accept array of Promise
accept array of Promise
resolve when all resolved, reject when any rejected
resolve when all resolved or rejected
return array of Promise value
return array of { status: 'fulfilled', value: any } or { status: 'rejected', reason: any }

Event Loop

Event loop: mechanism how JS handle async operation.
There are 4 world: call stack, Web API/NodeJS API, macrotask queue, microtask queue.
JS will prioritize executing microtask (promise, await) before continue to macrotask (Web API/NodeJS API, listener)
notion image
 

React

In Strict Mode, React will call some of your functions twice instead of once
  • React uses the result of one of the calls, and ignores the result of the other call
💡
In JavaScript, a function () {} or () => {} always creates a different function, similar to how the {} object literal always creates a new object. That means passing them as props (without useCallback), will make the child component re-render (even though child component wrapped by React.memo)
React.memo
  • for component
  • background: child component re-render when it’s parent re-render or when it’s props changed
  • use case:
    • when we want component to be re-render only when it’s props changed
useMemo
  • for value
  • dependencies comparison with Object.is
  • use case:
    • skip expensive calculation
    • prevent re-render by memoized the value that will be send as props
    • prevent useEffect to firing more often if the value is dependency of useEffect
useCallback
  • for function
  • dependencies comparison with Object.is
  • use case:
    • avoid writing extra nested function if using useMemo to wrap function
    • prevent re-render by memoized the function that will be send as props
    • prevent useEffect to firing more often if the function is dependency of useEffect
💡
React Compiler automatically memoizes values and functions, reducing the need for manual useMemo calls.
useEffect
useLayoutEffect
runs after paint
runs before paint, after DOM update
async, non-blocking
sync, blocking, delays paint until effect complete
when we don't need to interact with DOM or DOM changes are unobservable
when need to mutate DOM or perform measurements
useId
  • use case:
    • generate id for accessibility, e.g: htmlFor, aria-describedby
    • generate id for components that rendered multiple times
useRef
  • use case:
    • when we want to store value that’s when changed not resulted in rerendering e.g. form data, interval id
    • manipulating the DOM

Next.js

app router
pages router
Each file in /pages become route
Each file in /app/[page]/page.tsx become route
getStaticProps and getStaticPaths (SSG), getServerSideProps (SSR)
RSC by default, use fetch directly
no built in nested layout, use _app.js or _document.js
have layout and template
layout
template
UI to wrap pages
UI to wrap pages
persistent
remounted every time the page changed
Server Side Rendering (SSR)
  • generate the page on the server then send it to client
  • need server
Static Side Generation (SSG)
  • generate whole static routes initially
  • don’t need server
Client Side Rendering (CSR)
  • browser downloads a minimal HTML page and renders the content using JavaScript
  • don’t need server
Increment Static Regeneration (ISG)
  • regenerate only certain page instead of whole static routes
  • need server

Hydration

  • process that happened after the server-side rendered HTML is sent to client
  • process of attaching event listener and initialize state on server rendered HTML page to make the page interactive

Performance

Terbagi 2:
  • Load: lazy loading (page, component), CDN, caching, use small size package, image (lazy loading, compress, responsive)
  • Rendering: memoization, virtualization, prevent rerendering

SEO

  1. <meta> tag
  1. robots.txt
  1. sitemap.xml
  1. Structured data

CSS

CSS specificity
  1. inline
  1. id
  1. class (and pseudo class)
  1. attribute
  1. element (and pseudo element)

Layout thrashing

  • read and write DOM repeatedly
  • to prevent:
    • batch the DOM changes
    • use documentFragment

Reflow and repaint

  • repaint: changes made to element but not affect layout
    • e.g updating color, background, etc
  • reflow: changes made to element and affect layout
    • e.g. adding or removing element; updating: width, height, etc
  • to prevent:
    • use css class for style change instead of via js
    • use requestAnimationFrame to sync the animation with browser repaint cycle
    • use will-change for frequently changing elements
    • avoid layout thrashing

Not important, but might need to know

← open
falsy values:
  • boolean false
  • empty string “”
  • number 0 (0, -0, +0)
  • undefined
  • NaN
  • null
  • document.all
Object.freeze
Object.seal
Object.preventExtensions
property can’t be added
property can’t be added
property can’t be added
property can’t be modified
property can be modified
property can be modified
property can’t be deleted
property can’t be deleted
property can be deleted
check using Object.isFrozen()
check using Object.isSealed()
check using Object.isExtensible()
shallow
shallow
shallow
Object.is basically same with === except in treating 0 and NaN
notion image

Class

when creating new object with new Class(), what happened:
  1. creating new object
  1. set the prototype
  1. set this to newly created object
  1. return newly created object
mouseenter: doesn't bubbling in descendant mouseover: bubbling in descendant
to help visualize: imagine you can see through a house from top which you can always observe all from OVER, meanwhile when you ENTER you can only see what room you are currently