Organize Code
Function
JavaScript
function greet(){
console.log("Hello!");
}
greet(); // Hello!
Function is a block of code with a specific purpose that we encapsulate and run as many times as we want.
Functions are not run by themselves, and we should invoke (call) them to execute them.
Function can optionally return something one-time using the return
keyword.
function add(a, b){
return a + b;
}
var val1 = add(2, 3); // 5
var val2 = add(3, 4); // 7
Functions may receive inputs, which are called Arguments.
var sum = function(a, b){
return a + b;
}
var val = sum(2, 3); // 5
This is another way of defining functions in JavaScript. These functions are called Anonymous or Lambda.
Here we are creating an anonymous function in the runtime and assign it to a variable sum
. From here you can call that anonymous function using variable sum
.
var sum = (a, b) => {
return a + b;
}
var val = sum(2, 3); // 5
Arrow Functions are introduced in ES6.
The only difference in this way of defining a function is, the context (this
keyword) won't change from wherever it is defined.
function sum(a, b=1){
return a + b;
}
var val1 = sum(2); // 3
var val2 = sum(2, 3); // 5
Default Arguments are arguments that have a value assigned to them by default, so whenever that argument is missing in the function call, that default value will be used.
Default Argument is introduced in ES6.
Default Arguments should be the right most arguments in the function.
function sum(a, b){
return a + b;
}
var val1 = sum(2, 3) // 5
var val2 = sum.call(this, 2, 3); // 5
var val3 = sum.apply(this, [2, 3]); // 5
There are multiple ways to call a function:
sum(2, 3)
This is the most common way of calling a function.sum.call(this, 2, 3)
This will call the functionsum
with the context of whateverthis
is referring to. You can use any object instead ofthis
in this example and when the function is being run,this
keyword inside the function will refer to that object.sum.apply(this, [2, 3]);
Same as call method, exceptapply
gets an array of values for the second parameter.
function greet1(name){
name = 'John';
console.log('Hello ' + name);
}
function greet2(obj){
obj = {name: 'John'};
console.log('Hello ' + obj.name);
}
function greet3(obj){
obj.name = 'John';
console.log('Hello ' + obj.name);
}
var name = 'Sam';
var obj = { name: 'Sam' };
greet1(name); // Hello John
console.log(name); // Sam
greet2(obj); // Hello John
console.log(obj.name);// Sam
greet3(obj); // Hello John
console.log(obj.name);// John
In JavaScript primitive values are passed by value and Objects (object, array, function) are passed by Copy of a Reference.
It is Copy of Reference because if you change a content of the object, it will change outside of the function too, but if you reassign that object to a new object, it will not take any effect outside of the function.
In this example:
greet1
parameter is passed by value.greet2
parameter is passed by copy of reference.greet3
parameter is passed by copy of rererence.