Functions. Flashcards
what are functions?
They allow the code to be called many times without repetition.
Exampes of functions
examples of built-in functions, like alert(message), prompt(message, default) and confirm(question)
How do you create functions?
The function keyword goes first, then goes the name of the function, then a list of parameters between the parentheses (comma-separated, ) and finally the code of the function, also named “the function body”, between curly braces.
function name(parameter1, parameter2, … parameterN) {
// body
}
What are the main types of variables?
1.) Local Variables
2.) Outer Variables
Example of an Outer Variable
In this example a function is seen accessing and outer variable.
The function has full access to the outer variable. It can modify it as well.
let userName = ‘John’;
function showMessage() {
let message = ‘Hello, ‘ + userName;
alert(message);
}
showMessage(); // Hello, John
What is a global Variable?
1.) Variables declared outside of any function,
2.) Global variables are visible from any function (unless shadowed by locals).
3.) Modern code has few or no globals. Most variables reside in their functions.
How do you name Variables?
1.) Functions are actions. So their name is usually a verb. It should be brief, as accurate as possible and describe what the function does.
2.) Two independent actions usually deserve two functions, even if they are usually called together (in that case we can make a 3rd function that calls those two).
3.) It is a widespread practice to start a function with a verbal prefix which vaguely describes the action…
EXAMPLE:
"get…" – return a value, "calc…" – calculate something, "create…" – create something, "check…" – check something and return a boolean, etc.
what is function declaration?
Function Declaration: a function, declared as a separate statement, in the main code flow.
// Function Declaration
function sum(a, b) {
return a + b;
}
What is Function expression?
Function Expression: a function, created inside an expression or inside another syntax construct. Here, the function is created on the right side of the “assignment expression” =:
// Function Expression
let sum = function(a, b) {
return a + b;
};
What are function Callbacks?
Callbacks are the functions that are slipped or passed into another function to decide the invocation of that function. You may have seen them passed to other methods, for example in filter, the callback function tells JavaScript the criteria for how to filter an array.
What is a first class function?
Functions that can be assigned to a variable, passed into another function, or returned from another function just like any other normal value, are called first class functions. In JavaScript, all functions are first class functions.