Built-in Methods in Javascript π€
A JavaScript method is a property containing a function definition. In other words, when the data stored on an object is a function we call that a method.
To differenciate between properties and methods, we can think of it this way: A property is what an object has, while a method is what an object does.
Since JavaScript methods are actions that can be performed on objects, we first need to have objects to start with. There are several objects built into JavaScript which we can use.
How to access object methods?
We call, or use, methods by appending an instance with:
- a period (the dot operator)
- the name of the method
- opening and closing parentheses
You access an object method with the following syntax:
The methodName property will execute (as a function) when it is invoked with ().
If you access the methodName property, without (), it will return the function definition instead of executing an action.
Using docs
I cannot stress enough just how important being familiar with the official documentation can be. You do not need to memorize everything, but you should know where or how to find something you need.
That is why using documentation is part of the daily lives of developers. Developers use documentation as a reference tool. It describes JavaScriptβs keywords, methods, and syntax.
Take a moment to look at the javascript documentation by MDN Web Docs and play around with the links. There is a ton of very useful information about javascript in theses pages.
It does not matter if you don’t understand everything right away. Everybody goes through different learning paths Β‘Just keep practicing!
Useful Built-In Methods
Specific built-in objects have different built-in methods which we can use. Below you can find some useful methods for Date, Math, String, Array and Object objects. π
Date
JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.
Useful built-in methods for Date objects
When called as a function, returns a string representation of the current date and time, exactly as new Date().toString() does.
When called as a constructor, returns a new Date object.
Returns the numeric value corresponding to the current timeβthe number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored.
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC, with leap seconds ignored.Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.
You can find a lot more information on built-in methods for Date objects in the documentation:
Math
Math is a built-in object that has properties and methods for mathematical constants and functions.
Useful built-in methods for Math objects
Returns the provided number rounded to the closest integer (whole number).
Rounds down to the previous integer.
Rounds up to the next integer.
Returns the square root of x and the cube root of x, respectively.
Not technically a method, but a property! Handy if you need Pi.
You can find a lot more information on built-in methods for Math objects in the documentation:
String
The String object is used to represent and manipulate a sequence of characters. Strings are useful for holding data that can be represented in text form, and JavaScript provides a number of useful string built-in methods.
E.g. ‘example string’.methodName() .
console.log('hello'.toUpperCase()); // Prints 'HELLO'
Useful built-in methods for String objects
Returns the length of a string.
Convert all of the characters in a string to capitals. Non-destructive β returns a new string, does not change the original string.
As with toUpperCase. Converts all characters to lower case. Non-destructive.
Splits the string into an array, split by the provided separator. If an empty string (ββ) is provided, it will split each character into a new element in the array. Eg. (βJavaScript is greatβ).split(β β) will return [βJavaScriptβ, βisβ, βgreatβ].
'Javascript is great'.split("") // returns ['Javascript', 'is', 'great']
Finds every instance of the search for substring and replaces it with the given new substring. Non-destructive.
You can find a lot more information on built-in methods for String objects in the documentation:
Array
The simplest way to describe Arrays is that they list-like objects. Something super important about arrays is that they are indexed, meaning that you can access specific values by the index or the location they hold in the list.
Useful built-in methods for Array objects
Not a method, but a super useful arrayβs built-in properties is length. It returns the number of items in the array.
const newYearsResolutions = ['Keep a journal', 'Take a falconry class']; console.log(newYearsResolutions.length); // Output: 2
Allows us to add items to the end of an array. Notice that .push() changes, or mutates, the array. You might also see .push() referred to as a destructive array method since it changes the initial array.
const itemTracker = ['item 0', 'item 1', 'item 2']; itemTracker.push('item 3', 'item 4'); console.log(itemTracker); // Output: ['item 0', 'item 1', 'item 2', 'item 3', 'item 4'];
Removes the last item of an array. It does not take any arguments, it simply removes the last element of the array and it returns the value of the last element. It is a method that mutates the initial array.
const newItemTracker = ['item 0', 'item 1', 'item 2']; const removed = newItemTracker.pop(); console.log(newItemTracker); // Output: [ 'item 0', 'item 1' ] console.log(removed); // Output: item 2
The built-in JavaScript array methods that help us iterate are called iteration methods, at times referred to as iterators. Iterators are methods called on arrays to manipulate elements and return values.
Executes the same code for each element of an array.
groceries.forEach(groceryItem => console.log(' - ' + groceryItem) );
Looping is a very important concept, so letβs explore the syntax of invoking .forEach() .
- groceries.forEach() calls the forEach method on the groceries array.
- .forEach() takes an argument of callback function. Remember, a callback function is a function passed as an argument into another function.
- .forEach() loops through the array and executes the callback function for each element. During each execution, the current element is passed as an argument to the callback function.
- The return value for .forEach() will always be undefined .
We can also define a function beforehand to be used as the callback function.
function printGrocery(element) console.log(element); > groceries.forEach(printGrocery);
Itβs good to be aware of the different ways to pass in callback functions as arguments in iterators because developers have different stylistic preferences.
When .map() is called on an array, it takes an argument of a callback function and returns a new array. Take a look at an example of calling .map():
const numbers = [1, 2, 3, 4, 5]; const bigNumbers = numbers.map(number => return number * 10; >);
.map() works in a similar manner to .forEach()β the major difference is that .map() returns a new array.
Like .map(), .filter() returns a new array. However, .filter() returns an array of elements after filtering out certain elements from the original array. The callback function for the .filter() method should return true or false depending on the element that is passed to it. The elements that cause the callback function to return true are added to the new array.
const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door']; const shortWords = words.filter(word => return word.length 6; >);
You can find a lot more information on built-in methods for Array objects in the documentation:
Objects
It is a bit funny to say that we can use built-in methods for Object objects, but hey I did not make the rules. We can also take advantage of built-in methods for Objects. Objects are used to store various keyed collections, or key and value pairs.
Useful built-in methods for Array objects
Returns an array of the keys that the object contains.
Returns an array of the values of each of the elements in the object.
Returns an array containing nested arrays for each key-value pair. The first element in each nested array is the key, and the second is the value. Eg:
obj = a: 1, b: "b", c: [3,4,5] >Object.entries(obj) >> [["a",1], ["b","b"], ["c",[3,4,5]]
Creates a new object from an array of key-value pairs passed as the argument. Returns the new object.
Looping Through Objects
Same as iterating thorough Arrays with .forEach() , for. in will execute a given block of code for each property in an object.
let spaceship = crew: captain: name: 'Lily', degree: 'Computer Engineering', cheerTeam() console.log('You got this!') > >, 'chief officer': name: 'Dan', degree: 'Aerospace Engineering', agree() console.log('I agree, captain!') > >, medic: name: 'Clementine', degree: 'Physics', announce() console.log(`Jets on!`) > >, translator: name: 'Shauna', degree: 'Conservation Science', powerFuel() console.log('The tank is full!') > > > >; // for. in for (let crewMember in spaceship.crew) console.log(`$crewMember>: $spaceship.crew[crewMember].name>`); >
You can find a lot more information on built-in methods for Objects in the documentation:
Bonus
Adding a Method to an Object
We could create our own objects and methods to model real life situations and actions,
Adding a new method to an object is easy:
We can include methods in our object literals by creating ordinary, comma-separated key-value pairs. The key serves as our methodβs name, while the value is an anonymous function expression.
const alienShip = invade: function () console.log('Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.') > >;
With the new method syntax introduced in ES6 we can omit the colon and the function keyword.
const alienShip = invade () console.log('Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.') > >;
Object methods are invoked by appending the objectβs name with the dot operator followed by the method name and parentheses:
alienShip.invade(); // Prints 'Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.
person.name = function () return this.firstName + " " + this.lastName; >;
Useful resources on Javascript
Hi! My name is Pepe πΎ, and I am from Panama in Central America π΄ππ΄ You can find me in linkedin, twitter or github.
- If you found this useful feel free to share it!
- If you have any questions, recommendations or general comments feel free to drop me a message!
JavaScript Object Methods
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object. |
Alone, this refers to the global object. |
In a function, this refers to the global object. |
In a function, in strict mode, this is undefined . |
In an event, this refers to the element that received the event. |
Methods like call() , apply() , and bind() can refer this to any object. |
Note
See Also:
JavaScript Methods
JavaScript methods are actions that can be performed on objects.
A JavaScript method is a property containing a function definition.
Property | Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
fullName | function() |
Methods are functions stored as object properties.
Accessing Object Methods
You access an object method with the following syntax:
You will typically describe fullName() as a method of the person object, and fullName as a property.
The fullName property will execute (as a function) when it is invoked with ().
This example accesses the fullName() method of a person object:
Example
If you access the fullName property, without (), it will return the function definition: