Methods
A method is a function that is associated with an object.
Traversy media vid
It’s easy to get properties and methods mixed up.
A string will always have a length which is one of it’s properties. Using .length
will produce that property.
const ship = 'This ship is goin down';
console.log(ship.length);
// 22
Methods however end with parentheses. These can include parameters inside the parentheses, but not always.
const ship = 'This ship is goin down';
console.log(ship.toUpperCase());
// 22
?
<button
onclick="howLongParagraph.textContent = `The ship paragraph is ${ship.length} characters long.`;">
ship.length
</button>
Chaining multiple methods
You can chain several methods together like so:
alert(`Only a few letters ${ship.toUpperCase().substring(0, 6)}`)
First the toUpperCase()
method converts the string to capitals. Then the substring()
method is used to reduce the string to the first 6 characters (including spaces).