A method is a ultimately the same as a function in that it is a block of code that performs an action. The difference between a method and a function is that a method is a property of an object that performs actions on that object. Invoking a function and calling a method are a little different. For a function, you only need the function name and parenthesis. For a method, we need to identify where the method is located first, then invoke the function from there.
It looks like this:
nameOfObject.methodName()
There are many methods included with JavaScript's automatically built objects. All of these methods can be found here → . Before jumping into that big list, below are a few methods that deserve the spotlight. These are probably the more commonly used utilities.
Array Methods
const arr = [1, 2, 3, 4, 5];
arr.forEach(item => {
console.log(item); // output: 1 2 3 4 5
});
const arr = [1, 2, 3, 4, 5];
arr.includes(2); // output: true
arr.includes(7); // output: false
const arr = [1, 2, 3, 4, 5, 6];
// item(s) greater than 3
const filtered = arr.filter(num => num > 3);
console.log(filtered); // output: [4, 5, 6]
console.log(arr); // output: [1, 2, 3, 4, 5, 6]
const arr = [1, 2, 3, 4, 5, 6, 7];
// add one to every element
const oneAdded = arr.map(num => num + 1);
console.log(oneAdded); // output [2, 3, 4, 5, 6, 7, 8]
console.log(arr); // output: [1, 2, 3, 4, 5, 6, 7]
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((total, value) => total + value, 0);
console.log(sum); // 15
const arr = [1, 2, 3, 4, 5];
// at least one element is greater than 4?
const largeNum = arr.some(num => num > 4);
console.log(largeNum); // output: true
// at least one element is less than or equal to 0?
const smallNum = arr.some(num => num <= 0);
console.log(smallNum); // output: false
const arr = [1, 2, 3, 4, 5];
// all elements are greater than 4
const greaterFour = arr.every(num => num > 4);
console.log(greaterFour); // output: false
// all elements are less than 10
const lessTen = arr.every(num => num <= 10);
console.log(lessTen); // output: true
const arr = [1, 2, 3, 4, 5];
const alpha = ['e', 'a', 'c', 'u', 'y'];
// sort in descending order
descOrder = arr.sort((a, b) => a > b ? -1 : 1);
console.log(descOrder); // output: [5, 4, 3, 2, 1]
// sort in ascending order
ascOrder = alpha.sort((a, b) => a > b ? 1 : -1);
console.log(ascOrder); // output: ['a', 'c', 'e', 'u', 'y']
const aString= 'Text String.';
const aStringArray = Array.from(aString);
console.log(aString); // output: Text String.
console.log(aStringArray ); // output: ["T", "e", "x", "t", " ", "S", "t", "r", "i", "n", "g", "."]
const numberArray= Array.of(1, 2, 3, 4, 5);
console.log(numberArray); // output: [1, 2, 3, 4, 5]
const array1=[1,2,3,'A','String','put','together'];
const string7=array1.join(':'); // 1:2:3:A:String:put:together
const string7=array1.join(' - '); // 1 / 2 / 3 / A / String / put / together
String Methods
const aString = "HELLO! I AM EXCITED!!!";
aString.toLowerCase(); // "hello! i am excited!!!"
const aString = "hello. i am excited";
aString.toUpperCase(); // "HELLO. I AM EXCITED"
const aString = "John Smith, Jane Rider, Phyllis Sizlak, Franz Feldman";
const aNewArray = aString.split(','); // "["John Smith", " Jane Rider", " Phyllis Sizlak", " Franz Feldman"]
const str = 'Basketball is fun';
console.log(str.startsWith('Football')); // false
console.log(str.startsWith('Basketball')); // true
// You can chnage the position from the default 0
// to a new starting position.
console.log(str.startsWith('fun', 14)); // true
const str = 'Actually, baseball is more my thing';
console.log(str.includes('football')); // false
console.log(str.includes('baseball')); // true
console.log(str.includes(' ')); // true
const str = 'Actually, baseball is more my thing';
console.log(str.slice()); // 'Actually, baseball is more my thing'
// start at index 9
console.log(str.slice(9)); // 'baseball is more my thing'
// end at index 14(this last character will not be included)
console.log(str.slice(3, 14)); // 'ually, base'
const str = 'Dev work is fun!';
console.log(str.charAt()); // 'D'
console.log(str.charAt(3)); // ' '
console.log(str.charAt(14)); // 'N'
const str = 'Dev work is fun! ';
console.log(str.replace('Dev', 'Web')); // 'Web work is fun!'
// Showing case sensitivity
console.log(str.replace('dav', 'Web')); // 'Dev work is fun!'
// To ignore case, use a regex
console.log(str.replace(/dev/i, 'Web')); // 'Web work is fun!'
const str2 = 'Dev work is fun! Dev life is pretty cool';
// Only the first match is replcaed
console.log(str2.replace('Dev', 'Web')); // 'Web work is fun! Dev life is pretty cool'
// A regex can replace ALL instances
console.log(str2.replace(/Dev/g, 'Web')); // 'Web work is fun! Web life is pretty cool'
const str = 'Dev Life';
console.log(str.repeat(1)); // 'Dev Life'
console.log(str.repeat(3)); // 'Dev LifeDev LifeDev Life'
const str = 'Dev work is fun! Dev life is pretty cool!';
console.log(str.substring(0, 16)); // 'Dev work is fun!'
console.log(str.substring(17)); // 'Dev life is pretty cool!'
const str = '177';
console.log(typeof str); // string
console.log(typeof parseInt(str)); // number
const str = '177.32';
console.log(typeof str); // string
console.log(parseFloat(str)); // 177.32
console.log(typeof parseFloat(str)); // number
Number Methods
const nbr = 101;
console.log(typeof nbr); // number
console.log(typeof nbr.toString()); // string
const bool = true;
console.log(typeof bool); // boolean
console.log(typeof bool.toString()); // string
var nmbr = 99.74321223;
console.log(nmbr.toFixed(0)); // returns 10
console.log(nmbr.toFixed(2)); // returns 99.74
console.log(nmbr.toFixed(7)); // returns 99.7432122
var nmbr = 99.7;
console.log(nmbr.toPrecision(1)); // returns 100
console.log(nmbr.toPrecision(3)); // returns 99.7
console.log(nmbr.toPrecision(7)); // returns 99.70000
Function Methods
firstFunct.innerMethod.call(secondObject, param1, param2)
In this case, the
const cars = {
completeSelection: function(make, model) {
return this.color + " " + make + " " + model;
}
}
const firstSelection = {
color:"Blue"
}
cars.completeSelection.call(firstSelection, "Ford", "Mustang");
// "Blue Ford Mustang"
const cars = {
completeSelection: function(make, model) {
return this.color + " " + make + " " + model;
}
}
const firstSelection = {
color:"Blue"
}
cars.completeSelection.apply(firstSelection, ["Ford", "Mustang"]);
// "Blue Ford Mustang"
const ageCalculator = {
birthYear: 2015,
getAge: function() {
var d = new Date();
var thisYear = d.getFullYear();
const age = thisYear - this.birthYear
return age;
}
};
const person1 = {
birthYear: 1983
}
const person2 = {
birthYear: 1977
}
// Invoked at the global scope
const globalGetAge = ageCalculator.getAge;
console.log(globalGetAge());
// expected output: NaN
// Bind person1. "this" now points to person1
const bindGetAge1 = globalGetAge.bind(person1);
console.log(bindGetAge1());
// Result: 37
// Bind person2. "this" now points to person2
const bindGetAge2 = globalGetAge.bind(person2);
console.log(bindGetAge2());
// Result: 43
// Bind this orignal for demonstration.
const bindGetAge3 = globalGetAge.bind(ageCalculator);
console.log(bindGetAge3());
// Result: 5