-
Notifications
You must be signed in to change notification settings - Fork 0
46 Pollyfills
Biswajit Sundara edited this page Aug 21, 2023
·
3 revisions
Pollyfill is a piece of code that provides additional functionality that is not natively supported by a browser.
- It allows developers to use features of the latest ECMAScript (JavaScript) specifications in older browsers that do not support these features.
- Polyfills are often used to bridge the gap between the JavaScript code developers want to write (using modern language features) and the JavaScript that older browsers can understand.
- We check if
String.prototype.startsWithis already defined. If it's not, we define it using a polyfill function. - The polyfill function emulates the behavior of startsWith() by using the indexOf() method to check if the string starts with the specified substring, considering an optional starting position.
- After defining the polyfill, you can use str.startsWith() as if it were a built-in method, even in browsers that don't support it natively.
- This way, you can ensure consistent behavior for your code across different browsers, even when some of them do not support the latest JavaScript features.
// Check if String.prototype.startsWith() is not available (older browsers)
if (!String.prototype.startsWith) {
// Define the polyfill
String.prototype.startsWith = function (searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}<body>
<script>
var str = "Hello, World!";
console.log(str.startsWith1("Hello")); // true
console.log(str.startsWith1("World", 7)); // true
console.log(str.startsWith1("Goodbye")); // false
</script>
</body>- Similarly we can implement for
Array.prototype.includesalso