JS 2: Functions (CodeAcademy)

Unlock all answers in this set

Unlock answers
question
...
answer
1. Introducuction to Functions in JS
question
functions store blocks of code that you can later call at any time to avoid repetition in your program. e.g. every time you want a cake, you just give ingredients to the function and it makes one! the instructions the function follows are the same every time, but how the cake turns out depends on the ingredients you give to it. input/ingredient > instructions/baking > output / type of cake
answer
function / method / routine
question
example of function definition: var divideByThree = function(number) { var val = number / 3; console.log(val); }; explanation of example: line 1: declares the function var: return value or what is given back by the function e.g. flavor of cake you get back divideByThree: function name e.g. a title for the list of cake instructions. function: keyword that tells computer you're making a function and not something else e.g. stating that this is a list of instructions for making the cake and not something else (number): parameters are names in the parentheses that are used as *placeholders* for specific ingredients we give to the function when it is actually called. the placeholders are parameters in the function definition. The specific ingredients are the arguments in the function called that get passed to the parameters. The computer looks for these when executing the instructions. e.g. parameters the *general* name for ingredients needed/used to make the cake--when the function is called, these general ingredients (or parameters) get replaced with specific ingredients (or arguments.) *be sure to make parameter names general so that the function makes sense for a variety of applications and not just one specific task { var val = number / 3; console.log(val); }; : The code that is repeated every time the function is called e.g. these are the baking instructions that are carried out each time you call/say the function name and give it the specific ingredients/arguments ; : the syntax used after the closing brace to end the repeatable set of instructions in the function e.g. the period/conclusion that says that this is the end of the recipe
answer
parts of a function definition
question
unlike many other languages (like Java), JS does not require you to state the return type of a parameter when defining a function. If a value is passed to a function's parameter that does not match the parameters intended use, strange behavior can occur. e.g., a string parameter passed into a function that cubes that parameter will return NaN which stands for \"not a number\"
answer
parameters in JS
question
divideByThree(13); this is how you tell the computer to execute the reusable code block from the function definition. The part in parentheses is the argument for the placeholder/parameter in the function definition. e.g. tells the cake-maker to bake using its reusable instructions with the specific ingredients/arguments you have given to it.
answer
function call
question
you can join strings, variables, and other strings together to print out to the screen using console.log e.g. var greeting = \"Hello\"; var name = \"Sally\"; console.log(greeting + \", \" + name); this will print out \"Hello, Sally\"
answer
console.log - joining strings
question
Proper spacing in code makes it more readable. Readability helps with writing, reading, and especially debugging your code. Good spacing has properly dropped lines and indentation when appropriate. The computer does not care about spacing, but it will make it easier for you and those you collaborate with. e.g. of good spacing: var divideByThree = function(number) { var val = number / 3; console.log(val); }; e.g. of bad spacing: var divideByThree = function(number){var val = number / 3;console.log(val);};
answer
spacing
question
debugging can fall into basically two categories: syntax errors: using the wrong programming keywords, spelling, and punctuation, ect. logical errors: the code has no syntax errors and the program will run, but behaves unexpectedly.
answer
debugging: syntax vs. logical
question
...
answer
2. Functions and Return
question
Don't Repeate Yourself a principle in programming that states you should never rewrite the same code. instead use/create a function if you find yourself retyping something and just manipulate the function's parameters instead.
answer
D.R.Y.
question
used in a function definition to stop the function from running and cause the function to return a value to its outter function. returning a value from the function you are calling is useful for when you want to give information to the outter function (e.g. the main program). i.e. instead of using a function to just print to the screen, a function is useful for giving information back to where it was called from.
answer
keyword: return
question
1. return value of a variable that was declared in the function 2. return a parameter of the function 3. perform mathematical operation on a parameter and return the result 4. if a parameter is a string, use .length or .substring() to return the result e.g. for 1-4 function definition for examples: var divideByThree = function(number,string) { var val = number / 3; console.log(val); //1. //return val; //2. //return number; //3. //return number*3; //4. //return string.length; };
answer
four ways the return keyword can be used. four examples on returning a value from a function.
question
example of a function returning a string and that string being used with console.log to print to the screen: var isEven = function(number) { var oddOrEven=number%2; if(oddOrEven===0) return \"even\"; else return \"odd\"; }; var number=4534; console.log(\"The number \"+number+\" is \"+isEven(number)); The output would be: The number 4534 is even
answer
returned values can be used like any other values (e.g. number, variables, strings, bools, ect.)
question
...
answer
3. Functions and Variables
question
you can create a function that uses multiple parameters and returns values using them e.g. var perimeterBox = function(length,width) { return length*2+width*2; }; perimeterBox(3,4); output:14
answer
using multiple parameters in functions
question
describes which part of the program a given variable is accessible. local variable: accessible only in the function definition that it is defined in global variable: accessible anywhere in the program including any given function definition (except for function definitions that contain a local variable that is defined with the same name as that global variable)
answer
scope (variables)
question
var multiplied=5; var timesTwo = function(number) { var multiplied = number * 2; }; timesTwo(4); console.log(multiplied); output: 5 the output is 5 (and not 8) because console.log is printing out the variable, multiplied, that was defined globally-- not the one that was defined inside the function definition (which is a local variable). if the function definition were written such that only the global variable, multiplied, was used inside the function definition and no local variable was defined like this, var multiplied=5; var timesTwo = function(number) { multiplied = number * 2; }; timesTwo(4); console.log(multiplied); then the output would have been 8 since the function is referring to the global variable and not a locally defined variable.
answer
scope e.g.
question
when a global variable is used inside a function definition instead of defining a local variable, then the global variable's contents can be changed. this is something you generally want to avoid by defining a local variable.
answer
side effects
question
...
answer
Paper, Rock, Scissors Project
question
Javascript has a built in function, Math.random(), that is equal to a number between 0 and 1 (including decimal places); e.g. of application - heads or tales var coinFlip=Math.random(); if(coinFlip=.5) console.log(\"heads\"); *the = covers 50 to 100 because of the 0 being counted as a possibility, both have an equal probability of being true.
answer
Math.random()
question
if the first condition (the if statement) is met, then all remaining conditionals are skipped and the if statement's block is executed. If its condition is not met, the else if statement directly after it is tested. if the else if conditional is met, then all remaining conditionals are skipped and the block is executed. if it is not met, then the program continues to check the next else if statement and so on until a condition is met. if no conditions are met after testing the if statement and all of the else if statements, then the program will falls through and does not execute any of them. if there is an else statement tacked on at the end of if / else if conditionals and all conditions were tested as false false, then the else statement will execute its block. e.g. if(x==y) console.log(\"x equals y\"); else if(x==z) console.log(\"x equals z\"); else console.log(\"x does not equal y or z\");
answer
if / else if / else
question
sometimes it is necessary to test for conditions inside a block of code that is already a conditional statement e.g. if(choice1==\"rock\") { if(choice2==\"scissors\") { return \"rock wins\" } else { return \"paper wins\"; } }
answer
nested if statements
question
typeof() is a function that returns the returns the data type of its argument. e.g. var cube = function (x) { if (typeof(x) != 'number') return 0; return x * x * x; } this function definition safe guards against passing non-numerical arguments to the x parameter by returning 0 if the the argument is not a number.
answer
typeof()
Get an explanation on any task
Get unstuck with the help of our AI assistant in seconds
New