Check if string ends with desired character in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string as the first argument and a single character as the second argument.

The function should determine whether the string specified by the first argument ends with the character specified by the second argument or not. The only condition is that we have to do this without using any ES6 or library methods.


Following is the code −

const str = 'This is a string';
const checkEnding = (str = '', char = '') => {
   // helper function to grab the last character of the string
   const getLast = (str = '') => {
      const { length } = str;
      return str[length - 1];
   return getLast(str) === char;
console.log(checkEnding(str, 'g'))
console.log(checkEnding(str, 'h'))


Following is the output on console −

Published on 10-Dec-2020 12:29:07