Why are functions written differently in javascript objects?

Hey,

Outside of a javascript object, you have to explicitly write ‘function’. While inside objects you can write it without this word.

Outside object:

function exampleFunction(){}
Inside Object:

object = {
  randomFunction(){}
}

What am I not getting?

Well actually, it is not a function inside an object but a method :wink: .

Haha awesome, could you expand on your answer :wink:

Ill try :wink:

Whilst assigning a (global) function you are actually defining a variable of the type function similar to let, const and var. This is what we know as a function.

Now to the syntax, we know defining variables in general is done by presenting a type a name and a value. Hence function exampleFunction(){} To call/execute it we simply type exampleFunction();

A method is a function (sorry for the confusion) but the difference being that it is a property of an object. This method is part of this object alone.

As you know assigning a property of an object is done by defining key : value pairs. In the case of a function we can simply assign it by writing down randomFunction() inside the object.

Calling this property is then done by calling the object and chaining its property: object.randomFunction();

I hope this somewhat explains it.

Yes that makes sense! Thanks :wink:

1 Like