Functions
Definition: Functions are just recipes. To use declare function followed by function name and parenthesis and braces. Lines within a function ends in semicolons.
Syntax:// function syntax – runs code with no options
function functionName() {
// code here
}
Functions with Parameters
Parameter – Values inside the () when creating a function are called parameters.
Arguments – Values inside the () when running a function are called arguments.
Syntax:// function syntax – runs code with parameter with argument
function functionName(parameter) {
// code here
}
// run function
functionName(argument)
Customizing Functions
A variable or ‘string’ can be added to a function inside the (). This makes a function customizable.
Example:
function sayHiTo(person) {
console.log(‘hi’, person);
}
//run function
sayHiTo(‘gordon’) // person = ‘gordon’
= hi gordon
Functions Inside Functions
var todos = [‘item 1’, ‘item 2’, ‘item 3’]
function displayTodos() {
console.log(todos);
}
function addTodo(todo) {
todos.push(todo);
displayTodos();
}
Functions with Multiple Parameters
Example:
function changeTodo(position, newValue) {
todos[position] = newValue;
displayTodos();
}
Javascript Comments
Create a comment by writing // at the beginning of the line
Complete code for Todo List
var todos = [‘item 1’, ‘item 2’, ‘item 3’];
// It should have a function to display todos
function displayTodods () {
console.log(‘My Todos:’, todos);
}
//It should have a function to add todos
function addTodo(todo) {
todos.push(todo);
displayTodos();
}
//It should have a function to change todos
function changeTodo(position, newValue) {
todos[position] = newValue;
displayTodos();
}
//It should have a function to delete todos
function deleteTodo(position) {
todos.splice(position, 1);
displayTodos();
}
Variable Scope in Functions
If you’re inside a function, you can look out and see data, but the opposite isn’t true. If you’re outside, you can’t look in
Example
var myName = ‘Gordon’;
function sayName() {
var secret = ‘watchandcode’;
console.log(myName)
}
sayName(); // ‘Gordon’
console.log(secret); // error – can’t see variable inside function
Checking Your Code with Circles & Arrows
Draw circles around each function. Draw arrows from where the variable is being called to where it is declared. The only rule is arrows can’t enter circles, only exit. Any arrow trying to enter a circle is trying to read variable data that is out of its scope.