I'm learning JavaScript and am trying to learn the proper terms for what I am doing. There are so many ways to create a function.
I have created 3 examples that do the same thing, but the functions are created in completely different ways.
My questions are:
Are any one of these methods better than the other?
Why would I choose to do one way or another?
What is the last "object" method called?
What advice would you have to make this example better?
//EXAMPLE 1
// is this called function declaration?
function add( a, b ) {
return a + b;
}
function subtract( a, b ) {
return a - b;
}
function compute( a, b ) {
var sum = add( a, b );
var difference = subtract( a, b );
var total = sum + difference;
return total;
}
compute( 2, 3 ); //returns 4
//EXAMPLE 2
// is this called function expressions?
var add = function ( a, b ) {
return a + b;
};
var subtract = function ( a, b ) {
return a - b;
};
var compute = function ( a, b ) {
var sum = add( a, b );
var difference = subtract( a, b );
var total = sum + difference;
return total;
};
compute( 2, 3 ); //returns 4
//EXAMPLE 3
// what is this method called?
var calculator = {
add: function ( a, b ) {
return a + b;
},
subtract: function ( a, b ) {
return a - b;
},
compute: function ( a, b ) {
var sum = this.add( a, b );
var difference = this.subtract( a, b );
var total = sum + difference;
return total;
}
}
calculator.compute( 2, 3 ); //returns 4