3 Type Javascript Function

wahyu eko hadi saputro
3 min readApr 16, 2022

In javascript, function is treated as a object, for me that come from java OOP guy, learning java script style is little confusing but lets try to understand step by step. There are 3 type function of javascript :

  1. declaration function (function with name function)
  2. Anonymous function (function without name)
  3. arrow function

There 2 ways to call a function of declared function, the first one is with new keyword and the second one is without new keyword. If calling with new keyword it means we create new instance, and if calling without new keyword it means calling usual function. If the function does not have return value, then we call the function without new keyword, it cause the result will be undefined. To implement the theory, let practice with chrome or mozilla console development tool.

function Person(name, age) {  this.name = name;  this.age = age;}function Employee(name, age) {  return name}const varPerson = Person(“ana”, 5)console.log(varPerson)const varEmployee = Employee(“ana”,6)console.log(varEmployee)

From above image we can see, that varPerson is undefined due to calling function without new keyword and the function doesn’t have return statement, and otherwise for varEmployee. In javascript there is one very useful keyword that is “this” keyword. Keyword “this” will refer to current context, and the default reference is window. Execute bellow code and see the result

console.log(this)console.log(this.Employee(“ana”, 8))

Based on image above, this refer to window and we can call function with keyword this. If you come form OOP like java, must be understand the concept of this keyword. Next we will call function declaration with new keyword.

Based on above image, we created objPerson1, and we deep dive instance objPerson1 object channing, actually instance objPerson1 has many chain of parent object / prototype object, for prototype object will be discussed later. Syntax console.log(objPerson1.name) will call property name from objPerson1 object instance.

  1. Anonymous function

In javascript usually using anonymous function to assign variable / object property and etc.

const employeeName = function(){  return “paul”}console.log(employeeName())
function Teacher(name, age) {  this.name = name;  this.age = age;  this.nameAndAge = function(){      return this.name + “ “ + this.age  }}const objTeacher = new Teacher(“poter”, 50)console.log(objTeacher.nameAndAge())
  1. Arrow function
hello = () => {  return “Hello World!”;}

Actually arrow function come from anonymous function :

hello = function() {  return “Hello World!”;}hello = () => {  return “Hello World!”;}

Source :

--

--