0

Hello everyone,

I'm relatively new to programming, and I've been practicing functions and variables, mainly for web development. However, I'm still trying to grasp the concept fully. I've watched several tutorials, and I've noticed that some use functions within a variable while others use functions alone. I understand the idea of reusing functions multiple times, but at times, it seems unnecessary. Let's take an example to illustrate my point:

Example 1 :

var askQuestion = function() {
    return prompt('What\'s the first letter of your name?');
}

Example 2:

function askQuestion() {
    return prompt('What\'s the first letter of your name?');
}

Both examples seem to output the same thing. If I want to reuse the function later on, I still have to refer to it as askQuestion or askQuestion() in both cases, right? The only difference I notice is the absence of parentheses in the first example. So, my question is, what is the point of assigning the function to a variable? I'm still a beginner, and I might be missing something obvious. I'd greatly appreciate any help or clarification you can provide. Thank you! :)

I have tried watching tutorials and finding explanations online...but they all say the same thing..about reusing the function several times....but nobody seems to talk in detail about why one is more preferred over the other depending on use case scenarios...I would like a response in detail with explanations as to why.

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    The main difference is that you can use `askQuestion` before its declaration if declared as a plain `function`, not if you declare it as a `var` – Guerric P Jul 19 '23 at 13:23
  • https://stackoverflow.com/questions/11146814/difference-between-assigning-function-to-variable-or-not – 0stone0 Jul 19 '23 at 13:24
  • when you assign a function to a variable, thats called an anonymous function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function – Chris G Jul 19 '23 at 13:24

0 Answers0