-1

I am just a little confused on why I get the output of [Function] when I am executing a function that I created.

var nameString = function (name) {

return "Hi, I am" + " " + name;     
};


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

I understand that I am using the function within console.log to print out the value of it. Is it not supposed to print out my name "yasser" instead of saying function?

4 Answers 4

3

When you do console.log(nameString), it will just print the output of .toString() called on that function like nameString.toString(). The output of this will be [Function]

You need to execute the function nameString with string argument and then log the returned output as follows

console.log(nameString("Yasser"))
Sign up to request clarification or add additional context in comments.

Comments

1

Because you are running console.log on the function, you are not calling it, so you wont get the return value. I see you have called the function above the console.log, but you have not assigned the value anywhere

try

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

or

var s = nameString("Yasser");
console.log(s);

Comments

1

You are returning a string from your function but not assigning it to anything.

When you console.log you are not using the result of the previous call; you are simply printing what is, in effect in Javascript, a function pointer.

To fix this you should assign the result to a variable:

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

Or simply inline the result of the function:

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

Comments

1

Very basic thing for you to understand in the Javascript code shared, There are two things to be considered:

  1. Function Reference ----> nameString is the just a reference to the function. Nothing more!

    Check this: http://jsfiddle.net/d73heoL2/1/

var nameString = function (name) {

return "Hi, I am" + " " + name;     
};
alert(typeof nameString);

  1. Function call----> For a function to execute, you need to call it. For ex:

nameString();

Having said that, what you wanted can be achieved like this:

var nameString = function (name) {

return "Hi, I am" + " " + name;     
};

alert(nameString('WooCommerce'));

1 Comment

Perfect Explanation! Appreciated @Rakesh_Kumar

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.