Introduction to JavaScript Functions

Methods

We can write in an object-oriented fashion using JavaScript as well. In fact most of the built-in types are objects with many methods and properties, which is the main reason why we're even looking at this topic as we rarely need to write object-oriented code ourselves.

Methods vs functions

Methods are functions associated with a class. They can access internal class data.

Practical

What classes are is not very important for us. We just need to know that classes are objects with some methods and properties that can access the classes state.

For example, String is a class in JavaScript. All strings have this type. The class provides many helper methods and properties.

const reply = "I AM CALM"
console.log(reply.toLowerCase()) // "i am calm"
console.log(reply.length) // 9

Here JavaScript automatically creates a new String instance in the first line. In the second line, we use one of String's method toLowerCase to convert all letters to their lower case versions. The third line gets a property length of our specific String instance.

Classes are just functions

We can define what other most other languages call classes with functions in JavaScript.

Below is an example Person class written in Java.

class Person {
String name;
int age;
public Person(name, age) {
this.name = name;
this.age = age;
}
public String sayHi(String to) {
return String.format("Hi, %s! My name is %s.",
to, this.name);
}
}

The same class is written in JavaScript below. We instantiate instances of classes with the new keyword followed by the class name and constructor parameters.

function Person(name, age) {
this.name = name;
this.age = age;
this.sayHi = to => {
return `Hi, ${to}! My name is ${name}.`
}
}
const leto = new Person("Leto", 3500)
const greeting = leto.sayHi("Ghanima")
console.log(greeting) // "Hi, Ghanima! My name is Leto."