Problems with 11. Function Recap


#1

var nameString = function (name) {
	return S="Hi, I am" + " " + name;
};
console.log(S);
nameString("yowsimmo");

Problems with 11. Function Recap. Help?
#2

Running this I get an error concerning that S comes out of nowhere. Could you explain what you intended to do with it?


#3

S comes from inside the function:

return S="Hi, I am" + " " + name;

but that is not how this works


#4

@yowsimmo, you should call your function first, before you try to log something which is inside the function:

 var nameString = function (name) {
	return S="Hi, I am" + " " + name;
};
nameString("yowsimmo");
console.log(S);

your function doesn't gets executed until you call it, so then S is still undefined. I am still not sure this is the recommended way.


#5

I am still not sure this is the recommended way.

No it's not. This would use a global variable S to return something to the screen. Not only uses it a rather dangerous form of global variables that implicitly adds a property to the window object:
http://stackoverflow.com/questions/4862193/javascript-global-variables
but also it is simply not necessary as the return already gives the opportunity to get the value back to the main scope e.g.

var nameString = function (name) {
	return "Hi, I am" + " " + name;
};
var s = nameString("yowsimmo");
console.log(S);

would make far more sense.


#6

I already suspected that, and in this exercise there is no need to store the returned string in a variable, so the other recommended way is:

console.log(nameString("yowsimmo"));

Thanks haxor, always good to learn from you :slightly_smiling:

@yowsimmo, hopefully you can resolve the issue with our suggestions.


#7

i tried this and output came.

Hi,I'm ahab
Hi,I'm yowsimmo

see this

with no error.


#8

Weird, still, as you can read in our reply's it is bad practice.


#9

What happens is the following, when you press submit your code runs an SCT (submission correctness test) that runs your code with a few inputs to see if it is working and it seems like "Susie" is the first and "Captain Ahab" is the last test to check your code. So as you're doing something unexpected you see code that is meant to only run in the background.


#10

Thanks, I reveiwed the function recap and recorrected the line, It worked and my confussion clear

output came in single line
Hi, I am yow simmo