prisskreative
9/5/2014 - 3:37 AM

Functions

Functions

// Scope 
// Scope is a namespace for our variable 
// We can declare variables inside of our functions, and they have a unique property: they exist only within that function. 

var color = 'black'; // global scope
var number = 1;

function showColor () {
	var color = 'green';

	console.log('showColor color', color);
	console.log('showColor number', color);
}

showColor(); // green

     console.log('Global color', color);
     console.log('Global number', number);


// Shadowing a variable - (Don't do it)
// Creating two variables at different scopes with the same name

var color = 'black'; // global scope
var number = 1;

function showColor () {
	var color = 'green';

	number = 2; // change the global variable - overwrite

	console.log('showColor color', color);
	console.log('showColor number', color);
}

showColor(); // green

     console.log('Global color', color);
     console.log('Global number', number);
// Return Values
// the value that the function will evaluate to when called

/* Our functions can calculate values that we call the return value. The return statement not only allows us to pass the value back to the caller of our function, but also stops the execution of the function itself. */


//when you use return it will end loop or function, so the code below will not be executed


function sayHello (name, greeting){
	if (typeof greeting === 'undefined'){// if greeting equal to undefined we say hello
		greeting = "Hello";
	}
	console.log(greeting + "World" + name);

	return "Done"; // console apper done not undefined - before was undefined
}

// call a function
sayHello ("Jim", "Greetings"); 

sayHello ("Jim"); 


// Example 2

function sayHello (name, greeting){
	if (typeof greeting === 'undefined'){
		greeting = "Hello";
	}
	console.log(greeting + "World" + name);

	return name.length; 
}

// say hello will retrun a value
console.log(sayHello ("James", "Greetings")); 

console.log(sayHello ("Jim")); 


// Example 3

function sayHello (name, greeting){
	if (typeof name === 'undefined'){
		return 0; // return; = to undefined
			}
	console.log(greeting + "World" + name);

	return name.length; 
	console.log('End of function');
}

// say hello will retrun a value
console.log(sayHello ("James", "Greetings")); // 5

console.log(sayHello ("Jim")); // 3

console.log(sayHello ()); // 0 


//challenge
/* create a function named 'arraycounter' that takes in a parameter which is an array. the function must return the length of an array passed in or 0 if a 'string', 'number' or 'undefined' value is passed in. */

function arrayCounter (x){
  if (typeof x === 'undefined' || typeof x === 'string' || typeof x === 'number') {
    return 0;
  } else
    return x.length;
    }
// Functions

/* Arguments
Functions in JavaScript allow us to store code for reuse later in our programs. We can change the behavior each time we use the function by passing in data called arguments. */

//the way the browser works is it uses functions and events to actually interact with the page

// Function Names - Function name must be a valid variable name


function sayHello (){
	console.log("Hello World");
}

// call a function
sayHello (); 

// Functions are useful beacuse they can take arguments and return values

// everytime we sayHello we pass different name () - name variable that is useful inside the function


function sayHello (name, greeting){
	if (typeof greeting === 'undefined'){// if greeting equal to undefined we say hello
		greeting = "Hello";
	}
	console.log(greeting + "World" + name);
}

// call a function
sayHello ("Jim", "Greetings"); 

sayHello ("Jim"); 
// Functions are useful beacuse they can take arguments and return values
// Functions examples in the browser

// Document Object odel (DOM)
// The interface our code can use to interact with the web page
// DOM - It's the interface we have to the actual elements on our page.
/* It's how we could manipulate the contents of a div or change a style or add or remove  elements. */

// document is an object - how can get the elements out the page.

    var button = document.getElementById('action'); 
	var input = document.getElementById('text_field'); 
    
    // two argument - 1 click calling our event - 2 function that happen after event
    button.addEventListener('click', function () {
		console.log('clicked');
	});

	button.addEventListener('click', function () {
		console.log('Other click listener');
		input.setAttribute('value', 'Hello world');
	});



	/* Doesn't work in Internet Explorer - just can be one click

	button.onclick = function () {
		console.log('clicked');
	}

	button.onclick = function () {
		console.log('Other click listener');
	}
	*/
