01
BAŞLANGIÇ
JavaScript Nedir?
Tarayıcı, engine, ilk kod
▶
ECMAScriptV8 Engine
InterpretedSingle-threaded
Event Loop
JavaScript, HTML'i canlandıran, CSS'i kontrol eden ve sunucularla konuşan dildir. Tarayıcıda V8 / SpiderMonkey engine'i tarafından çalıştırılır. Node.js ile sunucu tarafında da koşar.
// 3 farklı bağlama yöntemi
// 1. Inline (kötü pratik)
<button onclick="alert('Tıklandı')">
// 2. Internal script
<script>
console.log("Hello World");
</script>
// 3. External (EN İYİ)
<script src="app.js" defer></script>
// defer → HTML parse bitmeden çalıştırma
💡 defer vs async: defer = HTML bittikten sonra çalıştır (sıralı). async = HTML'i beklemeden indir, hazır olunca çalıştır (sırasız). Genelde defer tercih et.
Hedef: JS'in "canlandıran katman" olduğunu kavra. HTML = iskelet, CSS = deri, JS = kaslar.
02
BAŞLANGIÇ
Değişkenler
var / let / const — scope farkı
▶
// var → eski, function scope, hoisting var
var isim = "Emre";
// let → block scope, yeniden atanabilir
let sayac = 0;
sayac = 1; // ✅ OK
// const → block scope, sabit referans
const PI = 3.14;
PI = 3; // ❌ TypeError!
// const object → içi değişebilir!
const user = { isim: "Ali" };
user.isim = "Veli"; // ✅ OK (referans sabit)
❌ VAR (KULLANMA)
• Function scope
• Hoisting (hata kaynağı)
• Re-declare edilebilir
• Eski ES5 mirası
• Hoisting (hata kaynağı)
• Re-declare edilebilir
• Eski ES5 mirası
✅ LET / CONST
• Block scope
• Temporal Dead Zone
• Öngörülebilir davranış
• Modern standart (ES6+)
• Temporal Dead Zone
• Öngörülebilir davranış
• Modern standart (ES6+)
Kural: Default olarak const kullan. Değer değişecekse let kullan. var yaz
03
BAŞLANGIÇ
Veri Tipleri
Primitive vs Reference — typeof
▶
// PRİMİTİF (stack'te saklanır)
typeof "merhaba" // "string"
typeof 42 // "number"
typeof 3.14 // "number" (float ayrı değil!)
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" ← JS'in ünlü bug'ı!
typeof 9n // "bigint"
typeof Symbol() // "symbol"
// REFERANS (heap'te saklanır)
typeof {} // "object"
typeof [] // "object" ← Array de object!
typeof function(){} // "function"
Fark neden önemli? Primitive'ler kopyalanır (pass by value). Reference tipler referans paylaşır — iki değişken aynı objeyi gösterir. Bu "mutation bug"larının kaynağıdır.
04
BAŞLANGIÇ
Operatörler
== vs === · nullish coalescing · optional chaining
▶
// == (loose) vs === (strict) — KRİTİK FARK
0 == "" // true ← type coercion!
0 === "" // false ← type check
null == undefined // true
null === undefined// false
// Nullish coalescing (ES2020)
const ad = kullanici.isim ?? "Misafir";
// null veya undefined ise "Misafir" — 0 veya "" geçer
// Optional chaining (ES2020)
const sehir = user?.adres?.sehir;
// TypeError yerine undefined döner
// Logical assignment
x ||= "default"; // falsy ise ata
y ??= 0; // null/undefined ise ata
05
BAŞLANGIÇ
Koşullar & Switch
if/else · ternary · switch · guard clause
▶
// Ternary — kısa if/else
const msg = yas >= 18 ? "Yetişkin" : "Çocuk";
// Guard clause pattern (daha temiz)
function isle(user) {
if (!user) return null; // erken çık
if (!user.email) return null; // erken çık
// asıl mantık burada, iç içe if yok
gonder(user.email);
}
// Switch — çoklu eşleşme
switch (gun) {
case "Pazartesi": calis(); break;
case "Cumartesi":
case "Pazar": dinlen(); break;
default: devam();
}
06
BAŞLANGIÇ
Döngüler
for · while · for...of · for...in
▶
// Classic for
for (let i = 0; i < 5; i++) { }
// for...of → iterable (array, string, Map)
for (const item of dizi) {
console.log(item); // değer
}
// for...in → object key'leri
for (const key in obj) {
console.log(key, obj[key]);
}
// while → koşul bilinmiyorsa
while (kuyruk.length > 0) {
isle(kuyruk.shift());
}
İpucu: Array döngüsü için önce forEach / map / filter dene. Daha okunabilir ve fonksiyonel.
07
ORTA SEVİYE
Fonksiyonlar — CRITICAL
declaration · expression · arrow · higher-order
▶
// 1. Function Declaration (hoisted)
function topla(a, b) { return a + b; }
// 2. Function Expression
const carp = function(a, b) { return a * b; };
// 3. Arrow Function — this bağlamaz!
const bol = (a, b) => a / b; // implicit return
const selamla = isim => ({ // obje döndür
mesaj: `Merhaba ${isim}`
});
// 4. Default Parameters
const guc = (taban, us = 2) => taban ** us;
// 5. Rest Parameters
const toplamHepsi = (...sayilar) =>
sayilar.reduce((t,n) => t+n, 0);
// 6. Higher-Order Function
const uygula = (fn, x) => fn(x);
uygula(x => x * 2, 5); // → 10
08
ORTA SEVİYE
Array & Object — EN KRİTİK
map · filter · reduce · spread · destructuring
▶
const kullanicilar = [
{ id: 1, isim: "Ali", yas: 22, aktif: true },
{ id: 2, isim: "Veli", yas: 17, aktif: false },
{ id: 3, isim: "Ayşe", yas: 28, aktif: true },
];
// filter → koşula uyanları al
const aktifler = kullanicilar
.filter(u => u.aktif && u.yas >= 18);
// map → her elemanı dönüştür
const isimler = aktifler
.map(u => u.isim.toUpperCase());
// reduce → tek değere indir
const ortalama = kullanicilar
.reduce((sum,u) => sum + u.yas, 0) / kullanicilar.length;
// find / findIndex / some / every
const ayse = kullanicilar.find(u => u.id === 3);
// Spread — kopyala / birleştir
const yeniListe = [...kullanicilar, { id: 4, isim: "Zeynep" }];
const guncellendi = kullanicilar.map(u =>
u.id === 1 ? { ...u, yas: 23 } : u
);
🔥 Altın Kural: Array metotlarını zincirle (chaining). filter → map → reduce akışını ele geçir. Tüm modern JS kodu bu 3 metodun üstüne inşa edilir.
09
ORTA SEVİYE
DOM Manipulation — WEB'İN KALBİ
select · modify · create · traverse
▶
// Seçiciler
const el = document.getElementById("baslik");
const btn = document.querySelector(".btn-primary");
const all = document.querySelectorAll("li"); // NodeList
// İçerik değiştirme
el.textContent = "Güvenli metin"; // XSS yok
el.innerHTML = "<b>HTML</b>"; // dikkat!
// Class işlemleri
el.classList.add("aktif");
el.classList.toggle("gizli");
el.classList.contains("aktif"); // boolean
// Attribute
el.setAttribute("data-id", "42");
el.getAttribute("data-id");
// Element oluştur & ekle
const li = document.createElement("li");
li.textContent = "Yeni madde";
li.classList.add("item");
document.querySelector("ul").append(li);
10
ORTA SEVİYE
Event System
addEventListener · delegation · bubbling
▶
// Temel event
btn.addEventListener("click", (e) => {
e.preventDefault(); // form submit vs engelle
console.log(e.target); // tıklanan element
});
// Event Delegation — performanslı pattern
document.querySelector("#liste")
.addEventListener("click", (e) => {
if (e.target.matches(".sil-btn")) {
e.target.closest("li").remove();
}
});
// Custom Event
const olay = new CustomEvent("veriGuncellendi", {
detail: { id: 42 }, bubbles: true
});
document.dispatchEvent(olay);
bubbling
Event child'dan root'a yükselir. stopPropagation() ile durdur.
capturing
addEventListener 3. param: true → capturing phase'de tetikle.
11
ORTA SEVİYE
ES6+ Modern JavaScript
Destructuring · Spread · Template literals · Modules
▶
// Destructuring — Array
const [birinci, ikinci, ...geri] = [1,2,3,4];
// Destructuring — Object (rename + default)
const { isim: ad = "Misafir", yas = 18 } = user;
// Template Literals
const html = `
<div class="kart">
<h2>${ad}</h2>
<p>Yaş: ${yas}</p>
</div>
`;
// Shorthand Property / Method
const x = 1, y = 2;
const nokta = { x, y }; // {x:1, y:2}
// Computed property
const alan = "isim";
const obj = { [alan]: "değer" }; // {isim:"değer"}
// Promise.allSettled / Object.entries
Object.entries(obj).forEach(([k,v]) => {});
12
İLERİ SEVİYE
Async JavaScript — GAME CHANGER
Callback hell → Promise → async/await · Event Loop
▶
// 1. Callback Hell (ESKİ — KÖTÜ)
getUser(id, user => {
getPosts(user.id, posts => {
getComments(posts[0].id, comments => {
// 3 seviye iç içe... devam eder
});
});
});
// 2. Promise chain
getUser(id)
.then(user => getPosts(user.id))
.then(posts => getComments(posts[0].id))
.catch(err => console.error(err));
// 3. async/await (EN OKUNAKLI)
async function yukle() {
try {
const user = await getUser(id);
const posts = await getPosts(user.id);
// Paralel çalıştır!
const [a, b] = await Promise.all([
fetchA(), fetchB()
]);
} catch (err) {
console.error(err);
}
}
Event Loop: JS single-threaded. Async işlemler Web API'ye gönderilir → callback queue'ya alınır → call stack boşalınca çalışır. Bu yüzden await "bloklamaz".
13
İLERİ SEVİYE
Fetch API & HTTP
REST · headers · JSON · interceptor pattern
▶
// GET request
const res = await fetch("https://api.example.com/users");
const data = await res.json();
// POST request
await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ isim: "Ali" })
});
// Yeniden kullanılabilir API yardımcısı
async function apiFetch(url, opts = {}) {
const token = localStorage.getItem("token");
const res = await fetch(url, {
...opts,
headers: { "Authorization": `Bearer ${token}`, ...opts.headers }
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
14
İLERİ SEVİYE
Error Handling
try/catch · custom errors · global handler
▶
// Custom Error sınıfı
class APIError extends Error {
constructor(msg, status) {
super(msg);
this.name = "APIError";
this.status = status;
}
}
try {
const data = await apiFetch("/users");
} catch (err) {
if (err instanceof APIError) {
// bilinen hata → yönet
} else {
// beklenmeyen hata → logla
}
} finally {
loading = false; // her durumda çalışır
}
// Global unhandled rejection
window.addEventListener("unhandledrejection", e => {
console.error("Yakalanmayan hata:", e.reason);
});
15
İLERİ SEVİYE
Web Storage & State
localStorage · sessionStorage · IndexedDB
▶
// localStorage — kalıcı, 5-10MB
localStorage.setItem("tema", "dark");
localStorage.getItem("tema"); // "dark"
localStorage.removeItem("tema");
// Obje kaydet (JSON serialize)
const kaydet = (key, val) =>
localStorage.setItem(key, JSON.stringify(val));
const oku = (key) =>
JSON.parse(localStorage.getItem(key));
// sessionStorage — sekme kapanınca sil
sessionStorage.setItem("draft", icerik);
// Cookie (domain/expiry kontrolü gerekirse)
document.cookie = "token=abc; max-age=3600; secure";
16
UZMAN
Advanced JS — İç Mekanizma
Closure · Scope · Prototype · this · Hoisting
▶
// Closure — dışarı sızmayan state
function sayac() {
let n = 0;
return {
artir: () => ++n,
deger: () => n
};
}
const s = sayac();
s.artir(); s.artir(); s.deger(); // 2
// this — bağlam her çağrıda değişir
const obj = {
isim: "Ali",
selamla() { return `Hey ${this.isim}`; },
// Arrow'da this yok — lexical bağlar
selamlaArr: () => `Hey ${this.isim}` // undefined!
};
// Prototype chain
function Hayvan(ad) { this.ad = ad; }
Hayvan.prototype.sesCikar = function() { };
const kopek = new Hayvan("Rex");
// kopek.sesCikar → prototype'tan miras
17
UZMAN
OOP — Class Sistemi
Class · inheritance · encapsulation · static
▶
class Kullanici {
#sifre; // private field (ES2022)
constructor(isim, sifre) {
this.isim = isim;
this.#sifre = sifre;
}
dogrula(girilen) {
return this.#sifre === girilen;
}
static olustur(veri) { // factory
return new Kullanici(veri.isim, veri.sifre);
}
}
class Admin extends Kullanici {
constructor(isim, sifre, yetki) {
super(isim, sifre); // parent çağır
this.yetki = yetki;
}
dogrula(girilen) { // override
return super.dogrula(girilen) && this.yetki;
}
}
18
UZMAN
Modüler JavaScript
ESM · import/export · bundler · tree shaking
▶
// utils.js — named export
export const topla = (a,b) => a+b;
export function format(n) { return n.toFixed(2); }
// api.js — default export
export default class APIClient { ... }
// main.js — import
import APIClient from "./api.js";
import { topla, format } from "./utils.js";
import * as Utils from "./utils.js";
// Dynamic import — lazy loading
const { grafik } = await import("./chart.js");
// HTML'de module script
<script type="module" src="main.js"></script>
19
UZMAN
Performance Optimization
Debounce · Throttle · Memoization · Virtual DOM felsefesi
▶
// Debounce — son çağrıdan ms sonra tetikle
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
input.addEventListener("input", debounce(ara, 300));
// Throttle — max her ms'de bir tetikle
function throttle(fn, ms) {
let son = 0;
return (...args) => {
const simdi = Date.now();
if (simdi - son >= ms) { son = simdi; fn(...args); }
};
}
// Memoization — hesaplanmış değeri cache'le
function memoize(fn) {
const cache = new Map();
return (key) => {
if (cache.has(key)) return cache.get(key);
const result = fn(key);
cache.set(key, result);
return result;
};
}
20
UZMAN
Testing
Unit · Integration · Jest · TDD
▶
// Jest — unit test
describe("topla fonksiyonu", () => {
it("iki sayıyı toplar", () => {
expect(topla(2,3)).toBe(5);
});
it("negatif sayı döner", () => {
expect(topla(-1,-1)).toBe(-2);
});
});
// Async test
it("API verisi çeker", async () => {
const data = await fetchUser(1);
expect(data).toHaveProperty("isim");
});
// Mock
jest.spyOn(global, "fetch").mockResolvedValue({
json: () => Promise.resolve({ isim: "Ali" })
});