JavaScript Basics

Programming the browser and beyond

Syntax & Types

  • Variables: let, const
  • Primitives: string, number, boolean, null, undefined, symbol, bigint
  • Objects, arrays, functions, arrow functions

Variables, Scope & Hoisting

  • let/const are block-scoped; var is function-scoped.
  • Hoisting: declarations move to top of scope; let/const in TDZ until initialized.
  • Prefer const by default; use let when you reassign.
for (let i=0;i<3;i++){ setTimeout(()=>console.log(i),0) } // 0 1 2
for (var j=0;j<3;j++){ setTimeout(()=>console.log(j),0) } // 3 3 3
        

Functions & This

  • Function declaration vs expression vs arrow.
  • this is dynamic in regular functions; lexical in arrow functions.
  • Bind/call/apply to set this; avoid arrow for object methods needing this.
const obj = {
  x: 42,
  regular(){ return this.x },
  arrow: ()=> this // window/global
}
        

Objects, Prototypes & Classes

  • Prototype chain for inheritance; Object.create(proto).
  • Class syntax sugar over prototypes; use extends and super.
class Animal{ speak(){ return '...' } }
class Dog extends Animal{ speak(){ return 'woof' } }
new Dog().speak() // 'woof'
        

DOM & Events

  • Select: querySelector, getElementById
  • Manipulate: textContent, classList, style, append
  • Events: addEventListener, capture/bubble, delegation
document.addEventListener('click', e=>{
  if(e.target.matches('.delete')){ e.target.closest('.item').remove() }
})
        

ES6+ Features

  • Destructuring, rest/spread
  • Template literals
  • Promises/async-await
  • Classes

Async JS (Promises)

fetch('/api').then(r=>r.json()).then(console.log).catch(console.error)
// async/await
async function load(){
  try{ const r = await fetch('/api'); const data = await r.json(); return data }
  catch(e){ console.error(e) }
}
        

Modules & Bundling

Use native ES modules with type="module". Prefer relative imports and keep modules cohesive.

// index.html
<script type="module" src="/main.js"></script>
// main.js
import { add } from './math.js';
console.log(add(2,3));