Javascript İpuçları

Bu yazıda, karşılaşacağınız bir çok durumda size yardımcı olacak javascript ipuçlarını bulacaksınız. Düşüncelerinizi yorumda paylaşmayı unutmayın.
  • Arrow Functions:

    // Without arrow function
    function add(a, b) {
      return a + b;
    }
    
    // With arrow function
    const add = (a, b) => a + b;

  • Promise:

    function fetchData() {
      return new Promise((resolve, reject) => {
        // Perform asynchronous operation
        const data = getDataFromServer();
    
        if (data) {
          resolve(data);
        } else {
          reject(new Error("Unable to fetch data"));
        }
      });
    }
    
    fetchData()
      .then((data) => console.log(data))
      .catch((error) => console.error(error));
  • promise.allSettled()

    JavaScript'te Promise.allSettled(), verilen tüm Promise nesnelerinin tam olarak ne durumda (başarılı ya da başarısız) olduklarını döner. Bu, her bir işlemin sonucunu ayrı ayrı kontrol etmek için yararlıdır. Promise.allSettled(), tüm vaatler (Promise) tamamlandığında (ya başarılı ya da başarısız) bir dizi ile sonuçlanır.

    Aşağıda bir örnek bulabilirsin:

    Örnek: Birden fazla Promise'in durumunu takip etme

    const promise1 = new Promise((resolve, reject) => setTimeout(resolve, 1000, 'İlk işlem tamamlandı')); const promise2 = new Promise((resolve, reject) => setTimeout(reject, 2000, 'İkinci işlem hata verdi')); const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 3000, 'Üçüncü işlem tamamlandı')); Promise.allSettled([promise1, promise2, promise3]) .then((sonuclar) => { sonuclar.forEach((sonuc, index) => { if (sonuc.status === 'fulfilled') { console.log(`Promise ${index + 1} başarılı: ${sonuc.value}`); } else if (sonuc.status === 'rejected') { console.log(`Promise ${index + 1} başarısız: ${sonuc.reason}`); } }); });

    Açıklama:

    • promise1: 1 saniye sonra başarılı (resolve) olacak.
    • promise2: 2 saniye sonra başarısız (reject) olacak.
    • promise3: 3 saniye sonra başarılı (resolve) olacak.

    Promise.allSettled, tüm bu Promise'ler tamamlandığında her birinin sonucunu içeren bir dizi döndürür. Bu dizide:

    • status: "fulfilled" başarılı olan Promise'leri,
    • status: "rejected" ise başarısız olan Promise'leri temsil eder.

    Çıktı:

    Promise 1 başarılı: İlk işlem tamamlandı Promise 2 başarısız: İkinci işlem hata verdi Promise 3 başarılı: Üçüncü işlem tamamlandı

    Bu yöntem, tüm işlemlerin tamamlanmasını beklemek ve başarı/başarısızlık durumlarını yönetmek için idealdir.


    #############################################################################

  • Ternary Operator:

    // Without ternary operator
    if (a > b) {
      result = "a is greater than b";
    } else {
      result = "b is greater than a";
    }
    
    // With ternary operator
    result = a > b ? "a is greater than b" : "b is greater than a";
    


  • Object Destructuring:

    const person = {
      firstName: "John",
      lastName: "Doe",
      age: 30
    };
    
    // Without object destructuring
    const firstName = person.firstName;
    const lastName = person.lastName;
    const age = person.age;
    
    // With object destructuring
    const { firstName, lastName, age } = person;


  • Nested Destructuring

    Örnek 1: Nesne İçinde Nesne Yapısıyla Destructuring

    const user = { name: "Ali", age: 30, address: { city: "İstanbul", country: "Türkiye" } }; // İç içe nesne destructuring const { name, address: { city, country } } = user; console.log(name); // "Ali" console.log(city); // "İstanbul" console.log(country); // "Türkiye"

    Bu örnekte, address nesnesi içinde yer alan city ve country değerlerine doğrudan erişim sağladık.

    Örnek 2: Dizi İçinde N0esne Yapısıyla Destructuring

    const students = [ { name: "Ayşe", grade: 90 }, { name: "Veli", grade: 85 }, { name: "Ahmet", grade: 95 } ]; // İlk iki öğrenciye destructuring ile erişim const [ { name: firstStudentName, grade: firstGrade }, { name: secondStudentName, grade: secondGrade } ] = students; console.log(firstStudentName); // "Ayşe" console.log(firstGrade); // 90 console.log(secondStudentName); // "Veli" console.log(secondGrade); // 85

    Bu örnekte bir dizi içinde yer alan nesnelere destructuring ile ulaşarak name ve grade bilgilerini aldık.

    Örnek 3: Nesne ve Dizi İç İçe Destructuring

    const person = { name: "Mehmet", hobbies: ["Kitap okumak", "Yüzmek", "Koşmak"], education: { university: { name: "Boğaziçi Üniversitesi", year: 2015 } } }; // İç içe hem nesne hem de dizi destructuring const { name, hobbies: [firstHobby], education: { university: { name: uniName, year: graduationYear } } } = person; console.log(name); // "Mehmet" console.log(firstHobby); // "Kitap okumak" console.log(uniName); // "Boğaziçi Üniversitesi" console.log(graduationYear); // 2015

    Örnek 4: Fonksiyon Parametrelerinde Destructuring

    Bir nesnenin sadece belirli bir anahtarını almak için {name} şeklinde destructuring yapabilirsin. Bu örnekte, fonksiyonun parametreleri destructuring kullanılarak alınır:

    const person = { name: "Ahmet", age: 25, city: "Ankara" }; // Destructuring ile yalnızca 'name' değerine erişim function greet({ name }) { console.log(`Merhaba, ${name}!`); } greet(person); // Çıktı: Merhaba, Ahmet!

    Burada, person nesnesi fonksiyona geçiriliyor, ve fonksiyon parametrelerinde sadece name değerine destructuring yaparak ulaşıyoruz.

    Örnek 5: Nesne Destructuring

    Bir nesnenin bir veya birkaç özelliğini ayıklayıp, geri kalanını bir kenara bırakmak için {name} şeklinde destructuring yapılabilir:

    const student = { name: "Zeynep", age: 22, department: "Bilgisayar Mühendisliği" }; // Yalnızca 'name' değerini destructuring ile al const { name } = student; console.log(name); // Çıktı: Zeynep

    Bu örnekte, student nesnesinden sadece name değeri destructuring ile alınmış ve name değişkenine atanmıştır.

    Örnek 6: Default Değer ile Destructuring

    Eğer destructuring yaparken belirttiğin anahtar nesne içinde yoksa, default bir değer belirleyebilirsin:

    const employee = { age: 35, position: "Müdür" }; // 'name' değeri yoksa varsayılan değer 'Bilinmiyor' olarak ayarlanacak const { name = "Bilinmiyor" } = employee; console.log(name); // Çıktı: Bilinmiyor

    Bu örnekte, employee nesnesinde name özelliği olmadığı için varsayılan olarak "Bilinmiyor" değeri kullanıldı.

    Örnek 7: Alias (Yeniden Adlandırma) ile Destructuring

    Destructuring yaparken bir anahtarı yeniden adlandırabilirsin:

    const user = { name: "Ebru", age: 29 }; // 'name' anahtarını 'userName' olarak yeniden adlandırıyoruz const { name: userName } = user; console.log(userName); // Çıktı: Ebru

  • Spread Operator to Combine Arrays:

    Üç noktalı sözdizimine spread operator (yayılma operatörü) denir. JavaScript'te, ... operatörü ile nesneleri ve dizileri genişletmek veya kopyalamak için kullanılır. Ancak bu örnekte object rest/spread (nesne dinlendirme/yayılma) özelliği kullanılıyor.

    Spread Operator Kullanımı:

    1. Nesneleri Genişletmek:

      const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 }; // obj2 = { a: 1, b: 2, c: 3 }
    2. Nesneleri Birleştirmek:

      const obj1 = { a: 1 }; const obj2 = { b: 2 }; const merged = { ...obj1, ...obj2 }; // merged = { a: 1, b: 2 }
    3. Koşullu Yayma (Conditional Spreading): Belirli bir koşul sağlandığında yayma yapılabilir:

      const obj = { ...(condition && { a: 1 }) }; // Eğer condition true ise { a: 1 } nesnesi eklenir, false ise eklenmez.

    Bu teknik, özellikle Redux veya React gibi yerlerde durum güncellerken nesneleri daha okunabilir ve temiz bir şekilde yönetmeye yardımcı olur.

