-1

I'm trying to run thie following code. It throws me a TypeError: hello is not a function on the second call of Logger.log(hello());

Here are the two functions:

function hello() {
  return hello = 'hello';
}

function testHello() {
  Logger.log(hello());
  Logger.log(hello());
}

Any help explaining why this happens and a workaround to it would be very appreciated.

Rubén
  • 34,714
  • 9
  • 70
  • 166
Juan
  • 1

1 Answers1

1

I think that when I saw your script, in your script, the following flow is run.

  1. At 1st running Logger.log(hello()); of testHello(), hello() is run as a function and hello of string value is returned. At that time, hello is assigned with a string value. By this, hello is changed from function to string as the global.
  2. At 2nd running Logger.log(hello());, hello is string. By this, an error like TypeError: hello is not a function occurs.
    • I thought that this is the reason of your issue.

For example, when typeof hello is used in your script, you can see the change of type. The sample script is as follows.

function hello() {
  return hello = 'hello';
}

function testHello() {
  Logger.log(typeof hello);
  Logger.log(hello());
  Logger.log(typeof hello);
  Logger.log(hello());
}

When this script is run, you can see the following values in the log.

function
hello
string
TypeError: hello is not a function <--- An error occurs here.

If you want to avoid this error, how about the following modification?

function hello() {
  var hello = 'hello'; // or let or const instead of var
  return hello;
}

function testHello() {
  Logger.log(typeof hello);
  Logger.log(hello());
  Logger.log(typeof hello);
  Logger.log(hello());
}

In this case, you can see the following values in the log.

function
hello
function
hello
Tanaike
  • 181,128
  • 11
  • 97
  • 165