Loading...

Methods in JavaScript

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

Array.forEach() - Loop over array's items.

const arr = [1, 2, 3, 4, 5];

arr.forEach(item => {

   console.log(item); // output: 1 2 3 4 5
});

Array.includes() - Check if the item passed exists in an array.

const arr = [1, 2, 3, 4, 5];

arr.includes(2); // output: true
arr.includes(7); // output: false

Array.filter() - Use given function to text elements in an array and create a new array using these.

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]

Array.map() - Call a given function on every element in an array and then create a new array using the results.

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]

Array.reduce() - Using a given function, this will return a single value by applying the function against an accumulator and each array element.

const arr = [1, 2, 3, 4, 5];

const sum = arr.reduce((total, value) => total + value, 0);

console.log(sum); // 15

Array.some() - true or false will be passed based on whether or not at least one array element passes the test in the given function.

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

Array.every() - This works like , but true or false will be passed based on whether or not all array element passes the test in the given function.

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

Array.sort() - This will sort through an array to arrange it in either ascending or descending order. This changes the original array.

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']

Array.from() - This will return an Array from any object with any iterable object or and object with a length property.

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", "."]

Array.of() - This just makes an array out of the arguments passed in.

const numberArray= Array.of(1, 2, 3, 4, 5);
console.log(numberArray); // output: [1, 2, 3, 4, 5]

Array.join() - This just makes an array out of the arguments passed in.

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

String.toLowerCase() - As it sounds, this changes the original string into an all-lowercase string.

const aString = "HELLO! I AM EXCITED!!!";
aString.toLowerCase(); // "hello! i am excited!!!"

String.toUpperCase() - Like above, except this changes the original string into an all-uppercase string.

const aString = "hello. i am excited";
aString.toUpperCase(); // "HELLO. I AM EXCITED"

String.split() - This will break a sting apart into individual items and return an array.

const aString = "John Smith, Jane Rider, Phyllis Sizlak, Franz Feldman";
const aNewArray = aString.split(','); // "["John Smith", " Jane Rider", " Phyllis Sizlak", " Franz Feldman"]

String.startsWith() - This will check the the string to see if it starts with whatever was passed.

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

String.includes() - This tests the end of a string to see if it matches the passed string.

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

String.slice() - This will return a specified part of the string. It does not change the original.

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'

String.charAt() - This will return the character at a given index. The original is not changed

const str = 'Dev work is fun!';

  console.log(str.charAt()); // 'D'
  console.log(str.charAt(3)); // ' '
  console.log(str.charAt(14)); // 'N'

String.replace() - Provide two values and it will replace the first with the second in the string. This is case sensitive

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'

String.repeat() - This will return a string that copies the original as many times as we tell it to.

const str = 'Dev Life';

console.log(str.repeat(1)); // 'Dev Life'
console.log(str.repeat(3)); // 'Dev LifeDev LifeDev Life'

String.substring() - This will Create a short string from a longer one.

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!'

String.parseInt() - Converts a string to a number and returns it as an integer. Only the first number is returned and white space is allowed at the beginning and end. If the first character cannot be used, it returns NaN. This does not change the original.

const str = '177';

console.log(typeof str);  // string
console.log(typeof parseInt(str));  // number

String.parseFloat() - Converts a string to a number and returns it as a floating point number. Only the first number is returned and white space is allowed at the beginning and end. If the first character cannot be used, it returns NaN. This does not change the original.

const str = '177.32';

console.log(typeof str);  // string
console.log(parseFloat(str)); // 177.32
console.log(typeof parseFloat(str));  // number

Number Methods

Number.toString() - Converts a number or boolean to a string.

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

Number.toFixed() - returns a string with the given number of decimals.

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

Number.toPrecision() - returns a string as long as the value passed and will add a decimal and zeros, if needed.

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

Function.call() - This calls a function. It can be used to borrow a method from another object like this: firstFunct.innerMethod.call(secondObject, param1, param2) In this case, the this keyword will point to secondObject

const cars = {
  completeSelection: function(make, model) {
    return this.color + " " + make + " " + model;
  }
}
const firstSelection = {
  color:"Blue"
}
cars.completeSelection.call(firstSelection, "Ford", "Mustang");
// "Blue Ford Mustang"

Function.apply() - This works the same as .call(), but the parameters can be an array.

const cars = {
  completeSelection: function(make, model) {
    return this.color + " " + make + " " + model;
  }
}
const firstSelection = {
  color:"Blue"
}
cars.completeSelection.apply(firstSelection, ["Ford", "Mustang"]);
// "Blue Ford Mustang"

Function.bind() - This is similar to .call(), but it returns a function. .bind() enables the returned function to be stored in a variable.When this variable is used to call the function, its this keyword is set to what is provided. In addition, a set group of arguments would preced any provided when the function is called.

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

q
↑ Back to Top