Functions Flashcards
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(array) { if (typeof array === "string" || typeof array === "number" || typeof array === "undefined"){ return 0; } else { return array.length; } };
var x = 1; var y = 1;
function hypotenuse(a , b) { var cSquared = a * a + b * b; x = Math.sqrt(cSquared); return x; }
hypotenuse(x, y);
When the ‘hypotenuse’ function is called the value of ‘x’ changes from 1. Fix it so that ‘x’ is still 1 in the global scope.
var x = 1; var y = 1;
function hypotenuse(a , b) { var cSquared = a * a + b * b; var x = Math.sqrt(cSquared); return x; }
hypotenuse(x, y);
var anonymousFunction;
Set the variable ‘anonymousFunction’ to be an anonymous function without any code to be executed.
var anonymousFunction = function(){};
(function () {
window.didExecute = true;
});
Make the anonymous function with the code ‘window.didExecute = true’ execute.
(function () {
window.didExecute = true;
})();
Aside from providing the return value to the code that called the function, what other behavior does return have that is useful?
it stops execution of the function immediately
In the following code, what will be output by the console.log call?
function example ( ) { var color = "red"; return color; }
example(“blue”);
console.log(color);
An error is thrown, color is not defined
Given the following code snippet, what are the values of a and b inside of the function when it is called?
function example (a, b) { console.log("a === ", a, " , b === ", b); }
example(“Treehouse”);
a === “Treehouse”, b === undefined
When the return statement is called without a value, what is the value returned from the function?
undefined
Why are functions so important, especially in the browser?
it allows you to attach code to be executed when events like clicks and key-presses happen
What is an anonymous function?
it is a function declared without a name that can be stored in a variable, passed as a value, or invoked immediately
In the following code, what value will be printed to the console?
var animal = “cow”;
function display (animal) { console.log(animal) }
animal = “pig”
display(“horse”);
“horse”
What happens when a function is called with fewer arguments than are defined in the function?
any remaining arguments hold the value undefined
Why is it a common pattern to execute anonymous functions immediately in your program?
functions provide a new variable scope, so variables can be used privately and without collisions