Gerçek Kullanım Örneği - Loopback 4:

import { Filter, repository } from '@loopback/repository'; import { Support } from '../models'; import { SupportRepository, UserRepository } from '../repositories'; import { authenticate } from '@loopback/authentication'; import { authorize } from '@loopback/authorization'; import { get, param, response } from '@loopback/rest'; @authenticate('jwt') @authorize({ allowedRoles: ['6591f2707fb9078aa0ee2ca9'] }) @get('/supports') @response(200, { description: 'Array of Support model instances', content: { 'application/json': { schema: { type: 'array', items: getModelSchemaRef(Support, { includeRelations: true }) } } }, }) async supportFind( @param.filter(Support) filter?: Filter<Support>, ): Promise<(Support | { name?: string; surname?: string; email?: string })[]> { const user_id = this.user?.id; const isAdmin = user_id === `${process.env.MAIN_DB}`; if (!filter) { filter = {}; } // Destructure created_at if it exists const { created_at, ...restWhere } = filter.where || {}; // Construct the date filter const dateFilter = { created_at: { $gte: new Date('2024-01-01T00:00:00Z'), $lt: new Date('2024-07-24T00:00:00Z'), }, }; // Combine filters filter.where = { ...restWhere, ...dateFilter, ...(!isAdmin && { user_id }), }; // Log the filter to check its structure console.log('filter:', JSON.stringify(filter, null, 2)); let supports = await this.supportRepository.find(filter); if (isAdmin) { const users = await this.userRepository.find({ fields: { user_id: true, name: true, surname: true, email: true, }, }); supports = supports.map(support => { const user = users.find(usr => JSON.stringify(usr.user_id) === JSON.stringify(support.user_id)); return { ...support, name: user?.name, surname: user?.surname, email: user?.email, }; }); } return supports; }
  • Template Literals:

    const name = "John";
    const age = 30;
    
    // Without template literals
    const message = "My name is " + name + " and I am " + age + " years old.";
    
    // With template literalz
    const message = `My name is ${name} and I am ${age} years old.`;


  • Nullish Coalescing Operator:

    const foo = null;
    const bar = foo ?? "default value";
    
    console.log(bar); // "default value"

  • Optional Chaining:
     
    ?. operatörü, JavaScript'te optional chaining (isteğe bağlı zincirleme) operatörü olarak bilinir. Bu operatör, bir nesnenin belirli bir özelliğinin veya yönteminin olup olmadığını kontrol eder ve yoksa bir hata fırlatmadan undefined döner. Özellikle, bir nesne veya alt nesne null veya undefined olduğunda programın çökmesini engeller.

    Örnek:

    let user = { name: "John", details: { age: 30 } }; // Optional chaining olmadan kontrol let userName = user && user.name; // "John" let userAge = user && user.details && user.details.age; // 30 // Optional chaining ile kontrol let userName = user?.name; // "John" let userAge = user?.details?.age; // 30 let userGender = user?.gender; // undefined (hata atmaz)

  • Uniray Plus Operator: Değişkenin tipini number tipine dönüştürür.

    Bu işlem, parseInt veya parseFloat gibi fonksiyonlar kullanmadan hızlı bir şekilde string'i sayıya çevirmek için kullanılır.

    Örneğin; aşağıdaki +positionsTaxRate
    kısmındaki + işareti, unary plus operator olarak kullanılıyor. Bu operatör, positionsTaxRate değişkenini string tipindeyse number (sayı) tipine dönüştürür. Yani, positionsTaxRate bir sayı olmalı fakat bir string olarak gelebiliyorsa, + operatörüyle bu string'in sayı olarak kullanılması sağlanıyor.

  • let positionsTaxRate = "5.5";
    let taxRate = +positionsTaxRate; // 5.5 sayısına dönüştürülür

    ############################################################################

  • matchAll

    Tabii! JavaScript'te matchAll metodunu kullanarak bir string içinde bir düzenli ifadeye (regex) uyan tüm eşleşmeleri bulabilirsin. matchAll, döngüyle ya da Array.from gibi bir yöntemle işlenebilen bir iterator döndürür.

    Aşağıda matchAll ile bir örnek bulabilirsin:

    Örnek 1: Bir string'de tüm tarihleri bulma

    const metin = "Bugünün tarihi 2024-10-01, yarının tarihi ise 2024-10-02."; const regex = /\d{4}-\d{2}-\d{2}/g; // Yıl-ay-gün formatında bir tarih arar const tarihler = metin.matchAll(regex); for (const tarih of tarihler) { console.log(tarih[0]); }

    Bu örnekte, matchAll, string içinde yyyy-mm-dd formatındaki tüm tarihleri bulur. Çıktı şu şekilde olacaktır:

    2024-10-01 2024-10-02

    Örnek 2: Gruplarla matchAll kullanımı

    Bir düzenli ifade ile gruplar oluşturup her eşleşmenin alt gruplarını alabilirsin:

    const metin = "Ali 25 yaşında, Veli 30 yaşında, Ayşe 22 yaşında."; const regex = /(\w+)\s(\d{2})\syaşında/g; const eslesmeler = metin.matchAll(regex); for (const eslesme of eslesmeler) { console.log(`İsim: ${eslesme[1]}, Yaş: ${eslesme[2]}`); }

    Bu kodda, (\w+) isimleri ve (\d{2}) yaşları yakalar. Çıktı:

    İsim: Ali, Yaş: 25 İsim: Veli, Yaş: 30 İsim: Ayşe, Yaş: 22

    matchAll, tüm eşleşmeleri bulup grup bilgileriyle döndürmek için oldukça kullanışlıdır!

  • String.prototype.at()

    const
    metin = "Merhaba Dünya!"; console.log(metin.at(0)); // "M" (ilk karakter) console.log(metin.at(7)); // "D" (8. karakter)
    console.log(metin.at(-1)); // "!" (son karakter)
    console.log(metin.at(-5)); // "n" (sondan 5. karakter)


  • Array Metodları

    • Mutator methods (diziyi değiştirenler): push(), pop(), shift(), unshift(), splice(), sort(), reverse(), fill(), copyWithin().
    • Accessor methods (değiştirmeyenler): concat(), slice(), join(), includes(), indexOf(), lastIndexOf(), find(), findIndex(), findLast(), findLastIndex(), some(), every(), filter(), map(), reduce(), reduceRight(), flat(), flatMap(), toString(), toLocaleString(), entries(), keys(), values().
    • Static methods: Array.isArray(), Array.from(), Array.of().

    • [1, 2, 3].length; // 3
    • [1, 2, 3].push(4); // [1, 2, 3, 4]
    • [1, 2, 3].pop(); // 3
    • [1, 2, 3].shift(); // 1
    • [1, 2, 3].unshift(0); // [0, 1, 2, 3]
    • [1, 2, 3].concat([4, 5]); // [1, 2, 3, 4, 5]
    • [1, 2, 3].join('-'); // "1-2-3"
    • [1, 2, 3].slice(1, 2); // [2]
    • [1, 2, 3].splice(1, 1); // [2]
    • [1, 2, 3].reverse(); // [3, 2, 1]
    • [1, 2, 3].sort(); // [1, 2, 3]
    • [1, 2, 3].includes(2); // true
    • [1, 2, 3].indexOf(2); // 1
    • [1, 2, 3].lastIndexOf(2); // 1
    • [1, 2, 3].find(x => x > 2); // 3
    • [1, 2, 3].findIndex(x => x > 2); // 2
    • [1, 2, 3].every(x => x > 0); // true
    • [1, 2, 3].some(x => x > 2); // true
    • [1, 2, 3].map(x => x * 2); // [2, 4, 6]
    • [1, 2, 3].filter(x => x > 1); // [2, 3]
    • [1, 2, 3].reduce((acc, x) => acc + x, 0); // 6
    • [1, 2, 3].reduceRight((acc, x) => acc + x, 0); // 6
    • [1, 2, 3].forEach(x => console.log(x)); // 1 2 3
    • [1, 2, 3].flat(); // [1, 2, 3]
    • [1, [2, 3]].flat(); // [1, 2, 3]
    • [1, [2, [3]]].flat(2); // [1, 2, 3]
    • [1, 2, 3].flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]
    • [1, 2, 3].fill(0); // [0, 0, 0]
    • [1, 2, 3].copyWithin(0, 1); // [2, 3, 3]
    • [1, 2, 3].at(-1); // 3
    • [1, 2, 3].toString(); // "1,2,3"
    • [1, 2, 3].toLocaleString(); // "1,2,3"
    • [1, 2, 3].entries(); // Array Iterator object
    • [1, 2, 3].keys(); // Array Iterator object (indices)
    • [1, 2, 3].values(); // Array Iterator object (values)
    • Array.isArray([1, 2, 3]); // true
    • Array.from('123'); // [1, 2, 3]
    • Array.of(1, 2, 3); // [1, 2, 3]
    • [1, 2, 3].findLast(x => x > 1); // 3
    • [1, 2, 3].findLastIndex(x => x > 1); // 2

     
  • String Metodları
    "hello".length; // 5 "hello".charAt(1); // "e" "hello".charCodeAt(1); // 101 "hello".codePointAt(1); // 101 "hello".concat(" world"); // "hello world" "hello".includes("ll"); // true "hello".endsWith("o"); // true "hello".startsWith("he"); // true "hello".indexOf("l"); // 2 "hello".lastIndexOf("l"); // 3 "hello".localeCompare("world"); // -1 (depending on locale) "hello".match(/l+/g); // ["ll"] "hello".matchAll(/l/g); // Iterator ["l", "l"] "hello".normalize(); // "hello" (default normalization form is NFC) "hello".padEnd(8, "*"); // "hello***" "hello".padStart(8, "*"); // "***hello" "hello".repeat(3); // "hellohellohello" "hello".replace("l", "x"); // "hexlo" "hello".replaceAll("l", "x"); // "hexxo" "hello".search("l"); // 2 "hello".slice(1, 3); // "el" "hello".split(""); // ["h", "e", "l", "l", "o"] "hello".substring(1, 3); // "el" "hello".toLowerCase(); // "hello" "hello".toUpperCase(); // "HELLO" " hello ".trim(); // "hello" " hello ".trimStart(); // "hello " " hello ".trimEnd(); // " hello" "hello".valueOf(); // "hello" "hello".toString(); // "hello" "hello".at(1); // "e" "hello".charCodeAt(0); // 104 "hello".split("").reverse().join(""); // "olleh" "hello".toLocaleLowerCase(); // "hello" (based on locale) "hello".toLocaleUpperCase(); // "HELLO" (based on locale) "hello".fromCodePoint(104, 101, 108, 108, 111); // "hello" (Static method)
  • Date Metodları

    Oluşturma

    new Date(); // Geçerli tarihi ve saati döndürür new Date(2024, 0, 1); // 1 Ocak 2024 new Date("2024-01-01"); // 1 Ocak 2024

    Değiştirilebilir Metotlar

    date.setFullYear(2025); // Yılı 2025 olarak ayarlar date.setMonth(11); // Ayı Aralık (0-11 arası) olarak ayarlar date.setDate(25); // Günü 25 olarak ayarlar date.setHours(10); // Saati 10 olarak ayarlar date.setMinutes(30); // Dakikayı 30 olarak ayarlar date.setSeconds(15); // Saniyeyi 15 olarak ayarlar date.setMilliseconds(100); // Milisaniyeyi 100 olarak ayarlar

    Erişilebilir Metotlar

    date.getFullYear(); // Yılı döndürür date.getMonth(); // Aylığı döndürür (0-11 arası) date.getDate(); // Günü döndürür date.getDay(); // Haftanın gününü döndürür (0: Pazar, 1: Pazartesi, ... 6: Cumartesi) date.getHours(); // Saati döndürür date.getMinutes(); // Dakikayı döndürür date.getSeconds(); // Saniyeyi döndürür date.getMilliseconds(); // Milisaniyeyi döndürür date.getTime(); // Tarihin milisaniye cinsinden Unix zaman damgasını döndürür date.valueOf(); // Tarihin milisaniye cinsinden Unix zaman damgasını döndürür date.toString(); // Tarihi string formatında döndürür date.toUTCString(); // UTC formatında tarih döndürür date.toISOString(); // ISO formatında tarih döndürür date.toLocaleString(); // Yerel formatta tarih döndürür date.toLocaleDateString(); // Yerel formatta tarih döndürür (sadece tarih) date.toLocaleTimeString(); // Yerel formatta zaman döndürür date.toDateString(); // Sadece tarihi string formatında döndürür date.toTimeString(); // Sadece zamanı string formatında döndürür

    Statik Metotlar

    Date.now(); // Geçerli tarih ve saati milisaniye cinsinden döndürür Date.parse("2024-01-01"); // Verilen tarih string'inin milisaniye cinsinden Unix zaman damgasını döndürür Date.UTC(2024, 0, 1); // UTC zamanında verilen tarihi milisaniye cinsinden döndürür

    UTC İlgili Metotlar

    date.getUTCFullYear(); // UTC yılı döndürür date.getUTCMonth(); // UTC ayı döndürür date.getUTCDate(); // UTC günü döndürür date.getUTCDay(); // UTC gününü döndürür date.getUTCHours(); // UTC saatini döndürür date.getUTCMinutes(); // UTC dakikasını döndürür date.getUTCSeconds(); // UTC saniyesini döndürür date.getUTCMilliseconds(); // UTC milisaniyesini döndürür

    Diğer Metotlar

    date.toJSON(); // JSON formatında tarih döndürür date.toGMTString(); // GMT formatında tarih döndürür date.setUTCFullYear(2025); // UTC yılı ayarlar date.setUTCMonth(11); // UTC ayı ayarlar date.setUTCDate(25); // UTC günü ayarlar date.setUTCHours(10); // UTC saati ayarlar date.setUTCMinutes(30); // UTC dakikayı ayarlar date.setUTCSeconds(15); // UTC saniyeyi ayarlar date.setUTCMilliseconds(100); // UTC milisaniyeyi ayarlar

    Önemli Notlar

    • Date nesnesinin bazı metodları yerel (local) zaman dilimi bilgilerini kullanırken, bazıları UTC (Koordinatlı Evrensel Zaman) bilgilerini kullanır.
    • Statik Metotlar Date sınıfının kendisine aittir ve doğrudan Date üzerinden çağrılır.
  • JS Hatalarının Kodu Durdurmaması İçin


            function ignoreerror() { return true

            window.onerror=ignoreerror();


  • Arada Bir Çalışan Fakat Çoğunlukla Çalışmayan Kütüphaneler İçin

        Böyle bir kütüphaneyi zamanlayıcı ile çalıştırdığımızda sonuç elde etmemiz bazı durumlarda
        mümkün. Örneğin:

         var intervalId = setInterval(function() {

                    try{

                        clearInterval(intervalId);

                        $('table').DataTable();

                    }catch(e){}

          }, 1000);


Comments