// This is what a function looks like:

var divideByThree = function (number) {
    var val = number / 3;
    console.log(val);
};

// On line 12, we call the function by name
// Here, it is called 'dividebythree'
// We tell the computer what the number input is (i.e. 6)
// The computer then runs the code inside the function!
divideByThree(12);


// ----------

var foodDemand = function (food){
    console.log("I want to eat" + " " + food);
}

foodDemand ("cheese, milk");

// -----------


var calculate = function (number) {
    var val = number * 10;
    console.log(val);
};

//--------

// Problem

// You want to declare a function that calculates the cost of buying 5 oranges.
// You then want to calculate the cost of the 5 all together.
// Write a function that does this called orangeCost().
// It should take a parameter that is the cost of an orange, and multiply it by 5.
// It should log the result of the multiplication to the console.
// Call the function where oranges each cost 5 dollars.

var orangeCost = function(cost){
  var val = cost * 5; 
  console.log(val); 
};

orangeCost(5);
/* Packaging code

Sometimes you will find the need to package some pieces of your code 
into self-contained chunks so that you can use them easily in different 
parts of your program. You can do this by writing a function. 

*/

function claimForCountry (country, thing) {
    var claim;

    claim = "In the name of " + country + " I claim this " + thing + "!";

    return claim;
}

var message;

message = claimForCountry("Spain", "land");

console.log(message);

message = claimForCountry("Italy", "pizza");

console.log(message);
function structure
function [name] ( [parameter1], [parameter2], [parameter3]... ) {
    [code]
    return [value];
}

/*
Let's break down function:

A function has a [name] that you call it by. In our example that name is claimForCountry.
When you call it you send it as many [parameters] as it needs. Parameters are just values you send the function. Our example claimForCountry needs two parameters:
country: The name of the country that is making the claim.
thing: The name of the thing that is being claimed.
Then the function runs [code] with those parameters. In our example we declare a variable and set it's value using country and thing.
Finally, after running the code it returns a [value]. In our case we return the claim variable's value.
So when you call claimForCountry it returns a string value which you can use as you see fit. You can also send it different parameters to change the message.
*/


//Variations
//The structure of function is not super strict. There are certain parts that are optional. For example, you can write a function with as many or as few parameters as you want. Try it:



// No parameters
function hi () {
    return "Hi!";
}

console.log( hi() );

// Five parameters
function addFiveNumbers (n1, n2, n3, n4, n5) {
    return n1 + n2 + n3 + n4 + n5;
}

console.log( addFiveNumbers(10, 20, 30, 5, 7) );

//Returning a value is also optional. For example we could 
//have written the hi function to use console.log directly:

// No return
function hi () {
    console.log("Hi!");
}

hi();

/*However, keep in mind that you may want to do different things with values 
besides console.log so it's often best to return.*/

// Create a function to see if a field on a web form is empty

// return true if is empty
// return false if the user enter something

// then return the form action to create another action like an alert 


