- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Title
- Type conversion
- While loop
JAVASCRIPT
JavaScript Methods: Syntax, Usage, and Examples
In JavaScript, a method is a function that's defined inside a class and used to perform actions on the object it belongs to. Methods help objects do things, like eat, sleep, or calculate something, depending on what you want your program to accomplish.
How to Use JavaScript Methods
To define a method inside a class, you skip the function
keyword and write the method name directly. Then, you place the method's instructions inside curly braces.
class VirtualPet {
constructor(name) {
this.name = name;
}
eat() {
console.log("nom nom");
}
}
In this example, eat()
is a method of the VirtualPet
class. It's written just like a function, but since it's inside a class, it's called a method.
To call a method, you use the object's name, followed by a dot, then the method name with parentheses.
const pet = new VirtualPet("Tom");
pet.eat(); // Output: nom nom
This line tells the pet
object to run its eat()
method. The parentheses are required, even if the method doesn't take any parameters.
When to Use Methods in JavaScript
Methods are useful whenever you want objects to perform actions. Rather than writing standalone functions, you can attach relevant functionality directly to the class it belongs to. Here are some common situations where methods make your code clearer and easier to manage:
Representing Real-World Behavior
Methods can represent actions your objects might do in real life. If you’re coding a game, you might have characters that jump, heal, or attack. Methods make these behaviors easy to attach to each character or object.
Managing Object State
Methods often modify or respond to the internal state of an object. For instance, if your object has properties like health
, energy
, or score
, a method can increase or decrease these based on actions.
class Player {
constructor(name) {
this.name = name;
this.health = 100;
}
takeDamage(amount) {
this.health -= amount;
}
}
Keeping Code Organized
By using methods, your code becomes easier to read. You won’t have a tangle of global functions. Instead, everything related to the object stays within the class. This improves structure and readability, especially as your application grows.
Examples of JavaScript Methods
Here are several examples showing how JavaScript methods work in action:
Example 1: Method That Changes Object State
class Light {
constructor() {
this.isOn = false;
}
toggle() {
this.isOn = !this.isOn;
}
}
const lamp = new Light();
console.log(lamp.isOn); // false
lamp.toggle();
console.log(lamp.isOn); // true
This method flips the isOn
state between true
and false
each time it’s called.
Example 2: Method With Parameters
class BankAccount {
constructor(balance) {
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
}
const account = new BankAccount(100);
account.deposit(50);
console.log(account.balance); // 150
The deposit()
method takes a value and updates the account's balance.
Example 3: Calling One Method From Another
class Speaker {
constructor(name) {
this.name = name;
}
greet() {
console.log("Hi, my name is " + this.name);
}
introduce() {
this.greet();
console.log("Nice to meet you!");
}
}
const anna = new Speaker("Anna");
anna.introduce();
// Output:
// Hi, my name is Anna
// Nice to meet you!
In this case, introduce()
calls another method inside the same class. This pattern helps you break complex logic into smaller, reusable parts.
Learn More About JavaScript Methods
JavaScript Methods vs Functions
Functions are standalone blocks of code. Methods are functions that belong to objects (usually defined inside classes). You can think of it like this: all methods are functions, but not all functions are methods.
function add(x, y) {
return x + y;
}
class Calculator {
add(x, y) {
return x + y;
}
}
The add()
function here is standalone in the first example. In the class, add()
is a method.
Method Overriding
In object-oriented JavaScript, classes can inherit methods from other classes. Sometimes you need to change how an inherited method works. This is where method overriding comes in.
class Animal {
speak() {
console.log("Some sound");
}
}
class Dog extends Animal {
speak() {
console.log("Woof!");
}
}
const dog = new Dog();
dog.speak(); // Output: Woof!
The Dog
class overrides the speak()
method from Animal
with its own version. If you want to keep some functionality from the parent class and add more, you can also use super
.
class Cat extends Animal {
speak() {
super.speak(); // Calls Animal's speak method
console.log("Meow!");
}
}
Using this
in Methods
Inside a method, the this
keyword refers to the object that owns the method. This is how the method accesses and modifies the object’s properties.
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
Calling increment()
changes the object’s count
property.
Arrow Functions as Methods
Arrow functions behave differently from regular methods when it comes to this
. You usually want to avoid using arrow functions as methods in classes because they don’t have their own this
context.
class Timer {
constructor() {
this.seconds = 0;
}
// Not recommended
start = () => {
setInterval(() => {
this.seconds++;
}, 1000);
};
}
In this example, using an arrow function inside setInterval
is fine because it helps preserve this
. But using arrow functions to define class methods themselves can cause problems if you rely on inheritance or need to bind the method later.
Built-In JavaScript Methods
JavaScript also provides built-in methods on data types like arrays and strings. These are different from class methods but follow the same syntax.
const fruits = ["apple", "banana"];
fruits.push("cherry"); // push is a method
const name = "Charlie";
console.log(name.toUpperCase()); // toUpperCase is a string method
These methods are part of JavaScript’s core and can be used on built-in objects without writing your own class.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.