I'm new for learning Javascript, and have encountered a problem that I cannot figure out it's rationale in an online course. Please take a look on the code below.
function palindrome(word){
let backwardWord = "";
for (letter of word){
// Adding letter at the beginning of the backward string
backwardWord = letter backwardWord;
}
if (word.toLowerCase() === backwardWord.toLowerCase())
return true
else
return false
}
palindrome('racecar');
As you may know, this function aims to find if the string reads the same in forward or backward.
My question is, for what I know, if statement requires {} in order to run, and return can only be used in function, not a if statement. Then why there are no {} in the if statement, and why a return could be used in the code above?
I've tried to rewrite a function using the same format, but it returns undefined rather than true.
let a=1
function test(){
if (a===1)
return true
else
return false
}
Thanks for anyone who answer this question, that will help a lot as I was puzzling for the past 0.5 hour and can't .
CodePudding user response:
When there is only one line inside a function then {} can be omitted. for example:
for(int i=0;i<5;i ){
print(i)
}
can be written as:
for(int i=0;i<5;i )
print(i)
As for your second option, undefined is shown because you have defined your function, but never called it or used it. If you type
test()
in the next line of your code then you will get true
as a answer.
CodePudding user response:
First of all the second function is running and returning true
let a=1
function test(){
if (a===1)
return true
else
return false
}
console.log(test());
console.log(typeof(test()));
If you have 1 line code after if
, {} are not necessary.
And here is your first code. Better use
for (let letter of word)
function palindrome(word){
let backwardWord = "";
for (let letter of word){
backwardWord = letter backwardWord;
}
if (word.toLowerCase() === backwardWord.toLowerCase()){
console.log(backwardWord);
return true;
}
else
return false
}
console.log(palindrome('racecar'));
And last, return
statement will get you out of the function immediately. You are returning true which has a type boolean
, you can see using typeof()
function in the second code.
CodePudding user response:
You are allowed to return
from anywhere within a function. return
, much like break
, immediately leaves whatever block it is executing.