Skip to main content

Introduction to Functions in JavaScript

Function is a set of code, that is defined once and can be called n number of times. A function can be reused, thus they are also used to avoid repetition of code. Function are reference datatype in javascript. Function includes multiple statements to perform task. A function can take input and then return output. Functions are one of the major building blocks in JavaScript.

Functions are callable entities. To call a function, we use parenthesis after function name, i.e sayHi(). All methods are build-in functions, that's why they must be called using parenthesis.

Function can be both User Defined and Pre-defined ( like alert, print, close, open etc )

JavaScript functions are first-class objects. Means they are very powerful in javascript as compared to other programming languages. They are even more powerful than objects.

Why JavaScript Functions are first class objects?

  1. Functions can be assigned to variables.
  2. Functions can have properties and methods.
  3. Functions can return functions (High order function).
  4. Functions can have callbacks (High order function).

Functions can be easily reused. To invoke a function, we can use events like click, hover, submit, focus, mousemove etc, or just call by function name followed by parentheses.