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?
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"))
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);
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"));
Very basic thing for you to understand in the Javascript code shared, There are two things to be considered:
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);
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'));
Related
I'm new to JavaScript, and I try to play around with it to understand all in-and-outs. I write
function greet() {
console.log("Hi");
};
console.log(greet());
And the result of it in the console is
> Hi app.js:2
> undefined app.js:4
I assume this is because greet() inside console.log first calls the function, which prints out "Hi". We get first line of log. But where did the second line come from?
Then I thought because Hi is overall result of greet(), then console.log basically calls variable Hi, but in this case the result would be is not defined, not undefined
In JavaScript, if nothing is returned from the function with the keyword return then undefined is returned by default.
var data = greet();
console.log(data);// undefined, since your function does not return.
Is equivalent to:
console.log(greet());
The second output is the returned result from the function. Since you are not returning anything from the function hence prints undefined.
To print 'Hi' in the second console you have to return that from the function.
function greet() {
console.log("Hi");
return 'Hi';
};
console.log(greet());
You should use a return keyword like this:
function greet() {
console.log("HI");
return "HI";
};
console.log(greet());
Or you can store it in a variable and return the variable:
function greet() {
const hello = ("HI");
return hello;
};
cosnole.log(greet());
,Because if you don't use return keyword and log the function to the console then it returns undefined.
In NodeJS, I pass the first function as a parameter of the second function like this:
The first function
function sayHello(){
console.log('Hello World!');
}
The second function
function log(func){
func();
}
Passing the first function as a parameter of the second function (1):
log(sayHello)();
When I run the code (1) above, there is a TypeError and the correct way is:
log(sayHello); //Without a pair of brackets at the end of the line
Why I cannot use log(sayHello)() as calling a normal function?
A few points:
This is very basic JS, nothing to do with node
How do you call a function func(a) ? You type func(myArg), not func(myArg)()!
If I understand your problem well, you're asking why you should
func(a)
and not
func(a)()
Pretty simple: because func(a)() does something else: it is the same as (func(a))():
first compute func(a)
then take the result (return) of the function func(a)
execute that returned object as a function
If your function does not have a return statement, it returns undefined. So you are actually doing:
undefined()
And undefined is not from a type that can be executed. So you got a typeError.
Let's have a few examples:
function sayHello(){
console.log('Hello World!');
}
function thatReturnSomeThing(){
return 123
}
function log(myFunc){
myFunc()
}
function logWithReturn(myFunc){
return myFunc()
}
function justReturn(myFunc){
return myFunc
}
function functionThatReturnAFunction(){
return function() {return "lots of returns here"}
}
let a = log(sayHello)
console.log("a = " + a) // undef
let b = logWithReturn(sayHello)
console.log("b = " + b) //undef because console.log does not return anything
let c = log(thatReturnSomeThing)
console.log("c = " +c) // undef cause log does not return anything
let d =logWithReturn(thatReturnSomeThing)
console.log("d = " + d) //123 because we returned the result of thatReturnSomeThing, which as well returned something different than undef
let e = logWithReturn(functionThatReturnAFunction)
console.log("e = " + e) //we returned a function, so we log the function itself
let f = logWithReturn(functionThatReturnAFunction)() //the behaviour you actually wanted is that I think
console.log("f = " +f)
I let you run that code, and I hope it would help you understand the difference between function and returned object (which can be a function).
function sayHello(){
return console.log('Hello World!');
}
function log(func){
return func;
};
log(sayHello)();
Just do it like this.Your sayHello was not returning anything.
The return type of log() is not a function that is why you are getting the Type Error. When you call log(sayHello), it is calling sayHello() which in turn call console.log(). The console.log() is then returning the given input which is not a function.
If you want to call log(sayHello)(), just change the log function as given below:
function log(func){
return func;
}
Suppose I have two functions test1 and test2!
test1 = function(name){
console.log('Hi, ', name);
};
test2 = function(name) {
var text = 'Hello ' + name;
var say = function() { console.log(text); }
return say;
}
Now I call the function and save them to vars,
var t1 = test1('John');
var t2 = test2('John');
What is exactly happening here?
Lets understand this:
In below code you are defining a function called test1 which will print Hi, John if you use test1('John').
test1 = function(name){
console.log('Hi, ', name);
};
Now lets understand below code, below you are defining a function called test2 which:
test2 = function(name) {
var text = 'Hello ' + name;
var say = function() { console.log(text); }
return say;
}
var text = 'Hello ' + name; //define a variable called text
var say = function() { console.log(text); } //defininga a function called say which will log the data in variable text in the console.
Then you are returning say function.
OUTPUT:
Input: => var t1 = test1('John');
Output: => Hi, John //It's quite straight forward.
Input: => var t2 = test2('John');
Output: => undefined //Here you are re-assigning function returned from test2 which was say to t2. Hence if you now type t2 then you wil get function () { console.log(text); } as output which is similar to say.
I hope you understood, sorry for poor english.
Your function test1 returns void, since there is no return statement
This function prints Hi John to the console
Your function test2 returns the function say() to the console and stores it in t2. This makes t2 a function. If you pay attention to the syntax in test2 that's one of the two standard ways of defining a function in javascript. if you call
t2();
you will get the similar output to test1('John');:
Hello John
your first function executes a code and don`t return any thing then t1 will be undefined. but second function returns a function then t2 contains a function that never called so it will not log to console
On calling, test2 returns 'say' which is a pointer to a function, not the value. That is why it will not output anything.
To call function 'say' you need to do test2('john')().
In the second pair of parenthesis, we pass in the arguments to the function inside.
var name = "myName";
function test() {
document.write(name);
}
var testcheck= test();
document.write(testcheck);
This returns " myNameundefiend " that is the value+undefined
why is that happening ?
You're not returning a value from your test function, making the testcheck variable undefined.
The test() call first writes the name to the document, then document.write(testcheck); adds undefined behind that.
You'll need to return name from the function:
function test() {
document.write(name);
return name;
}
There's no need to document.write twice. Either only keep it in the function, or remove it from the function and use document.write(testcheck);.
Update
The code for the function / class is stored in a string which is why I cannot call it directly. The idea is to do introspection on the object and enumerate its data members which works when it is a function but doesn't work when a variable like the one below is eval'ed.
I am trying to evaluate an object in javascript. Something like this.
var myObj {
greet: "Greeting",
myPrint: function() {
alert("hello");
}
};
The idea is to be able to run this in eval and get the variable name somehow (myObj) or an object created. I have experimented with various methods using eval but cannot figure this out. This works when I have something like this.
function myObj() {
this.greet = "Greeting";
this.myPrint = function() {
alert("hello");
}
};
Running eval("(" + code + ")"); where code is a string containing the above function returns myObj() to me.
Update 2
So basically I want to evaluate something like this.
eval("var x = 5"); and I am trying to get x. Since its a string being evaluated, even though it gets added to the window namespace, there is no way to decipher it apart from parsing the string. Now this is just a simple example but as I said, it's a little difficult with the 1st piece of code. As I said...
eval("function test() { return 'hello'; }"); return test() which is similar to what I am expecting for the "var x = 5" statement.
Is there a way to do this similarly for the 1st case which I am missing ?
Thanks
A code:
var sCode = '{ great: "Greating", myPrint: function() { alert("hello!"); } }',
oObj = eval("(" + sCode + ")");
oObj.myPrint(); // alert "hello"
console.log(oObj.great); // prints "Greating"
Are you trying to dynamically call a callback?
var myObj = { // fixed this line of code as it was missing the =
greet: "Greeting", // replaced ; with ,
myPrint: function() {
alert("hello");
}
};
console.log(eval(myObj)); // returns obj as expected.
If I am correct in my assumption you would need to use bracket notation and EVAL is not needed
So if you were passing a String it would look like:
var str = 'myPrint';
var strTwo = 'greet'
myObj[str](); // to execute the function
myObj[strTwo]; // now contains "Greeting"
Which would execute that function.
Hope that helps!
Tim
EDIT:
var myObj = 'var myObj = { greet: "Greeting", myPrint: function() { alert("hello"); } }'
console.log(eval(myObj));
myObj.myPrint();
Then this is what you want if this does not work it means you are not escaping your string correctly:
http://jsfiddle.net/XtyHh/
You eval the object without executing the myPrint function.
You would need to do something like
myObj.myPrint()
To get it to throw the alert.
[edit] To immediately run the myPrint function change your code to this:
var myObj = {
greet: "Greeting",
myPrint: (function() {
alert("hello");
})();
};