CodeBlanks Logo Icon CodeBlanks

typeof operatörü

JavaScript kursu · Başlangıç · Ders 5/133

typeof ile bir değişkenin türünü nasıl öğreneceğini ve tuzaklarını görürsün.

typeof operatörü nedir?

Bir değerin türünü öğrenmek için typeof operatörünü kullanırsın. typeof sağındaki değerin türünü bir string olarak döndürür: "number", "string", "boolean" gibi.

Örneğin typeof 42 ifadesi "number" sonucunu verir; typeof "merhaba" ifadesi "string" verir; typeof true ifadesi "boolean" verir. Sonuç bir string olduğu için console.log(typeof 42) yazdığında ekranda number kelimesini görürsün.

typeof null tuzağı

typeof null beklediğin gibi "null" değil, "object" döndürür. Bu JavaScript'in ilk yıllarından kalan tarihsel bir hatadır; sonradan düzeltilemedi çünkü eski kodlar kırılırdı.

Bu yüzden bir değerin null olup olmadığını kontrol etmek için typeof kullanma. Onun yerine doğrudan deger === null karşılaştırması yap. Bu davranış bir tuzak olarak bilinir; bilmeyen programcıları şaşırtır.

Uygulama Üç değerin türünü typeof ile yazdır

Bir sayının, bir metinnin ve null'un türünü typeof ile bul ve her birini console.log ile ekrana yazdır.

Örnek çözümü göster
console.log(typeof 42);
console.log(typeof "merhaba");
console.log(typeof null);

Kendini test et

  1. typeof 42 ifadesinin sonucu nedir?

    typeof 42
    • "number"
    • "string"
    • "integer"
    • "42"
    Cevabı göster

    "number" — Doğru. 42 bir sayı olduğu için typeof "number" döner.

  2. typeof ile 42'nin türünü bul

    let sonuc = ____;
    Cevabı göster
    let sonuc = typeof 42;
  3. Değeri typeof sonucuyla eşleştir

    42
    "number"
    "merhaba"
    "string"
    true
    "boolean"
    null
    "object"
  4. typeof null ifadesinin sonucu nedir?

    typeof null
    • "null"
    • "undefined"
    • "object"
    • "boolean"
    Cevabı göster

    "object" — Doğru. typeof null "object" döner; bu tarihsel bir hatadır.

Başlangıç bölümündeki tüm dersler