MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  • What are built-in methods?
  • Using docs
  • Useful Built-In Methods
  • Math
  • String
  • Array
  • Objects
  • Bonus
  1. 2nd Month
  2. Week 5
  3. Javascript

Built in functions

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.

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:

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.

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.

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

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

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.

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 forEachmethod 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;
};
PreviousArrow function expressionsNextREST - Representational State Transfer

Last updated 1 year ago

&

2️⃣
JavaScript | MDN
Date()
new Date()
Date.now()
Date.parse()
Date - JavaScript | MDN
Math.round(num)
Math.floor(num)
Math.ceil(num)
Math.sqrt(x)
Math.cbrt(x)
Math.PI
Math - JavaScript | MDN
string.length()
string.toUpperCase()
string.toLowerCase()
string.split(separator, limit)
string.replace(searchFor, replaceWith)
String - JavaScript | MDN
array.length
array.push()
array.pop()
array.forEach()
array.map()
array.filter()
Array - JavaScript | MDN
Object.keys(obj)
Object.values(obj)
Object.entries(obj)
Object.fromEntries(arr)
for...in
Object - JavaScript | MDN