Woocommerce Lover
Woocommerce Lover

Reputation: 11

Javascript Function does not return expected output

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?

Upvotes: -1

Views: 234

Answers (4)

Rakesh_Kumar
Rakesh_Kumar

Reputation: 1452

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'));

Upvotes: 1

Dean Ward
Dean Ward

Reputation: 4793

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"));

Upvotes: 1

Kelsadita
Kelsadita

Reputation: 1038

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"))

Upvotes: 3

atmd
atmd

Reputation: 7490

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);

Upvotes: 1

Related Questions