Hi there!
Below you'll find 5 neart JavaScript tricks that you can start using today in your projects. Both beginners and more seasoned developers might find it interesting:
1. Debouncing Function Calls
Debouncing is a technique to limit the number of times a function is executed in response to events like scrolling. This can improve performance by ensuring that the function runs a set amount of time after the event has stopped.
function debounce(func, delay) {
let timeoutId;
return function(...args) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// Usage Example
window.addEventListener('resize', debounce(() => {
console.log('Window resized!');
}, 500));
2. Creating a Simple Modal
You can create a simple modal dialog with just HTML and JavaScript. Here’s how you can do it:
<!-- Modal HTML -->
<div id="myModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background-color:rgba(0,0,0,0.5);">
<div style="background:#fff; margin: 15% auto; padding: 20px; width: 80%;">
<span id="closeModal" style="cursor:pointer; float:right;">×</span>
<p>This is a simple modal!</p>
</div>
</div>
<button id="openModal">Open Modal</button>
<script>
const modal = document.getElementById('myModal');
const openBtn = document.getElementById('openModal');
const closeBtn = document.getElementById('closeModal');
openBtn.onclick = function() {
modal.style.display = 'block';
};
closeBtn.onclick = function() {
modal.style.display = 'none';
};
window.onclick = function(event) {
if (event.target === modal) {
modal.style.display = 'none';
}
};
</script>
3. Dynamic Property Names in Objects
You can use computed property names in object literals to create objects with dynamic keys.
const key = 'name';
const value = 'John';
const obj = {
[key]: value,
age: 30
};
console.log(obj); // { name: 'John', age: 30 }
4. Detecting Performance with Performance API
You can measure the performance of different parts of your code using the Performance API, which is helpful for identifying bottlenecks.
console.time("myFunction");
function myFunction() {
for (let i = 0; i < 1e6; i++) {
// Some time-consuming operation
}
}
myFunction();
console.timeEnd("myFunction"); // Logs the time taken to execute `myFunction`
5. Prototypal Inheritance
You can utilize JavaScript’s prototypal inheritance to create a simple class-like structure.
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name); // Call parent constructor
}
// Inheriting from Animal
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function() {
console.log(`${this.name} barks.`);
};
const dog = new Dog('Rex');
dog.speak(); // "Rex barks."
Hopefully, you've learnt something new today.
Have a nice day!
Top comments (0)