jsnewbie
jsnewbie

Reputation: 41

Javascript Palindrome function logic written correctly?

I'm new to programming so please bear with me. I'm currently working on Functions Logic. I'm trying to write a function to see if the string passed is a palindrome or not (true or false).

Here is my code,

function palindrome(word){
  if(word === word.reverse())
    return true;
 } else {
    return false;
 };

 palindrome("ohho");

When I run this on the Google Inspect Element console. I get a syntax error that says Uncaught SyntaxError: Unexpected token else regarding the } else { I have a couple of questions,

  1. Is the logic in my code correct?
  2. Also, why am I getting a Syntax error?

Thanks!

Upvotes: 3

Views: 88

Answers (2)

Kosh
Kosh

Reputation: 18423

It can be simplified as:

function palindrome(word) {
  return word === Array.from(word).reverse().join('')
}

console.log(palindrome("ohho"))
console.log(palindrome("ohno"))

More efficient way :

function palindrome(word) {
  var ln = word.length;
  for (var i = 0; i <= ln/2;) 
    if (word[i++] !== word[ln-i]) return false;
  return true
}

console.log(palindrome("ohho"))
console.log(palindrome("ohno"))

Try to handle uppercase, lowercase, spaces and punctuation yourself to check phrases like "Race car."

Upvotes: 5

KhaledMohamedP
KhaledMohamedP

Reputation: 5542

One thing to note is that reverse is not a method under the String type. It will only work for Array checkout https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

You can still hack around this by simply converting the string value to an array via the String split method!

so 'ohho'.split('') will result to the following ["o", "h", "h", "o"] you can still reverse this array. I will prefer to leave the rest of the challenge to you ;)


Edited: @jeremy pointed out in the comment where split can fail with unicode character

split("") is not appropriate for splitting a string into chunks. It fails on higher-order Unicode characters. Array.from(..) works properly

so I will recommend the use of Array.from('😀ohho😀') over split. one thing to note is that Array.from won't work with IE unless you have polyfill.

More info Array.from()

Upvotes: 1

Related Questions