Functions
Functions are re-usable pieces of code, a key concept of development is DRY (Don't repeat yourself) code. If you need to repeat something multiple times, you can put it inside of a function and re-use it over and over. There are also many pre-written functions which come with Javascript, and more that can be added from various modules or libraries.
In this example we have two numbers which may be numbers or they may be text, we're not sure, and we want to multiply them together. We will use the parseFloat function that comes with JavaScript within our function to ensure that the inputs have been converted to numbers before we multiply them.
function multiply (number1, number2) {
return parseFloat(number1) * parseFloat(number2);
}
const areaSqFtRoom1 = multiply('50', 25);
const areaSqFtRoom2 = multiply('30', 20);
While the inputs for this function are contrived, this shows that whether we pass a string value (wrapped in ' or ") or a numerical value into the function; the multiplication can still take place.
A function consists of inputs (arguments), and a single output (returnValue). Objects which we'll discuss soon, can be used to return multiple values within the single return value. Functions may have names but we'll look at some examples where they don't have one (without names they are called anonymous functions). The block of the function is everything within the curly braces.
function functionName (arguments) {
return returnValue
}
Variables
Variables store information/data for use later in your code. Variables also allow you to re-use data within your script and they prevent you from repeating yourself.
For example, if we know that there are roughly 2.20 pounds in a kilogram, we can store that in a variable. We don't expect it to change, so we'll use a constant variable. By using a variable, we avoid repeating 2.20 everywhere in our code. If we later need to change it to a more precise 2.20462, we can do so easily.
const lbInKg = 2.20;
Note: we named this using a style called camel case in which the first word is lowercase and every following starts with an uppercase. Spaces are not allowed in variable names, so using a consistent format helps with readability
In JavaScript, you'll see three variable declarations: var, const, and let. const variabl: