Art of Code — Problem Set 1
Functions vs. Methods
A JavaScript function is a block of code designed to perform a particular task. Functions are executed when “something” invokes it or calls it. A JavaScript function is defined with the functionkeyword, followed by a name, followed by parentheses().Function names can contain letters, digits, underscores, and dollar signs .The parentheses may include parameter names separated by commas: (parameter1, parameter2, …)The code to be executed, by the function, is placed inside curly brackets: {}
Example:
function myFunction(x1, x2) {
return x1 * x2;
}
JavaScript Methods are functions that live in properties and act on the value they are a property of. Methods are the actions that can be performed on objects.
Example:
var person = {
firstName: “Shakir”,
lastName : Moss”,
fullName : function() {
return this.Shakir+ “ “ + this.Moss;
}
};
Constructors, which are functions whose names usually start with a capital letter, can be used with the new operator to create new objects.The new object’s prototype will be the object found in the prototype property of the constructor function.
Example:
function Person(first, last, age){
this.first = first;
this.last = last ;
this.age = age;
}
person.prototype.name = function() {
return this.firstName + “ “ + this.lastName;
};
This concludes the writing assignment.