Home > Article > Web Front-end > You Might Not Know: Important and Little-Known Feature in JavaScript
JavaScript is one of the cornerstones of the web development world. Even if you've been using this language for years, you may not have discovered some advanced features. In this article, we will cover the 5 most important and little-known features of JavaScript.
Reaching a value in the nested structure of objects in JavaScript can sometimes carry the risk of error. If a deep value is undefined or null, this can cause an error. The optional chaining (?.) operator eliminates this problem.
Example:
const user = { name: 'John', address: { city: 'New York' } }; console.log(user.address?.city); // 'New York' console.log(user.address?.zipcode); // undefined, hata vermez
The nullish coalescing (??) operator in JavaScript is used to return an alternative value when a value is null or undefined. This operator is especially useful for providing a default value if a variable has no value or is not defined.
Examples:
let x = 0; let y = x ?? 42; // 0 döner, çünkü 0 null veya undefined değildir console.log(y);
function getConfig(config) { return config ?? { timeout: 1000, retries: 3 }; } let userConfig = null; let finalConfig = getConfig(userConfig); // { timeout: 1000, retries: 3 } console.log(finalConfig);
Debouncing is a technique that ensures that a function runs only once in a given period of time. This is especially useful for frequently triggered events in user interactions (e.g. typing, scrolling). Debouncing , usually used to start an action (e.g. API call) after the user has completed something.
When the user is typing in a search input field, instead of making an API call with every keystroke, debouncing ensures that the API call is made only when the user stops typing:
Prevents server overload: A large number of requests will not be sent, which makes the server work more efficiently.
Reduces delay: User gets faster response.
Improves user experience: User expects suggestions to come only when he stops typing.
Example:
<!DOCTYPE html> <html lang="tr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Debounce Örneği</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } #searchInput { padding: 10px; width: 300px; font-size: 16px; border: 1px solid #ccc; border-radius: 4px; } #result { margin-top: 20px; } </style> </head> <body> <h1>Arama Örneği</h1> <input type="text" id="searchInput"/> <div id="result"></div> <script> // Debounce fonksiyonu function debounce(func, delay) { let timeoutId; return function(...args) { clearTimeout(timeoutId); // Önceki zamanlayıcıyı temizle timeoutId = setTimeout(() => func.apply(this, args), delay); // Yeni bir zamanlayıcı ayarla }; } const search = debounce((query) => { console.log(`Searching for ${query}`); // Burada bir API çağrısı yapabilirsiniz document.getElementById('result').innerText = `Sonuçlar için arama yapılıyor: ${query}`; }, 300); // Input olayını dinleme document.getElementById('searchInput').addEventListener('input', (event) => { search(event.target.value); }); </script> </body> </html>
Proxy allows capturing and modifying operations against an object. This feature is useful for defining customized behaviors before performing operations on the object.
Example:
const target = { message: 'Hello' }; const handler = { get: function(obj, prop) { if (prop in obj) { return obj[prop]; } else { return `Property ${prop} does not exist`; } } }; const proxy = new Proxy(target, handler); console.log(proxy.message); // Hello console.log(proxy.nonExistent); // Property nonExistent does not exist
It is possible to avoid duplicate values by using both structures. Examples showing how to do it using both structures:
Preventing Duplicate Values with Set
const numbers = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9, 9]; const uniqueNumbers = [...new Set(numbers)]; console.log(uniqueNumbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Preventing Duplicate Values with WeakSet
const uniqueObjects = new WeakSet(); const objA = { name: 'Alice' }; const objB = { name: 'Bob' }; const objC = objB; // Aynı referans // Değer ekleme uniqueObjects.add(objA); uniqueObjects.add(objB); uniqueObjects.add(objC); // objB'nin referansı olduğu için bu eklenmeyecek console.log(uniqueObjects); // WeakSet { ... } (objA ve objB ile gösterir)
These features are tools that will enable you to fully utilize the power and flexibility of JavaScript. You can use these features in your projects to ensure that your codes are more performant, clean and sustainable.
The above is the detailed content of You Might Not Know: Important and Little-Known Feature in JavaScript. For more information, please follow other related articles on the PHP Chinese website!