Introduction To Functions in JavaScript
Agenda:
- Review
- Learning Objectives
- Learn Functions!
- Introduction to functions
- Exercise
Review
- Data Types (arrays, bools, etc)
- Control Flow (if/else/for/while)
Learning Objectives
- Define A Function
- Write A Function
- Invoke A Function
What Is a Function
Functions
- Are encapsulated (self-contained)
- Have scope
- Can be invoked
Lets Write A Function
function helloWorld() {
console.log( 'Hello World!' )
}
Invoking A Function
// define the function
function helloWorld() {
console.log( 'Hello World!' )
}
helloWorld() // invoke the function
// => 'Hello World'
Function Parameters
Parameters allow functions to become more reusable
// name is a parameter
function helloPerson( name ) {
console.log( 'Hello ' + name + '!' )
}
helloPerson('Ramsay')
// => 'Hello Ramsay'
// Lets use some numbers because Math!
var startingNumber = 1
function doubleNumber( number ) {
return number * 2
}
doubleNumber(startingNumber)
// => 2
doubleNumber(10)
// => 20
Returning Values From Functions
Returning Values From Functions
Side Effects vs Output
Side Effect
var num = 10
function multiplyNumber( multiple ) {
num *= multiple;
}
multiplyNumber( 5 )
// => num = 50
multiplyNumber( 2 )
// => num = 100
Output
var num = 10
function multiplyNumber( multiple ) {
num *= multiple;
}
multiplyNumber( 5 )
// => num = 50
multiplyNumber( 2 )
// => num = 100
Introduction To Functions in JavaScript
By Ramsay Lanier
Introduction To Functions in JavaScript
- 895