Introduction to Functions
November 8, 2019 Leave a comment
Functions cannot be overloaded in JS: Function defined with n arguments can be passed with n args where extra args will be ignored.
function foo() {
return "Hello World";
}
foo();
Functions can be created as
- Function Expression
- Anonymous Function Expression
- Functions as arguments
- Functions on objects
1. Function Expression
Functions as values (FIRST CLASS CITIZENS)
var myFunc = function foo() {
return "Hello World";
}
myFunc();
2. Anonymous Function Expression
In the below expression function name is not required as we call with assigned variable anyways which is aka AFE
var myFunc = function() {
return "Hello World";
}
myFunc();
3. Functions as Arguments
var myFunc = function() {
return "Hello World";
}
var executorFunc = function(fn) {
fn();
}
executorFunc(myFunc);
4. Functions on Objects
var myObj = {
"prop1": true
}
myObj.myFunc = function() {
console.log("Hello World");
}
console.log(myObj);
myObj.myFunc();
Default Function Arguments
‘arguments’: is an indexed object with list of arguments passed to method
‘this’: Understanding ‘this’ keyword in JS
var person = {
"firstName": "Niranjan",
"lastName": "Tallapalli",
"getFullName": function() {
console.log(person.firstName + ' ' + person.lastName);
}
}
person.getFullName(); // would work fine BUT
// imagine this scenario
var person2 = person; // object address is copied
person = {};
person2.getFullName(); // this would have person reference which is empty hence results in “undefined undefined”
// instead refer to the object on which getFullName is invoked which is done via “this” keyword
Note: *** Functions are objects behind the scenes in JS ***
Array functions
myArr.push(element); // will add element at the end of an array
myArr.pop(); // will remove last element from array
myArr.shift(); // removes element from beginning of array
myArr.unshift(element); // push element at the beginning of array
myArr.forEach(function(item, index, arr) {
console.log(item +' '+index);
})
Recent Comments