Discover how a single word, <code>this</code>, can make your code smarter and simpler!
Why this in functions in Javascript? - Purpose & Use Cases
Imagine you have many buttons on a webpage, and you want each button to show its own label when clicked. Without a way to refer to the button itself inside the click code, you'd have to write separate code for each button manually.
Writing separate code for each button is slow and boring. If you add more buttons, you must write even more code. It's easy to make mistakes, like showing the wrong label or forgetting to update some buttons.
The this keyword inside functions lets you refer to the object that called the function. This means one function can work for many buttons, each knowing which one was clicked, without extra code.
button1.onclick = function() { alert('Button 1'); };
button2.onclick = function() { alert('Button 2'); };function showLabel() { alert(this.label); }
button1.label = 'Button 1';
button2.label = 'Button 2';
button1.onclick = showLabel;
button2.onclick = showLabel;Using this makes your code flexible and reusable, so one function can handle many objects easily.
When you click on different items in a menu, each item can show its own details using the same function that uses this to know which item was clicked.
this helps functions know who called them.
It saves time by avoiding repeated code for similar tasks.
It makes your code easier to manage and less error-prone.