Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 726
jsnewbie Avatar asked May 09 '26 02:05

jsnewbie


2 Answers

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."

like image 80
Kosh Avatar answered May 11 '26 16:05

Kosh


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()

like image 44
KhaledMohamedP Avatar answered May 11 '26 15:05

KhaledMohamedP