5 advanced JavaScript examples that are useful but not commonly used.

Phong Yew Tong
3 min readJan 16, 2024
Photo by Florian Olivo on Unsplash

Let's go straight into five advanced JavaScript tips with code examples that might be highly useful in specific scenarios, even though they might not be commonly used in everyday programming frustration …. hahaha!

1. Using JavaScript Proxies for Validation

Tip: Proxies can manage and validate object property assignments dynamically.

const validator = {
set: function(obj, prop, value) {
if (prop === 'age') {
if (!Number.isInteger(value)) {
throw new TypeError('Age must be an integer');
}
if (value > 200) {
throw new RangeError('Age seems invalid');
}
}
obj[prop] = value;
return true;
}
};

const person = new Proxy({}, validator);
person.age = 100; // Works
// person.age = 'young'; // Throws error
// person.age = 300; // Throws error

Use Case: This is particularly useful for data validation in models or configurations where you must ensure data integrity throughout your application.

2. Custom Iterators with Generators

Tip: Generators can be used to create custom, efficient iterators.

function* idGenerator() {
let id = 0;
while (true) {
yield id++;
}
}

const gen = idGenerator();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

Use Case: This pattern is ideal for generating unique IDs, iterating over complex data structures, or implementing custom iteration logic without storing the entire dataset in memory.

3. Memoization for Performance

Tip: Memoization stores the results of expensive function calls and returns the cached result when the same inputs occur again.

const memoize = (fn) => {
const cache = {};
return function(...args) {
const key = args.toString();
if (key in cache) return cache[key];
cache[key] = fn.apply(this, args);
return cache[key];
};
};

const complexCalc = memoize((x, y) => {
// Assume expensive computation here
return x + y;
});

console.log(complexCalc(10, 20)); // Computed
console.log(complexCalc(10, 20)); // Cached result

Use Case: Memoization is useful in optimizing algorithms with overlapping subproblems, such as dynamic programming solutions or heavy computational functions.

4. Using WeakMap for Private Properties in Classes

Tip: WeakMap can be used to create truly private members in JavaScript classes.

const privateProperties = new WeakMap();

class Example {
constructor(data) {
privateProperties.set(this, data);
}

getData() {
return privateProperties.get(this);
}
}

const instance = new Example({ secret: "hidden" });
console.log(instance.getData()); // { secret: "hidden" }

Use Case: This technique is ideal for encapsulating private data in classes, especially when creating libraries or frameworks where you need to hide internal state from the end user.

5. Debouncing Function Calls

Tip: Debouncing is a technique to limit the rate at which a function gets invoked, especially useful in scenarios where some code shouldn’t run until the user has stopped a certain action.

function debounce(func, delay) {
let debounceTimer;
return function() {
const context = this;
const args = arguments;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(context, args), delay);
};
}

// Usage example: Debouncing a text input field
const inputField = document.getElementById('input-field');
inputField.addEventListener('keyup', debounce(() => {
console.log('Input value:', inputField.value);
}, 300));

Use Case: Debouncing is particularly useful in handling events that get fired more frequently than you would want to handle them. Common use cases include resizing windows, scrolling events, and most importantly, searching input fields where you want to wait for the user to stop typing before making an AJAX request.

Well, did you learn something new today?

Each of these examples showcases specific advanced capabilities of JavaScript, which are particularly useful in large-scale applications or scenarios requiring optimized performance and robust data handling. These techniques might help to manage complex tasks more efficiently, ensuring a smoother user experience and effective resource utilization.

😁 Follow me and drop me some claps 👏👏 👏 if this article helps you, it motivates 💪 me to create more! Thank you, everyone! 🙏

--

--

Phong Yew Tong

I will follow you back. Entrepreneurship, React, Flutter, Firebase, Typescript, Javascript, ChatGPT, Crypto. Visit www.aiwithwords.com