Power of window object in javascript
Shubham
Posted on August 25, 2020
Most of the time we are working on javascript framework or vanilla js and using some third party library. To debug we either use console.log
for that library utility or use debugger to see what is the value. The problem with this is you can't really test on the go. That is you can't try different input faster. You have to do it manually in your code. For example:
Consider you are using using date-fns for your project. And you want to test its one function lets say it is:
formatDistance(subDays(new Date(), 3), new Date())
//=> "3 days ago"
Now you want to track what will be shown if the number is 23
you have to do it manually in code to check all this thing.
Today I will let you know another way to explore these function call on the go. i.e by accessing window object
Things need to do:
- Assign function to window object i.e Note: For this case I am using format Distance you can set any name and any other function
window.formatDistance = formatDistance
- Now you can access this function using window object
- Now you can play with in browser console. No need to go to and from with code editor
If you want to test in now how it works. Here is the link. Open your browser console and play with it: link
Note:
- This is for debugging purpose. Do not ever deploy this to on production may lead to security threat. Apart from this remove once your debugging is done otherwise if you keep adding consistently it may cause memory overflow issue as well.
- Also use some identifier like this
window.__identifierName__
so that you will always remember that this is your creativity. So that you can remove it later easily 😛 (Thanks @TiagoDias for mentioning this)
Posted on August 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.