JavaScript Functions

Basic Functions

function mySimpleFunction () { // Defining the function console.log("Testing"); } mySimpleFunction(); // Calling/Running the function

- A function is a group of code that can be run in other parts of the program as many times as needed

Functions That Receive Input:

function myParamFunc (name, age) { console.log("My name is " + name + " and I am " + age + " years old."); } myParamFunc("Joey", 12); // Provide parameters when calling function

- Parameters allow a function to run with specified values, name and age are parameters in this example

- Parameters have to be provided in the same order that they are defined in the function definition; e.g. It won't work as expected if you call myParamFunc(12, "Joey")

- If a variable is provided as a parameter value such as in myParamFunc(myVar1, 12), it passes the value of the variable, so the variable will not be updated by the function and will retain its original value after the function ends (unless it is an array or object, which will be covered later)

Functions That Produce Output:

function myOutptFunc (myPrm1) { // Replace "void" with the data type of the result return myPrm1 * 2; } myFuncResult = myOutptFunc(4); // Receive the function output as a value console.log(myFuncResult);

- Functions can return a value of any data type (e.g. number, String, ...)

- The result of the function doesn't have to be stored as a variable, it could be accessed like a value, for example: console.log(myOutptFunc(3));

Challenge

Write a function that will take two numbers as parameters and will return the value of them multiplied together. Make another function that will take 4 numbers as parameters, and it will call the first function on the first two numbers and add the result to the result of the first function on the last two numbers. Display the final result.

Completed