JavaScript Functions is a Statement or Expression?

Answer of above question is JavaScript functions can be used either as statement or expression. JavaScript functions can be treated in different ways. They can be

  • Expression
  • Passed as value
  • Returned as value
  • Statement

Functions in JavaScript can be Expression or Statement. Problem is in both flavour they look exactly same.

So a function statement is

clip_image001

This can be also written as below. Here we are assigning function as expression to a variable.

clip_image002

Function statement are always hoisted to the scope it is defined. So you do not need to define a function before using it. Consider following example,

clip_image003

In above function statement, we are using function before it is defined. You will get expected result.

Now let us make function as expression,

clip_image004

Above lines of code will throw you exception that funct1() is undefined. So function as expression does not get hoist to its scope.

clip_image006

JavaScript function can be used in if statement as well,

clip_image007

You will get following output,

clip_image008

If you change return of function to 0 then if statement would not get executed,

clip_image009

Apart from this JavaScript function can be treated as value as well. JavaScript functions act as Value. They can

  • JavaScript function can be assigned to a variable
  • JavaScript function can set as property of an Object
  • JavaScript function can be passed as argument to other function
  • JavaScript function can be returned from function etc…

You can assign function as Object property. This can be done as following,

clip_image001[6]

You see that above we assigned a JavaScript function as Object’s Property. You can use JavaScript function as argument of another function. This can be done as below,

clip_image002[6]

So we learnt in this post that a JavaScript function can be used either as statement and expression. I hope you find this post useful. Thanks for reading.

4 responses to “JavaScript Functions is a Statement or Expression?”

  1. […] JavaScript Functions is a Statement or Expression? (Dhananjay Kumar) […]

  2. […] JavaScript Functions is a Statement or Expression? […]

  3. […] JavaScript Functions is a Statement or Expression? […]

Leave a comment

Create a website or blog at WordPress.com