Javascript-functions Flashcards
What is a function in JavaScript?
The benefits of even the most basic functions include:
packing up code for reuse throughout a program
giving a name to a handful of code statements to make it code easier to read
making code “dynamic”, meaning that it can be written once to handle many (or even infinite!) situations
Describe the parts of a function definition.
The function keyword to begin the creation of a new function.
An optional name. (Our function’s name is sayHello.)
A comma-separated list of zero or more parameters, surrounded by () parentheses. (Our sayHello function doesn’t have any parameters.)
The start of the function’s code block, as indicated by an { opening curly brace.
An optional return statement. (Our sayHello function doesn’t have a return statement.)
The end of the function’s code block, as indicated by a } closing curly brace.
Describe the parts of a function call.
The function’s name. Again, our function’s name is sayHello.
A comma-separated list of zero or more arguments surrounded by () parentheses.
Our sayHello function does not take any arguments.
When comparing them side-by-side, what are the differences between a function call and a function definition?
// defining the sayHello function function sayHello() { var greeting = 'Hello, World!'; console.log(greeting); }
// calling the sayHello function sayHello();
What is the difference between a parameter and an argument?
The key thing to remember about parameters and arguments is that when we define a function, we declare parameters and that when we call a function, we pass it arguments. Let’s look at our definition and call side-by-side.
Why are function parameters useful?
You can think of a parameter as a placeholder. It is basically a variable whose value is not known until we call the function and pass an argument. When the function’s code block is run, the parameter is will be holding the value of the argument. Here’s an example of passing the string “friend” as an argument to sayHello
What two effects does a return statement have on the behavior of a function?
Causes the function to produce a value we can use in our program.
Prevents any more code in the function’s code block from being run.