-2

While debugging an issue I executed the following in console of chrome browser

function(){ console.log('hi') }

I am getting following error

Uncaught SyntaxError: Unexpected token (

Could you please explain why is it returning error? It should print the value 'hi'. Thanks

treyBake
  • 6,277
  • 6
  • 25
  • 54
Chirayu Chirayu
  • 51
  • 1
  • 11
  • I'm getting a different error. Also, the above will not print "hi", it will try and define an anonymous function. To display hi, paste `console.log('hi')` – ChrisG Jan 14 '19 at 10:25
  • Hi Chris, I understand that if i use console.log('hi') ,I will get hi printed on the screen but i was using data bind on a button and in that i have to use function on the click of a button. – Chirayu Chirayu Jan 14 '19 at 10:34

4 Answers4

4

You are using a function expression in a context where the function keyword can only start a function declaration.

And if you want it to actually print anything: You have to call it.

You could make it a function declaration by giving it a name:

function myFunction() {
  console.log('hi')
}

myFunction();

You could put it in expression context:

(function() {
  console.log('hi')
})();

// or

const myFunction = function() {
  console.log('hi')
};

myFunction();

// or

+function() {
  console.log('hi')
}();

// etc
Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
2

Do this, you have made a function which is not called or assigned .Name the function and call it.

function a(){ console.log('hi')}
a();
ellipsis
  • 11,688
  • 2
  • 14
  • 33
1

you can use anonim call

(function(){ console.log('hi') })()
Vadim Hulevich
  • 1,719
  • 7
  • 16
0

add a name to your function function test() {}

Houssein Zouari
  • 702
  • 6
  • 18