Is it Best Practice to Assign a Function to a Variable?


#1



https://www.codecademy.com/en/courses/spencer-sandbox/3/3?curriculum_id=506324b3a7dffd00020bf661


My code is working fine, I am just curious: would we normally assign this function to a variable?


function Cat(age, color) {
  this.age = age;
  this.color = color;
}


#2

Yes, @betaslayer23552, we would. But in this case, this isn't a function, this is a Object constructor for the object Cat. That is also why you have the lines this.age = age and this.color = color because you are assigning properties to each instance of that object.


#3

Thanks for your quick response @bartholomewallen ! So we never assign Object constructors to variables?

I was also a little confused, sometimes new Object methods were created by naming the object in the name of the variable such as:

square.calcPerimeter = function() {
return this.sideLength * 4;
};

and other times like this:

var setAge = function (newAge) {
this.age = newAge;
};

I have read w3schools and mostly understand how to use these techniques but still feel like I am missing something, maybe in the 'why' category. Any explanation you or anyone else could offer or maybe some additional reading to ensure I completely understand the concepts presented?

Thanks again!


#4

Well the difference is mostly visual, @betaslayer23552,

Well the difference is sort of in JavaScript understanding. Function of this form

function funcName(arg1, arg2) {
    //Some code!
}

are called "named functions", and they are registered at the start of the execution of the JavaScript code. Whereas functions of the following form

var funcName = function(arg1, arg2) {
    //Some Code!
}

are called anonymous functions. These are effectively treated as variables that hold a function value in them, and so are assigned when the code reaches them.

What does this mean?

Let us use a function add as an example

For named functions, it means that, this code

var sum = add(1, 2)
function add(arg1, arg2) {
    return arg1 + arg2;
}

will execute properly and return 3, whereas this code

var sum = add(1, 2)
var add = function(arg1, arg2) {
    return arg1 + arg2;
}

will throw an error. However, in this case, Codecademy is just doing this for a visual difference between functions and Object constructors. It is generally best practice to use the

function funcName(arg1, arg2) { 
    //Some code!
}

form since you have the freedom of using it anywhere. Hope this addresses all your doubts.

PS If your feel my answer is satisfactory, then please put it as the solution so that others know the topic has been resolved.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.