Is this a functional declaration, expression, and object?

I learn JavaScript and try to learn the right terms for what I do. There are so many ways to create a function.

I created 3 examples that do the same, but functions are created in completely different ways.

My questions:

  • Are any of these methods better than others?

  • Why should I do anyway?

  • What is the last method of the object called?

  • What advice should you make 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
Run codeHide result
+4
source share
2 answers

Function declaration:

function add(a,b) { return a+b; }

A function declaration is defined during parsing for a specific script block. It can be called anywhere in the block without causing an error:

(function() {
    add(3,3)    //The function block has already been parsed, add() is available
    function add(a,b) { return a+b; }
})();

Function Expressions:

var add = function(a,b) { return a+b; }

. .

(function() {
    add(3,3)    //Error: add() has not yet been defined.
    var add = function(a,b) { return a+b; }
})();

:

- , .

var obj = {
    propert1: 'property1 value',
    add: function(a,b) {
       return a+b;
    }
};

obj.add(3,3), .

?

. . ( ):

(function returnVal() {
    function getSomething() {
        return 'foo';
    }
    return getSomething();

    function getSomething() {
        return 'bar';
    }
})();  //returns 'bar'

, , getSomething() .

(function returnVal() {
    var getSomething = function() {
        return 'foo';
    }
    return getSomething();

    getSomething = function() {
        return 'bar';
    }
})(); //returns 'foo'

, , , , .

var obj = {};
obj.foo = function() { /*code*/ }
obj.bar = function() { /*code*/ }

, obj. .

+1

- ?

function add( a, b ) {
  return a + b;
}

.

- ?

var add = function ( a, b ) {
  return a + b;
};

. , function(…){…} , ( , ).

?

… {
    add: function ( a, b ) {
        return a + b;
    },
}

, . , .

- ?

( ). , , (, IIFE, , , , ..).

+3

All Articles