0

Calling function with a return only returns string without a parameter. It only outputs "Hi, I am" what am i missing here. I have searched and searched...

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

I have also wrote it like this.

function nameString(name){
return "Hi, I am" + " " + name ;
};
nameString("casey");
console.log(nameString(name));
1

4 Answers 4

2

You're not calling it with a defined parameter, so it's not going to do anything.

Breaking down your example:

var string = function nameString(name) { // Declares a function nameString and assigns it to string
  return "Hi, I am" + " " +name;
};
string("casey"); // Calls string with name:"casey" but discards the return value
console.log(nameString(name)); // Calls nameString with the undefined global variable name

That's not going to work, since you end up returning "Hi, I am " + undefined.

What you probably want to do is call nameString and then save the return value, which is written:

function nameString(name) {
  return "Hi, I am" + " " +name;
};
var string = nameString("casey");
console.log(string );
Sign up to request clarification or add additional context in comments.

Comments

2

In the scope outside the function the variable 'name' is undefined. You have to define the variable first, than you can pass it as an argument to the function. This way:

function nameString(name){
return "Hi, I am" + " " + name ;
};

var name = "casey";
console.log(nameString(name));

If you are not too experienced, i suggest avoiding name conflicts in order to avoid confusion, so it would be better do this way :

function nameString(name){
return "Hi, I am" + " " + name ;
};

var exernalName= "casey";
console.log(nameString(externalName));

Comments

1

Your Syntax is off a bit.

var string = function nameString(name) {
  return "Hi, I am" + " " + name;
};

alert(string("casey"));

Comments

1

Your function should be a function expression or a function declaration so either:

var string = namestring() {}; // function expression

or

function nameString(name) {}; // function declaration

Your first one is both and that is why it doesn't work. To fix it you should just do:

function nameString(name) {
return "Hi, I am" + " " +name;
};

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

Additionally I think what you were going for in your first attemp was something like this:

function nameString(name) {
  return "Hi, I am" + " " + name;
};

var string = nameString("casey"); // save this value to a var to use later

console.log(string); // use the "string" variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.