Skip to content

Instantly share code, notes, and snippets.

@bnates
Created May 13, 2017 23:13
Show Gist options
  • Save bnates/5f4baf0b0c38840e4568d733ec4501b9 to your computer and use it in GitHub Desktop.
Save bnates/5f4baf0b0c38840e4568d733ec4501b9 to your computer and use it in GitHub Desktop.
Function and For Loop Demo
/* =============================================================
DEMO: create a function that will log all items in an array
================================================================ */
// declare our function
function logItems() {
// create an array of items
var items = ['some item', 'another item', 'final item'];
// loop through each of the items in the array
for (var i = 0; i < items.length; i++) {
// log the item name on each iteration of the loop
console.log(items[i]);
}
}
// invoke (aka "call") the function
logItems();
/* ==============================================================================
DEMO: create a function that accepts an array of integers as it's argument
the function should return a new array with each number multiplied by 2
================================================================================= */
// declare our function with a single parameter
function multiplyNums(arr) {
// declare a variable who's value is an empty array
// this empty array will be used to eventually hold our final/new array
var nums = [];
// loop through each item in our passed in array
for (var i = 0; i < arr.length; i++) {
// multiply the number by 2 on each iteration and push it to our "nums" array
nums.push(arr[i] * 2);
};
// return the new array of multiplied numbers
return nums;
}
// invoke our function and pass in an array as it's argument
multiplyNums([2, 10, 30]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment