📅 September 14, 2018
•⏱️9 min read
The Web Developer Bootcamp - Udemy
Intro to Functions by Colt Steele
Functions let us wrap bits of code up into REUSABLE packages. They are one of the building blocks of JS.
function doSomething() {
console.log("HELLO WORLD");
}• Declare a function first. • Then call it.
Often we want to write functions that take inputs.
function square(num) {
console.log(num * num);
}모든 함수는 반환을 한다.
//this function capitalizes the first char in a string:
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
var city = "paris"; //"paris"
var capital = capitalize(city); //"Paris"
//we can capture the returned value in a variablefunction isEven(num){
return num % 2 === 0;
}
function factorial(num){
//define a result variable
var result = 1;
//calculate factorial and store value in result
for(var i = 2; i <= num; i++){
result *= i;
}
//return the result variable
return result;
}
function kebabToSnake(str) {
//replace all '-' with "_"'s
var newStr = str.replace(/-/g , "_");
//return str
return newStr;
}function sing() {
console.log("twinkle twinkle...");
console.log("how i wonder...");
}
setInterval(sing, 1000);
clearInterval(2);
setInterval(function() {
console.log("I am an anonymous function!");
console.log("THIS IS AWESONE!");
}, 2000);Push Use push to add to the end of an array:
var colors = ["red", "orange", "yellow"];
colors.push("green");
//["red", "orange", "yellow", "green"]Pop Use pop to remove the last item in an array
var colors = ["red", "orange", "yellow"];
colors.pop();
//["red", "orange"]
//pop() returns the removed element
var col = colors.pop(); //orangeUnshift Use unshift to add to the front of an array
var colors = ["red", "orange", "yellow"];
colors.unshift("infrared")
//["infrared", "red", "orange", "yellow"]Shift Use shift to remove the first item in an array
var colors = ["red", "orange", "yellow"];
colors.shift();
//["orange", "yellow"]
//shift() also returns the removed element
var col = colors.shift(); //orangeIndexOf Use indexOf() to find the index of an item in an array
var friends = ["Charlie", "Liz", "David", "Mattias", "Liz"];
//returns the first index at which a given element can be found
friends.indexOf("David"); //2
friends.indexOf("Liz"); //1, not 4
//returns -1 if the element is not present.
friends.indexOf("Hagrid"); //-1Slice Use slice() to copy parts of an array
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
//use slice to copy the 2nd and 3d fruits
//specify index where the new array starts(1) and ends(3)
var citrus = fruits.slice(1, 3);
//this does not alter the original fruits array
//citrus contains ['Orange','Lemon']
//fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
//you can also use slice() to copy an entire array
var nums = [1,2,3];
var otherNums = nums.slice();
//both arrays are [1,2,3]2 Dimensional Array
var friendGroups = [
["Harry", "Ron", "Hermione"],
["Malfoy", "Crabbe", "Goyle"],
["Mooney", "Wormtail", "Prongs"]
];
//What is the result of this line:
console.log(friendGroups[2][0]); // Mooney
console.log(friendGroups[2]); // ["Mooney", "Wormtail", "Prongs"]Simple todo list app list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="list.js"></script>
</head>
<body>
<h1>Todo List</h1>
<ul>
<li>"new" - Add A Todo</li>
<li>"list" - List All todos</li>
<li>"quit" - Quit App</li>
</ul>
</body>
</html>list.js
var todos = ["Buy new turtle"];
var input = prompt("What would you like to do?");
while(input !== "quit"){
// handle input
if(input === "list") {
todos.forEach(function(todo){
console.log(todos);
});
} else if(input === "new") {
// ask for new todo
var newTodo = prompt("Enter new todo");
// add to todos array
todos.push(newTodo);
}
// ask again for new input
input = prompt("What would you like to do?")
}
console.log("ok you quit the app")For Loop To loop over an array using a for loop, we need to make use of the array's length property
var colors = ["red", "orange", "yellow", "green"];
for(var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
//red
//orange
//yellow
//greenForEach
JavaScript provides an easy built-in way of iterating over an array: ForEach
arr.forEach(someFunction)
var colors = ["red", "orange","yellow", "green"];
colors.forEach(function(color){
//color is a placeholder, call it whatever you want
console.log(color);
});
//red
//orange
//yellow
//green
colors.forEach(function(iLoveDogs) {
console.log("INSIDE THE FOREACH " + iLoveDogs);
});
//INSIDE THE FOREACH red
//INSIDE THE FOREACH orange
//INSIDE THE FOREACH yellow
//INSIDE THE FOREACH greenExercise
var numbers = [1,2,3,4,5,6,7,8,9,10];
numbers.forEach(function(color){
if(color % 3 === 0) {
console.log(color);
}
});
//3
//6
//9Exercise2
[1,2,3].forEach(function(el, i, arr) {
console.log(el, i, arr);
});
// 1 0 [1, 2, 3]
// 2 1 [1, 2, 3]
// 3 2 [1, 2, 3]Q. I am wondering exactly how that function works..
list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="list.js"></script>
</head>
<body>
<h1>Todo List</h1>
<ul>
<li>"new" - Add A Todo</li>
<li>"list" - List All todos</li>
<li>"delete" - Remove a Specific Todo</li>
<li>"quit" - Quit App</li>
</ul>
</body>
</html>list.js
var todos = ["Buy New Turtle"];
var input = prompt("What would you like to do?");
while(input !== "quit"){
//handle input
if(input === "list") {
printList();
} else if(input === "new") {
addTodo();
} else if(input === "delete") {
deleteTodo();
}
//ask again for new input
input = prompt("What would you like to do?");
}
console.log("OK, YOU QUIT THE APP");
function printList() {
console.log("**********");
todos.forEach(function(todo, index){
console.log(index + ": " + todo);
});
console.log("**********");
}
function addTodo(){
//ask for new todo
var newTodo = prompt("Enter new todo");
//add to todos array
todos.push(newTodo);
console.log(newTodo + " added to list")
}
function deleteTodo(){
var index = prompt("Enter index of todo to delete");
todos.splice(index, 1);
console.log("Todo Removed")
}Write a function printReverse() that takes an array as an argument and prints out the elements in the array in reverse order (don't actually revese the array itself.
printReverse - My solution
let arr = [1, 2, 3, 4];
let arr2 = ["a", "b", "c"];
function printReverse(array) {
if (array === undefined || array.length === 0) {
// array empty or does not exist
console.log("This array is empty!");
return;
}
for(var i = array.length; i >= 0 ; i--) {
console.log(array[i]);
}
}
printReverse(arr);
//4
//3
//2
//1
printReverse(arr2);
//c
//b
//aprintReverse - Colt Steele
function printReverse(arr){
for(var i = arr.length - 1; i >= 0; i--){
console.log(arr[i]);
}
}
printReverse([3,6,2,5]);
//5
//2
//6
//3Write a function isUniform() which takes an array as an argument and return true if all elements in the array are identical.
isUniform - My solution
let arr = [1, 1, 1, 1];
let arr2 = [2, 1, 1, 1];
let arr3 = ["a", "b", "c"];
let arr4 = ["b", "b", "b"];
function isUniform(array) {
if (array === undefined || array.length === 0) {
// array empty or does not exist
console.log("This array is empty!");
return;
}
let temp = array[0];
for(let i = 1; i < array.length; i++) {
if(temp !== array[i]){
console.log("false");
return;
}
}
console.log("true");
}
isUniform(arr); //true
isUniform(arr2); //false
isUniform(arr3); //false
isUniform(arr4); //trueisUniform - Colt Steele
function isUniform(arr){
var first = arr[0];
for(var i = 1; i < arr.length; i++){
if(arr[i] !== first){
return false;
}
}
return true;
}Write a function sumArray() that accept an array of numbers and return the sum of all numbers in the array.
sumArray - My solution
let arr = [1, 2, 3];
let arr2 = [10, 3, 10, 4];
let arr3 = [-5, 100];
function sumArray(array) {
if (array === undefined || array.length === 0) {
// array empty or does not exist
console.log("This array is empty!");
return;
}
let result = 0;
for(let i = 0; i < array.length; i++) {
result += array[i];
}
console.log(result);
}
sumArray(arr); //6
sumArray(arr2); //27
sumArray(arr3); //95sumArray - Colt Steele
function sumArray(arr){
var total = 0;
arr.forEach(function(element){
total += element;
});
return total;
}Write a function max() that accepts an array of numbers and returns the maximum number in the array.
max - My solution
let arr = [1, 2, 3];
let arr2 = [10, 3, 10, 4];
let arr3 = [-5, 100];
function max(array) {
if (array === undefined || array.length === 0) {
// array empty or does not exist
console.log("This array is empty!");
return;
}
if(array.length === 1) {
console.log(array[0]);
} else {
let result = array[0];
for(let i = 1; i < array.length; i++) {
if(array[i] > result) {
result = array[i];
}
}
console.log(result);
}
}
max(arr); //3
max(arr2); //10
max(arr3); //100max - Colt Steele
function max(arr){
var max = arr[0];
for(var i = 1; i < arr.length; i++){
if(arr[i] > max){
max = arr[i];
}
}
return max;
}let colors = ["red", "orange", "yellow"];
function myForEach(arr, func) {
// loop through array
for(var i = 0; i < arr.length; i++) {
// call func for each item in array
func(arr[i]);
}
}
myForEach(colors, function() {alert("Hi")});
myForEach(colors, function(color) {console.log(color)});
//red
//orange
//yellowArray.prototype.myForEach = function (func) {
for(let i = 0; i < this.length; i++) {
func(this[i]);
}
};
let friends = ["charlie", "dave", "maddy", "caitlin"];
friends.myForEach(function (name) {
console.log("I love " + name);
});
//I love charlie
//I love dave
//I love maddy
//I love caitlin