0

what is the difference between these functions?

let square = function square(number) { return number * number }

let square = function(number) { return number * number }

both work the same but is there any difference?

KBoraB
  • 11
  • 2
  • First arrow function (es6). Second is regular. Thera are some defference between them. You can easly find information about this. Thanks – Hazrat Gafulov Jun 04 '22 at 04:33

2 Answers2

1

This function has a name "square", you need to call it with its name to execute it,

function square(number) { return number * number }

while, this is a anonymous function without a name, and it will execute without any call,

function(number) { return number * number }

read more about anonymus functions here.

Rohit
  • 11
  • 4
  • So which one should I prefer to use? – KBoraB Jun 04 '22 at 04:49
  • both are useful in different scenario, as you said you are new to this so you should use named functions, and anonymous functions can be used in callback situations where it depends on something else to be executed. as they are hard to call. example: ``` var Arr = [2,3,4,5] # Anonymous function goes directly console.log(Arr.map(function(x){ return x+1})); ``` – Rohit Jun 04 '22 at 05:24
  • *"and it will execute without any call"* Huh? A function cannot be executed without calling it. Btw, since the function is assigned to a variable, the function's name will actually be set to the variable's name at runtime. – Felix Kling Jun 04 '22 at 09:32
  • @FelixKling yeah you are right, A function cannot be executed without calling it. but you don't have to make an explicit call to an anonymous function for it to perform a given task. call is made implicitly in case of anonymous functions. – Rohit Jun 04 '22 at 13:22
  • @Rohit: No, that's not right. An anonymous function is just a function without an explicit name. It's not automatically called. It doesn't behave differently than any other function. I mean, paste `(function() { console.log('hello'); })` in your console. You won't see the `console.log` output because the function is not called. – Felix Kling Jun 04 '22 at 13:25
0

In let square = function(number) { return number * number }, you are using whats called an anonymous function and setting its value to square.

In let square = function(number) { return number * number } you are just creating a standard named function and assigning it to the variable square.

Both are functionally the same and its up to user preference.

uwu
  • 27
  • 1