// check if email is empty
function isEmailEmpty() { 
   var field = document.getElmentById('email'); //access the form field - access an element by id and store the reference in a variable
   
//test value using a conditional statement
if (field.value === ''){ //is the value equal to an empty string
   return true;
} else {
   return false;   //if it has something on it
}

// creating a variable that holds the return value from the function either true or false
var fieldTest = isEmailEmpty();
if (fieldTest === true){ // then use a conditional statement to see if is empty
   alert("Please provide your email address");
}

-----------


// Javascript return statement (return exits a function and sends a value back to the spot in the program where the function was called)

// A return statement causes the javascript interpreter to function immediately 
// the return statement should be the last in a function
// the return statement can only return a single value (string - number - boolean or a content of a variable)


function noAlert{
   return 5;
   alert("This won't appear");
}

noAlert();
alert("This will appear!");



----


function good{
   var message = "Hello";
   return message;
}

function noGood{
   var message = "Hello";
   return 1, message, 'a string'; // WRONG
}
// Create a reusable code with functions




//The basic structure of a function
function myFunction() {
  // do a bunch of stuff here
}


//Calling a function
myFunction();


//A function expression
var myFunction =  function () {
  // do stuff here
};



-----------



function alertRandom(){
	var randomNumber = Math.floor(Math.random() * 6 ) + 1;
	alert(randomNumber);
}// no semicolon


alertRandom();





// Rewrite - annonimous function (we store a function in a variable)
var alertRandom = function(){
	var randomNumber = Math.floor(Math.random() * 6 ) + 1;
	alert(randomNumber);
}; // finish with semicolon


alertRandom();



-------------


/* Functions don't just run JavaScript statements. 
They can also return values that you can use elsewhere in a program. */


// return a value (we can use the function wherever we want) 
// with alert is just an alert


function goToCoffeeShop(){
	return "Espresso is on its way.";
}

alert ( goToCoffeeShop());

// use the return value in different ways

// alert ( goToCoffeeShop());

// console.log( goToCoffeeShop());

// var coffeeStatus = goToCoffeeShop();  save in a variable



------------




// Generate a random number that return
// Add a parameter that will hold the value that is pass by the function - upper of our random number
function getRandomNumber = ( upper ){
	var randomNumber = Math.floor(Math.random() * upper ) + 1;
	return randomNumber;
}; // finish with semicolon


console.log( getRandomNumber(6) ); //calling a function and passing an argument
console.log( getRandomNumber(100) );
console.log( getRandomNumber(1000) );
console.log( getRandomNumber(2) );

------------


// Get year

function getYear (){  
  var year = new Date().getFullYear();
  return year;
}


------------


// Function can return a value - like an assist that bring coffee when I said go to the coffee shop
// but in addition you can send information to a function to change how that function works.


/* 
  everytimes I ask for the coffee I get coffee.
  but what if a want ice tea instead of coffee */

function goToCoffeeShop(){
	return "Espresso is on its way.";
}

alert ( goToCoffeeShop());


// Javascript function can also accept information 
// call an argument which you send to the function
// the argument store in a variable call the parameter that you can use inside a function

// the parameter works as a variable


function goToCoffeeShop(drink){ // drink is the parameter inside the function
	alert( drink + ' is on the way!');
}

// now this function is expecting information so when we call the function
// we pass some infomation (passing an argumnet to the function)
goToCoffeeShop('Espresso');

// goToCoffeeShop('Ice tea');
// goToCoffeeShop('chamolile');


----------

// Multiple parameters - (don't pass more than 4 or 5)

// you can add another parameter
function goToCoffeeShop(drink, pastry){ 
	alert( drink + "and" + pastry + "are on the way!");
}

goToCoffeeShop("Espresso", "croissant");


----

// Simple function
function getArea( width, length, unit ) {
  var area = width * length;
  return area + " " + unit;
}
console.log(getArea(10,20, 'sq ft'));


// Adding parameters to a function

function calculateArea( width, length ) {
  return width * length;
}

calculateArea( 5, 4 ); // 20
calculateArea( 30, 4 ); // 120



----------


/* Create a new function named max() which accepts two numbers as arguments. 
   The function should return the larger of the two numbers. 
   You'll need to use a conditional statement to test the 2 numbers to see 
   which is the larger of the two. */



function max(num1, num2) {
  if (num1 > num2) {
    return num1; 
  }
  else{
    return num2;
  }
}


alert (max(2,5));



-----------

// Function Scope


// Each variable leaves in different scope
function greeting(){ 
	var person ='Lilah';
	alert(person);
}

// Global Scope (all functions can access the global scope)
var person = 'George';
greeting();
alert(person);
greeting;


------

// A function can change the value of a variable from the global scope
// no good idea

function greeting(){ 
	person ='Lilah'; // take out the var keyword change George to Lilah
	alert(person);
}

var person = 'George';
greeting();
alert(person);
greeting;

// Always put the var keyword inside a functional when you creating a variable

-----------



var counter = 0;
function doStuff( ) {
   counter = 10;
}


----------

// the function produce random numbers between 10 and 100 - 50 and 60
// function need to accept two values lower and upper value
// formula to create a random value between two numbers
// call it and pass to values

// random number formula

function getRandomNumber(lower, upper){
	Math.floor(Math.random() * (upper - lower + 1)) + lower;
}


console.log( getRandomNumber(1, 6) ); 
console.log( getRandomNumber(1, 100) );
console.log( getRandomNumber(200, 500) );


-----------


//You can test if a JavaScript value is a number with this on the console

isNaN(9) // false

isNaN('nine') // true

// isNan = is not a number 


// Javascript let you create your own errors


if (  ||  ){
	throw new Error('error message');
}

// if the number is a string you will see the error message

function getRandomNumber(lower, upper){
	if ( isNan (lower) || isNan (upper) ){//if is a number return true if not false
	throw new Error('Both arguments must be numbers');
}
	return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}


console.log( getRandomNumber(1, "six") ); 
console.log( getRandomNumber(1, 100) );
console.log( getRandomNumber(200, "five hundred") );



// Compiling is the process of turning source code 
// into machine code. Compiled languages include C and Swift.

// Anonymous Functions
// We can declare functions without names, called anonymous functions, which are useful when we want to use a function once, or simply store it in a variable.


var myFunction = function (){
    console.log('my Function was called');
    undeclaredVariable;
};

var callTwice = function (targetFunction){
	targetFunction();
	targetFunction();
}

callTwice(myFunction(){
	console.log('Hello from anonymous function');
}); // passing the value to the variable



// example 2

function tempFunction(){
	var a, b, c;
}

tempFunction();


// example 3

(function tempFunction(){
	var a, b, c;
    //...

	console.log('from anonymous function')

})(1, 'hello')
/* Functions are a foundational concept in JavaScript. 
 Functions allow us to store code for reuse in our programs. 
 This allows us to organize our code and make it much easier 
 to maintain and write.*/
 
 
/* array and objects store data in the program - 
   function store actual functionality or behavior */

/* Functions
   A function contains a piece of code that needs to be executed several 
   times from different parts of your application. A function optionally 
   takes in arguments and returns an object or value as a result. */


//alert is a function and we pass the value and say hello = (value) - 

alert("hello");

console.log("Hello world");


//var sayHello store our function - define a function using the function keyword function(type of argument to pass)
//define behavior of the function inside {} - hello word apper several times with sayHello();

var sayHello = function() {
  console.log("Hello World")
}


sayHello();

 console.log("x has been set")

sayHello();

//with message - function help to change everything in function like php var and not in different places of the page

var sayHello = function() {
  var message = "Hello";
  message = message + " World!";
  console.log("Hello World")
}

var debug = function(message){
  console.log("Debug", message);
}

sayHello();

 debug("x has been set")

sayHello();


//function that boble the number (double no variable name because is a world use in javascript) - return 14
var doubleNumber = function(num){
  return num * 2;
} +
   
 debug(doubleNumber(7));

// example function

function printAmount() {
	console.log( amount.toFixed( 2 ) );
}

var amount = 99.99;

printAmount(); // "99.99"

amount = amount * 2;

printAmount(); // "199.98"

// example function with parameters

function printAmount(amt) {
	console.log( amt.toFixed( 2 ) );
}

function formatAmount() {
	return "$" + amount.toFixed( 2 );
}

var amount = 99.99;

printAmount( amount * 2 );		// "199.98"

amount = formatAmount();
console.log( amount );			// "$99.99"