Professional Documents
Culture Documents
JS Functions
JS Functions
JS Functions
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
// code to be executed
}
Why Functions?
You can reuse code: Define the code once, and use
it many times.
A function expression associates a value with a variable, just like any other
assignment statement. function expressions load only when the interpreter
reaches the definition of the function.
};
console.log(getRectArea(3, 4));
Function Declaration
Function Declaration is the traditional way to define a function. It is somehow
similar to the way we define a function in other programming languages. We start
declaring using the keyword “function”. Then we write the function name and then
parameters.
// Function declaration
function add(a, b) {
console.log(a + b);
}
// Calling a function
add(2, 3);
Anonymous Function
Anonymous Function is a function that does not have any name associated
with it. Normally we use the function keyword before the function name to
define a function in JavaScript, however, in anonymous functions in
JavaScript, we use only the function keyword without the function name.
(function (){
// logic
})
let show = function() {
console.log('Anonymous function');
};
show();
Arrow Functions
Arrow functions are been introduced in the ES6 version of JavaScript. It is used to
shorten the code. Here we do not use the “function” keyword and use the arrow
symbol.
Furthermore, if the function body has only one statement that it returns, we can
skip curly braces {} and the return statement:
let name_of_function = (parameters) => ...
console.log(add(3, 2));
Map
The map() method is used for creating a new array from an existing one,
applying a function to each one of the elements of the first array.
console.log(doubled); // [2, 4, 6, 8]
Filter
The filter() method takes each element in an array and it applies a
conditional statement against it. If this conditional returns true, the
element gets pushed to the output array. If the condition returns
false, the element does not get pushed to the output array.
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(item => item % 2 ===
0);
console.log(evens); // [2, 4]
const students = [
];