Introduction to Core-JS
core-js is a widely adopted JavaScript library that provides a plethora of polyfills for modern JavaScript features and standard library methods. It is essential for ensuring your JavaScript applications stay compatible with older browsers, while still utilizing the latest ECMAScript features.
Array Methods
Array.prototype.includes
const includesExample = [1, 2, 3].includes(2); // true
Array.from
const arrayFromExample = Array.from('foo'); // ['f', 'o', 'o']
Object Methods
Object.assign
const target = { a: 1 };
const source = { b: 2 };
const returnedTarget = Object.assign(target, source);
// { a: 1, b: 2 }
Object.entries
const objEntriesExample = Object.entries({ a: 1, b: 2 });
// [['a', 1], ['b', 2]]
String Methods
String.prototype.startsWith
const startsWithExample = 'JavaScript'.startsWith('Java'); // true
String.prototype.endsWith
const endsWithExample = 'JavaScript'.endsWith('Script'); // true
Number Methods
Number.isInteger
const isIntegerExample = Number.isInteger(123); // true
Promise Methods
Promise.all
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then(values => {
console.log(values); // [3, 42, 'foo']
});
App Example with Core-JS
Let’s create a simple app that uses the above methods:
import 'core-js/stable';
import 'regenerator-runtime/runtime';
// Check if an array includes a value
const arrayCheck = [1, 2, 3].includes(2); // true
// Convert a string to an array
const stringToArray = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
// Merge objects
const originalObj = { a: 1 };
const newObj = Object.assign({}, originalObj, { b: 2 });
// Check string patterns
const startsWithHello = 'Hello World'.startsWith('Hello'); // true
// Use multiple promises
const promiseResult = Promise.all([
Promise.resolve('First Promise'),
Promise.resolve('Second Promise')
]).then(results => {
console.log(results); // ['First Promise', 'Second Promise']
});
console.log({ arrayCheck, stringToArray, newObj, startsWithHello });
With core-js, you can ensure browser compatibility and leverage modern JavaScript features efficiently.
Hash: a421b0bafc79bc3423c971f06c33074e7d59ca0963bd2ff8a7e37e4c0d7ae2fe