+ 3

JS Palindromes function

Whats the mistake in my code? why it's not checking palindromes it's only return trur. function palindromes(str){ for(var i=str.length-1; i>=0; i--){ } for(var e=0; e<str.length; e++){ } if(str[i] === str[e]){ return true; } else{ return false; } }

24th Feb 2018, 3:53 PM
Abdul Basit
Abdul Basit - avatar
7 Respuestas
24th Feb 2018, 4:11 PM
Swapnil Srivastava
Swapnil Srivastava - avatar
+ 18
And, the error is that after the for loops, i becomes -1 and e becomes str.length and thus, str[i] and str[e] both are undefined. Thus, undefined === undefined. Thus, it always returns true.
24th Feb 2018, 4:15 PM
Swapnil Srivastava
Swapnil Srivastava - avatar
+ 18
@Abdul Basit yes I'm Indian @Code Learner I'm not 'sir'
25th Feb 2018, 2:00 AM
Swapnil Srivastava
Swapnil Srivastava - avatar
+ 16
With the comma, we are using both the variables in a single loop. So, both the variables are used. One runs from str.length-1 to 0 and the vice versa for the other.
24th Feb 2018, 5:03 PM
Swapnil Srivastava
Swapnil Srivastava - avatar
+ 2
@Abdul,@Swapnil Swapnil sir's answer is correct. If two variables in for loop confuse you , you could do this way function palindromes(str){ for(var i=0; i<str.length; i++){ if(str[i] != str[str.length-1-i]){ return false; } } return true; } because you can find e by knowing i and vice versa.
25th Feb 2018, 12:38 AM
code learner
code learner - avatar
+ 1
I didn't understand this for loop for(var i=str.length-1, e=0; i>=0 && e<str.length; i--,e++) I mean the arrangement. Can we change the arrangement of variables?
24th Feb 2018, 5:01 PM
Abdul Basit
Abdul Basit - avatar
+ 1
Ohhh... I didn't pay attention on comma. Cant we write both loop separately? Are you Indian?
24th Feb 2018, 5:12 PM
Abdul Basit
Abdul Basit - avatar