skip to Main Content

I am not understanding something fundamental about the return statement. Please help. This should return true if the word is a palindrome. Thank you for any help just getting started here. I am guessing the return can not be used in a ternary? Or is the .string() causing a problem? Or is it a scope issue that I’m not understanding? Or i am just missing the core concept of return?

palindrome = (str) => {
  let check1 = [];
  let check2 = [];

  for (i = 0; i < str.length; i++) {
    check1.push(str[i].toLowerCase());
  }

  for (j = str.length - 1; j >= 0; j--) {
    check2.push(str[j].toLowerCase());
  }
    
//return throws error
check1.toString() === check2.toString()
   ? return true
   : console.log('not a palindrome')
};

palindrome("some word");

Should return true if the word is a palindrome.

4

Answers


  1. Here is a hint:

    return check1.toString() === check2.toString() || console.log('not a palindrome')
    
    Login or Signup to reply.
  2. Although there are many schools of thought on how to structure code like this, one is to make sure the "happy path", where everything works out according to plan, runs to the end, with other, irregular branches, terminating early.

    In other words:

    palindrome = (str) => {
      // ...
        
      if (check1.toString() !== check2.toString()) {
         console.log('not a palindrome');
         return;
      }
    
      return true;
    }
    

    That being said, the console.log does not belong here in the first place, that’s a job for the caller to perform, like:

    palindrome = (str) => {
      // ...
      
      return check1.toString() !== check2.toString();
    }
    
    if (!palindrome(str)) {
      console.log(`${str} is not a palindrome`);
    }
    

    This keeps that palindrome() function focused on one thing, which is often a highly desirable trait for a function from a design and testing perspective. It’s easy to test something returns true or false. It’s annoying to test if it produces specific, often arbitrary output.

    Additionally, though it is a matter of preference, if you’re writing a regular function that takes regular arguments and doesn’t involve this, it may me clearer to define it as:

    function palindrome(str) {
      // ...
    }
    

    Where the "arrow function" style is more often used as a convenience where an inline function is preferred, like map(x => ...) or for callbacks where this binding is ideally preserved.

    The ternary operator is often quite controversial, and that’s in large part because many programmers, when discovering it, want to use it everywhere for everything, and soon enough you end up with impenetrably obtuse code like:

    let u = x ? y ? z(a ? b : c(d) ? f(g) : h) : r(s) : t(y);
    

    Where the line is between something harmless like x ? 0 : 1 and that does depend entirely on a lot of subjective opinions but it’s almost always best to express things simply where practical.

    Login or Signup to reply.
  3. A ternary operator requires an "expression" (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator) that can be executed.

    Instead, you are placing a keyword (return). The difference is subtle but important.

    Your browser should throw an error similar to:
    Uncaught SyntaxError: expected expression, got keyword 'return'

    Edit: /u/tadman has provided some excellent alternatives.

    Login or Signup to reply.
  4. the issue is in the ternary operator, you shouldn’t use it like that

    you could try Eric Fortis approach.

    or you could try this expansion of his answer

    const palindrome = (str) => {
        let reversed = str.split('').reverse().join('');
        return reversed === str || console.log("not a palindrome");
    }
    

    the split method allows you to split a string into an array on a given character, by passing empty string it splits every character into an index of the array.

    arrays have a reverse method that…. well, that’s self-explanatory.

    but also have a join method to join each index into a string with a given character in between, by passing an empty string you get each index concatenated.

    the result is the given string reversed, which you can now compare to the original

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search