Lesson 8: Functions: Basics
Functions
Functions can contain loops, arrays, and can also be passed parameters. A function runs only when it called and can be called multiple times with different parameters. Functions can return data as a result.
Defining Functions
- Functions are defined in JavaScript using the function keyword.
- After declaring the function keyword, you must define a function name, followed by parentheses () and braces containing the code for the function.
Example:
function myName is () {
console.log("Hello,World");
}
Hello,World
Example 2:
function myFunction () {
console.log ("I Love JavaScript")
}
I Love JavaScript
Functions with a parameter/argument
- Arguments are values that can be passed through a function. Parameter is another term used instead of argument. They are the same thing.
- When a function is being created, the arguments/parameters are defined inside the brackets, also known as parentheses, which are found after the function name.
Example:
function myFunction(myName){
console.log ("My name is" + myName)
}
How to call a function?
- Use the function name followed by parentheses to call a function.
- When passing parameters/arguments through a function, you must pass the correct number of parameters back.
- In the example above, we are passing one parameter (myName) through the function so the function will return only one parameter.
Example:
myFunction("Kevin")
}
My name is Kevin
Multiple Parameters
Example:
function myFruit (firstFruit,secondFruit){
console.log ("My favourite fruits are "+ firstFruit + "&" + secondFruit)
myFruit ("Apple", "Orange")
}
My favourite fruits are Apple & Orange
In the example above, the function takes two arguments, “firstFruit” and “secondFruit”. When the function is called, you must pass a value for each of the two parameters listed in the function above.
Further Reading