syntax function javascript code example
Example 1: javascript function
function myFunc(theObject) {
theObject.make = 'Toyota';
}
var mycar = {make: 'Honda', model: 'Accord', year: 1998};
var x, y;
x = mycar.make; // x gets the value "Honda"
myFunc(mycar);
y = mycar.make; // y gets the value "Toyota"
// (the make property was changed by the function)
Example 2: javascript function
// variable:
var num1;
var num2;
// function:
function newFunction(num1, num2){
return num1 * num2;
}
Example 3: javascript function
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUNCTION DECLARATION (invoking can be done before declaration)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function calcAge1(birthYear) {
return 2037 - birthYear;
}
const age1 = calcAge1(1991);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUNCTION EXPRESSION (invoking canNOT be done before declaration)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const calcAge2 = function (birthYear) {
return 2037 - birthYear;
}
const age2 = calcAge2(1991);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ARROW FUNCTION (generally used for one-liner functions)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const calcAge3 = birthYear => 2037 - birthYear;
const age3 = calcAge3(1991);
console.log(age3);