Simple Palindrome test comparing array VS comparing string

I am doing some JS algorithms test, for example I want to check whether a word is palindrome.
And let’s say that we ignored the fact that there might be non-letters/upper or lowercase in the passed in variable.

1st method: compare array:

function palindrome(str) {
  let arr = str.split('');
  let reversed = [];

  for(let i = arr.length-1;i>=0;i--){

  console.log("reversed is:" + reversed);
  console.log("original is:" + arr);

  if(reversed===arr){return true;}
  else{return false;}



2nd method comparing strings

function check (string){
	let new_string = string.split('').reverse().join('');


	if (string === new_string){
		return true;
	return false;



how come the second one works and the 1st one will give you false no matter what?

function check(string){
	let new_string = {};

	for(let i = string.length-1; i>=0; i--){
		new_string = new_string + string[i];

	console.log("string is " + string);
	console.log("reversed string is: " + new_string);
	return new_string === string;


And the snippet above the value of new_string is:

[object Object]olleh

why is there an [object Object ] in front of olleh?

Edit: this code snippet is worng because I assigned new_string to an empty object

You can’t compare arrays like that unfortunately :frowning:
That would be convenient though.

You can either run a loop and compare them value by value or simply turn them into strings.

1 Like

Same with the bottom one.

It’s giving you unexpected behavior because you can’t add an object to a string like that.

1 Like

I found this article:

Maybe this is the correct way to compare arrays?

Wow haha. That is a really long function.

I probably wouldn’t write that unless I am required to.

1 Like