JavaScript Functions Flashcards
Functions can:
1)
2)
3)
Functions can:
1) hold a series of statements that perform some sort of processing.
2) may return data
3) may receive input via parameters
function functionName(parameter1, parameter2){ statement1; statement2; statement3; return (value); }
In JavaScript, functions can be treated as values. (Show example)
var addNumbers = function(a, b) { return(a+b); };
addNumbers(1,2);
A function can be passed into another function as a parameter (Show example)
var addingFunction = function (a,b){ console.log(a+b); }
var multiplicationFunction = function (a,b){ console.log(a*b); }
var calculate = function(calculationFunction, a, b) { calculationFunction(a,b); };
calculate(addingFunction, 4,12);
calculate(multiplicationFunction, 4,12);
A function can be returned by another function (Show example)
Functions that operate on other functions, either by taking them as arguments or by returning them, are called _____-order functions.
var power = function(power) { return function(number){ console.log(Math.pow(number, power)); } };
var square = power(2); var cube = power(3);
square(5);
cube(5);
Functions as values in Objects (Show example)
var animal = { name:"Rover", age:5, humanYears : function(){ return (15 + (this.age*4)); } }
console. log(animal.age);
console. log(animal.humanYears());
Object Constructors (Show example)
function Circle(r) { this.radius = r; this.area = function() { return Math.PI*this.radius*this.radius; } }
c = new Circle(10); c2 = new Circle(5);
console. log(“Circle 1 Radius: “+c.radius);
console. log(“Circle 2 Area: “+c2.area());
Closures and private variables (Show example)
function Circle(r) { var radius = r;
return {
area: function(){
return Math.PIradiusradius;
},
setRadius: function(r){
radius = r;
}
}
}
c = new Circle(10);
console. log(“Circle Radius: “+c.radius);
console. log(“Circle Area: “+c.area());
c. setRadius(5);
console. log(“Circle Area: “+c.area());