different ways to write a function in an object
Hey, i've seen a function in an object either being written as a key value pair on simply on it's own e.g.
What is the difference between these two methods and when would you need to use one over the other? perhaps is just preference too? Thanks in advance.
17 Replies
this is the first time i am seeing the 2nd one
there are i think quite some ways to do it
like u can arrow functions
exampleFunc: () => {...}
the main difference between arrow func and anyonymous function i believe is just in the this
keyboard
this keyword in arrow function refers to gloabal this i.e window object
where is in anonymous function is refers to the object itselfit's not just that:
-
this
doesn't change
- arguments
doesn't exist
- implicit return if you have just 1 expression without braces
- if you have 1 argument, you don't need parenthesiswhen you say arguments don't exist in an arrow function, what do you mean? i thought you could use arguments? like so
no, im talking about the
arguments
variable
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/argumentsOhh I see
And this is true for arrow functions, not the syntax snxxwyy showed afaik. That's an anonymous function but it should still work like a regular named function I think? AFAIK the difference between snxxwyy's examples is nonexistent
yes, but i wasn't talking about that
i was answering to this
but in the object, it's exactly the same
the example code, that is
however, i think it is a named function
yes, it is a named function
this:
is the same as this:
Not saying you were, just clarifying for the actual question of the topic
that makes sense
I didn't even know this was a thing lol.
ok so this keeps track of all the arguments u pass in, even if u pass more arguments than is required. so basically this is the equivalent of the rest parameter?
not exactly
it has other things that rest parameters don't have
i see
differences between rest parameters vs
arguments
:
- arguments
has ALL the arguments
- rest parameters only have the rest of the parameters that aren't associated to a specific argument variable
- arguments
is an array-like object, rest parameters are an array
- arguments
has the callee
property, which refers to the function itself (just ... don't ask)
- arguments
isn't available in arrow functions
- rest parameters are a syntax change to javascript, while arguments
is just a variable
- returning arguments
is VERY VERY VERY bad, returning rest parameters is fine
- to receive rest parameters, you must write the arguments
- for the arguments
to work, you don't need to declare any arguments
for example, take this code:
if you call it like this: func_name(1, 2, 3, 4, 5)
you have the following results:
- abc(1, 2, 3, 4, 5)
-> [1, 2, [3, 4, 5]]
- args(1, 2, 3, 4, 5)
-> [1, 2, 3, 4, 5]
i see. thank you very much for the in dept information
you're welcome