Built-in Methods in Javascript 🤓
Tags: javascript
Published: 2021-06-02 15:54:32

### Hi! Programming can be overwhelming 😫 but once you are comfortable with some basic concepts, it starts to feel like a superpower 🦸‍♀️ and Javascript is one of the coolest languages to learn! 💯

### In this document you can find a summary of using Built-in Methods in Javascript. We will cover:

- What are built-in methods?
- Using Docs
- Useful Built-in methods
    - Date
    - Math
    - Strings
    - Arrays
    - Objects

If you need help with your setup, you can find some help below 👇

[Basic Setup](https://www.notion.so/Basic-Setup-ff2d8a8930d04a31bf508bc44a38bf95)

## What are built-in methods?

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.

[Standard built-in objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects)

### 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:

```jsx
objectName.methodName()
```

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. 

[JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript)

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**

**[Date()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)**

When called as a function, returns a string representation of the current date and time, exactly as `new Date().toString()` does.

**[new Date()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)**

When called as a constructor, returns a new `Date` object.

**[Date.now()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now)**

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.

**[Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse)**

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:**

[Date - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)

## Math

Math is a built-in object that has properties and methods for mathematical constants and functions.

**Useful built-in methods for Math objects**

**[Math.round(num)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round)**

Returns the provided number rounded to the closest integer (whole number).

**[Math.floor(num)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor)**

Rounds down to the previous integer.

[**Math.ceil(num)**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil)

Rounds up to the next integer.

**[Math.sqrt(x)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt) & [Math.cbrt(x)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cbrt)**

Returns the square root of x and the cube root of x, respectively.

**[Math.PI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI)**

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:**

[Math - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math)

## 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()`.

```jsx
console.log('hello'.toUpperCase()); // Prints 'HELLO'
```

**Useful built-in methods for String objects**

**[string.length()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length)**

Returns the length of a string.

**[string.toUpperCase()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase)**

Convert all of the characters in a string to capitals. Non-destructive — returns a new string, does not change the original string.

**[string.toLowerCase()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase)**

As with toUpperCase. Converts all characters to lower case. Non-destructive.

**[string.split(separator, limit)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)**

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”]**. 

```jsx
'Javascript is great'.split("") // returns ['Javascript', 'is', 'great']
```

**[string.replace(searchFor, replaceWith)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)**

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:**

[String - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype)

## 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.  

```jsx
let fruits = ['Apple', 'Banana']
```

**Useful built-in methods for Array objects**

[**array.length**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)

Not a method, but a super useful array’s built-in properties is length. It returns the number of items in the array.

```jsx
const newYearsResolutions = ['Keep a journal', 'Take a falconry class'];

console.log(newYearsResolutions.length);
// Output: 2
```

[**array.push()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)

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.

```jsx
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'];
```

**[array.pop()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop)**

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.

```jsx
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
```

**Iterators**

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.

**[array.forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)**

Executes the same code for each element of an array.

```jsx
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.

```jsx
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.

**[array.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)**

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():

```jsx
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.

**[array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)**

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.

```jsx
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:**

[Array - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Iteration_methods)

## 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**

**[Object.keys(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)**

Returns an array of the keys that the object contains.

**[Object.values(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)**

Returns an array of the values of each of the elements in the object.

**[Object.entries(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)**

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:

```jsx
obj = { a: 1, b: "b", c: [3,4,5] }Object.entries(obj)
>> [["a",1], ["b","b"], ["c",[3,4,5]]
```

**[Object.fromEntries(arr)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries)**

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.

```jsx
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}`);
}
```

[for...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)

**You can find a lot more information on built-in methods for Objects in the documentation:**

[Object - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods)

## 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.

```jsx
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.

```jsx
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:

```jsx
alienShip.invade(); // Prints 'Hello! We have come to dominate your planet. Instead of Earth, it shall be called New Xaculon.
```

```jsx
person.name = function () {
  return this.firstName + " " + this.lastName;
};
```

## Useful resources on Javascript

[JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript)

[freeCodeCamp.org](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/)

[JavaScript Tutorial: Learn JavaScript For Free | Codecademy](https://www.codecademy.com/learn/introduction-to-javascript)

[JavaScript Code to go](https://codetogo.io/javascript/)

---

Hi! My name is Pepe 👾, and I am from Panama in Central America 🌴🌞🌴 You can find me in [linkedin](https://www.linkedin.com/in/pepebenitez/), [twitter](https://twitter.com/elpepebenitez) or [github.](https://github.com/elpepebenitez) 

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