My whole goal was to write a loop that would take a string, count the letters and return two responses: one = "this word is symmetric" or two = "this word is not symmetric". However the code I wrote doesn't console anything out. Here's the code:
var arya = function(arraycount){
for (arraycount.length >= 1; arraycount.length <= 100; arraycount++) {
while (arraycount.length%2 === 0) {
console.log("This is a symmetric word and its length is " + " " arraycount.length " units.");
arraycount.length%2 != 0
console.log("Not a symmetric word");
}
}
}
arya("Michael");
There are many ways to accomplish your goal, but here are a few. The first is a somewhat naïve approach using a
for
loop, and the second uses recursion. The third asks whether the string equals the reverse of the string.iterative (
for
loop) functionThis function begins by asking whether your input string is a single character or empty string, in which case the string would be a trivial palindrome. Then, the
for
loop is set up: starting from 0 (the first character of the string) and going to the middle character, the loop asks whether a given character is identical to its partner on the other end of the string. If the parter character is not identical, the function returnsfalse
. If thefor
loop finishes, that means every character has an identical partner, so the function returnstrue
.recursive function
This function begins the same way as the first, by getting the trivial case out of the way. Then, it tests whether the first character of the string is equal to the last character. Using the ternary operator, the function, returns false if that test fails. If the test is true, the function calls itself again on a substring, and everything starts all over again. This substring is the original string without the first and last characters.
'reflecting' the string
This one just reverses the string and sees if it equals the input string. It relies on the
reverse()
method ofArray
, and although it's the most expressive and compact way of doing it, it's probably not the most efficient.usage
These will return true or false, telling you whether
string
is a palindrome. I assumed that is what you mean when you say "symmetric." I included some debugging statements so you can trace this recursive function as it works.The Mozilla Developer Network offers a comprehensive guide of the JavaScript language. Also, here are links to the way
for
loops andwhile
loops work in JS.