简体   繁体   中英

trying to run a simple beginner function in javascript, not returning correctly

Here is the code I wrote;

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

};
nameString("Bobby");

I am trying to get it to return one line stating; Hi, I am Bobby

instead, it returns three:

Hi, I am Bobby
Hi, I am
Hi, I am Bobby

I can't figure out why it is returning three times

Codecademy runs the function 3 times for some reasons, basically to detect stuff and hint you on the right code... Each time outputing something in the console since you put console.log . Use return instead and it will work.

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

};
console.log(nameString("Bobby"));

Don't use the console in codecademy functions, it needs to be on the call..

This on it self just renders the result just one time. Maybe it is nested in some code which ensures the three execution cycles...

Well, it's the first time I see a function like yours (I'm not saying it be bad, I'm not a JavaScript expert)...

Try it:

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

I think your problem is that you are trying to put the returned value of a function as value of a variable. But really, your function does not return any value. So maybe it's causing this rare behavior that you tell us... Other approach more similar as yours:

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

Use it:

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

var theName = prompt("What is your name?");
var result = nameString(theName);
console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM