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
This can be also written as below. Here we are assigning function as expression to a variable.
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,
In above function statement, we are using function before it is defined. You will get expected result.
Now let us make function as expression,
Above lines of code will throw you exception that funct1() is undefined. So function as expression does not get hoist to its scope.
JavaScript function can be used in if statement as well,
You will get following output,
If you change return of function to 0 then if statement would not get executed,
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,
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,
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.
Leave a Reply