๐Ÿ“—

JavaScript & TypeScript

๐Ÿง‘โ€๐Ÿณ Cook

The language of the web

JavaScript is the only language that runs natively in browsers. TypeScript adds types for fewer errors.


JavaScript vs TypeScript

AspectJavaScriptTypeScript
TypesDynamicStatic
ErrorsAt runtimeDuring development
Files.js.ts
CompilationNot neededNeeds tsc

๐Ÿ’ก Recommendation: Use TypeScript for serious projects.


Fundamental concepts

Variables

const name = "Ana"       // Doesn't change
let age = 25             // Can change
// var is obsolete, don't use it

Functions

// Arrow function (preferred)
const add = (a: number, b: number): number => a + b

// Traditional function
function multiply(a: number, b: number): number {
  return a * b
}

Arrays

const fruits = ['apple', 'pear', 'grape']

fruits.map(f => f.toUpperCase())     // Transform
fruits.filter(f => f.length > 4)     // Filter
fruits.find(f => f === 'pear')       // Find one

Objects

interface User {
  name: string
  age: number
  email?: string  // Optional
}

const user: User = {
  name: "Ana",
  age: 25
}

Async/Await

// Call API
async function getUser(id: string) {
  const res = await fetch(`/api/users/${id}`)
  const data = await res.json()
  return data
}

// Use
const user = await getUser('123')

Practice

โ†’ Todo App with React


Useful links