Functions

JavaScript

0 Comments

The code shown below creates a new function called addNumbers. This function is very simple. It takes two numbers as input, adds them together, and returns the result.

function addNumbers(num1, num2) {
    /* Create a new variable called result */
    var result;

    result = num1 + num2;

    return result;
}
  • Notice that each line of JavaScript code ends with a semi-colon (;).

Function parameters

Function parameters give you a way to pass information to a function. In our example, our function accepts 2 parameters called num1 and num2. You can name your parameters anything you want. In the rest of the function, you can use the parameter name to access the value that was passed into the function.

Variables

In Line 3, we created a new variable called result. A variable is basically a bucket for you to store some value in. You can name your variables whatever you'd like.

Variables are created by putting the var keyword in front of the variable name. Once the variable is created, you can refer to its name in the rest of your code. In Line 5, we store a value in our new result variable.

Variables can hold many different types of values

  • Numbers
  • Strings (text) - Strings should be wrapped in single or double quotes. For example, 'Name' or "Last name".
  • Boolean values (true or false)
  • And more advanced types that you'll learn later

Running the function

var theResult = addNumbers(5, 3);

This code runs our addNumbers function and passes it the numbers 5 and 3. The function adds the numbers together and returns the value 8, which is stored in a new variable called theResult.

Why are functions useful?

You'll sometimes need to run the same code multiple times. Functions save you from having to copy and paste this code in multiple places, which you should never do when programming.

Functions also allow you to break up your code into smaller pieces. Each function could be responsible for a specific part of the problem. This makes your code a lot easier to understand.

Leave a Comment