-1

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,440
  • 6
  • 26
  • 57
Chirayu Sharma
  • 75
  • 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')` –  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 Sharma 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
  • 914,110
  • 126
  • 1,211
  • 1,335
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
  • 12,049
  • 2
  • 17
  • 33
1

you can use anonim call

(function(){ console.log('hi') })()
Vadim Hulevich
  • 1,803
  • 8
  • 17
0

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

Houssein Zouari
  • 712
  • 6
  • 18