I have to admit, I was a few years behind the curve when it came to all the new functionality in ES6 aka ECMAScript 2015 aka ECMAScript 6. When I finally did start to learn it and get up to speed, I was primarily interested in the arrow functions, destructuring, array methods, etc. I didn't pay much attention to the new functionality added to the
In a PR the other day, I was checking that a string started with a specific character by doing it the old school way:
const myString = "ABCD"; console.log(myString.indexOf('A') === 0 ? 'It starts with "A"' : 'It does not start with "A"');
During the PR review, a colleague pointed out I could have accomplished the same thing with the "new"
const myString = "ABCD"; console.log(myString.startsWith('A') ? 'It starts with "A"' : 'It does not start with "A"');
🤦♂️Clearly both methods do exactly the same thing. The second is only 3 characters shorter. However, it is much more readable. If someone unfamiliar with coding read the first sample, they'd have to figure out what the heck was going on. The second example is much more obvious. What do you know? An old 🐶 can learn new tricks!
There are several other very handy String object methods in ES6. Be sure to check them out as well.
- String Object for general info
P.S. With all the new
.includes methods, you might want to be sure to compare them using the same case.
const myString = "ABCD"; console.log(myString.toLowerCase().endsWith('d') ? 'It ends with "d or D"' : 'It does not end with "d or D"');