Javascript Functions Basics
by Kyle Pennell
JavaScript
/**
* Definition
*/
// statement/declaration
function add(a, b) {
return a + b;
}
console.log(add(1, 2)); // 3
// expression
var add = function (a, b) {
return a + b;
}
console.log(add(1, 2)); // 3
var add = function (a, b) {
return a + b;
}
// function constructor
var add = new Function("a", "b", "return a+b;");
console.log(add(1, 2)); // 3
/**
* Properties
*/
// example of "arguments" property
var sum = function () {
var i,
sum = 0;
for (i = 0; i < arguments.length; i += 1) {
sum += arguments[i];
}
return sum;
}
console.log(sum(4, 8, 15, 16));
// invoke functions by trailing with () parenthesis
// you can also invoke functions indirectly...
var Person = function Person(first, last){
this.first = first;
this.last = last;
};
var Engineer = function Engineer(first, last, level) {
Person.call(this, first, last);
// alternatively use apply
//Person.apply(this, [first, last]);
this.level = level;
}
var newEngineer = new Engineer("Jim", "Bob", "Guru");
console.log(newEngineer);