JavaScript İpuçları ve Trikler
10 Ocak 2025 • 6 dakika okuma

JavaScript ile daha temiz, verimli ve okunabilir kod yazmanız için pratik ipuçları ve günlük geliştirmede kullanabileceğiniz trikler.
🎯 Temel İpuçları
1. Destructuring ile Temiz Kod
javascript
// ❌ Eski yöntem
const user = {
name: 'Ahmet',
age: 25,
email: 'ahmet@example.com'
};
const name = user.name;
const age = user.age;
const email = user.email;
// ✅ Modern yöntem
const { name, age, email } = user;
// Varsayılan değerlerle
const { name, age = 18, city = 'İstanbul' } = user;2. Template Literals
javascript
// ❌ String concatenation
const message = 'Merhaba ' + name + ', yaşınız ' + age;
// ✅ Template literals
const message = `Merhaba ${name}, yaşınız ${age}`;
// Çok satırlı stringler
const html = `
<div class="card">
<h2>${title}</h2>
<p>${description}</p>
</div>
`;3. Arrow Functions
javascript
// ❌ Geleneksel function
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(num) {
return num * 2;
});
// ✅ Arrow function
const doubled = numbers.map(num => num * 2);
// Çoklu parametre
const add = (a, b) => a + b;
// Obje döndürme
const createUser = (name, age) => ({ name, age });🔧 Gelişmiş Teknikler
4. Optional Chaining
javascript
// ❌ Uzun kontroller
if (user && user.address && user.address.street) {
console.log(user.address.street);
}
// ✅ Optional chaining
console.log(user?.address?.street);
// Array ile
const firstPost = user?.posts?.[0];
// Function ile
user?.getName?.();5. Nullish Coalescing
javascript
// ❌ Falsy değerler problemi
const username = user.name || 'Misafir'; // '' için de 'Misafir' döner
// ✅ Nullish coalescing
const username = user.name ?? 'Misafir'; // Sadece null/undefined için
// Varsayılan değer atama
user.settings ??= { theme: 'light' };6. Array Methods
javascript
const users = [
{ name: 'Ali', age: 25, active: true },
{ name: 'Ayşe', age: 30, active: false },
{ name: 'Mehmet', age: 35, active: true }
];
// Filtreleme
const activeUsers = users.filter(user => user.active);
// Dönüştürme
const names = users.map(user => user.name);
// Bulma
const user = users.find(user => user.name === 'Ali');
// Toplam hesaplama
const totalAge = users.reduce((sum, user) => sum + user.age, 0);
// Koşul kontrolü
const hasActiveUser = users.some(user => user.active);
const allActive = users.every(user => user.active);🚀 Modern JavaScript
7. Async/Await
javascript
// ❌ Promise chains
fetchUser(id)
.then(user => fetchPosts(user.id))
.then(posts => {
console.log(posts);
})
.catch(error => {
console.error(error);
});
// ✅ Async/await
async function getUserPosts(id) {
try {
const user = await fetchUser(id);
const posts = await fetchPosts(user.id);
return posts;
} catch (error) {
console.error('Hata:', error);
}
}8. Promise Kombinasyonları
javascript
// Paralel çalıştırma
const [user, posts, comments] = await Promise.all([
fetchUser(id),
fetchPosts(id),
fetchComments(id)
]);
// İlk tamamlanan
const result = await Promise.race([
fetchFromAPI1(),
fetchFromAPI2()
]);
// Hata toleranslı
const results = await Promise.allSettled([
fetchData1(),
fetchData2(),
fetchData3()
]);9. Modules
javascript
// utils.js
export const formatDate = (date) => {
return new Intl.DateTimeFormat('tr-TR').format(date);
};
export const capitalize = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
export default function logger(message) {
console.log(`[${new Date().toISOString()}] ${message}`);
}
// main.js
import logger, { formatDate, capitalize } from './utils.js';
logger('Uygulama başlatıldı');💡 Performans İpuçları
10. Debouncing
javascript
function debounce(func, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// Kullanım
const searchInput = document.getElementById('search');
const debouncedSearch = debounce((query) => {
// API çağrısı
searchAPI(query);
}, 300);
searchInput.addEventListener('input', (e) => {
debouncedSearch(e.target.value);
});11. Memoization
javascript
function memoize(fn) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
// Kullanım
const expensiveCalculation = memoize((n) => {
console.log('Hesaplanıyor...');
return n * n * n;
});🛠️ Debugging İpuçları
12. Console Tricks
javascript
// Obje tablosu
console.table(users);
// Gruplandırma
console.group('User Operations');
console.log('Fetching user...');
console.log('User found:', user);
console.groupEnd();
// Zaman ölçümü
console.time('API Call');
await fetchData();
console.timeEnd('API Call');
// Koşullu log
console.assert(user.age > 0, 'Yaş pozitif olmalı');13. Error Handling
javascript
class CustomError extends Error {
constructor(message, code) {
super(message);
this.name = 'CustomError';
this.code = code;
}
}
async function safeApiCall(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new CustomError(
`API hatası: ${response.status}`,
response.status
);
}
return await response.json();
} catch (error) {
if (error instanceof CustomError) {
console.error('Özel hata:', error.message, error.code);
} else {
console.error('Beklenmeyen hata:', error);
}
throw error;
}
}📝 Sonuç
Bu ipuçları günlük JavaScript geliştirmede size zaman kazandıracak ve kodunuzu daha okunabilir hale getirecektir. Sürekli pratik yaparak bu teknikleri içselleştirin.
Önerilen Kaynaklar
Etiketler: JavaScript, Tips, Best Practices, ES6+
Kategori: Programlama