+ 4

help me call the if statement in the function

function greet(name1,name2,name3, name4){ return "Hello, " + name1 + "!"; "Hello, " + name2 + "!"; "Hello, " + name3 + "!"; var name4= "Johnny"; if(name4 === "Johnny") { return "Hello, my love!"; } } greet("Jim","Jane","Simon", "Johnny"); //only greet Jim, Jane, and Simon //I need name4 to say Hello, my love

1st Feb 2017, 1:04 AM
totoro
totoro - avatar
5 Antworten
+ 13
function stops executing once it hits return statement. And in your case your code stops execution right at second line. Your code could be very simple and better like this: function greet(name) { if (name === "Johnny") { return " Hello, my love!"; } else { return "Hello " + name + "!" ; } } You may now call the function and pass in any of the names as argument. When you pass in "Johnny" the greeting will be exactly how u want it and the rest accordingly. e.g console.log(greet("Johnny "));
1st Feb 2017, 1:15 AM
Benneth Yankey
Benneth Yankey - avatar
+ 7
Try to change the strict equality ( === ) to simple equality ( == ), else you are comparing if 'name' and string 'Johnny' are same object, not just same content as expected ;) Anyway, I guess your line 'var name4="Johnny";' was there for debuging purposes? Else, you'll be always True at next 'if' statement ^^
1st Feb 2017, 7:39 AM
visph
visph - avatar
+ 5
Oh yes... I didn't notice that the first line of your function is still a return statement, so others lines are never executed ^^ Try to: function greet(name1,name2,name3, name4){ var r="Hello, " + name1 + "!\n"; r+="Hello, " + name2 + "!\n"; r+="Hello, " + name3 + "!\n"; } if (name4 == "Johnny") { r+="Hello, my love!\n"; } else { r+="Hello, " + name4 + "!\n"; } return r; } ( corrected with use of a var 'r' to prepare the string for return, instead trying to returning value in many times )
3rd Feb 2017, 2:50 AM
visph
visph - avatar
+ 2
@visph I only could solve the other 3 I tried so hard to manipulate Johnny into scream hello my love! But I guess he don't love me -.-
3rd Feb 2017, 2:37 AM
totoro
totoro - avatar
+ 1
The shortest form: function greet(name){ return "Hello, " + (name=="Johnny" ? "my love" : name)+"!"; }
7th Feb 2017, 8:44 PM
Denis Saveliev
Denis Saveliev - avatar