JavaScript methods are like built-in tools that let you work with different types of data quickly and easily. Whether you want to change text, work with lists, handle numbers, or respond to user actions, methods are functions attached to objects that help you do these tasks without writing all the code from scratch. For beginners, learning these methods is a key step to understanding how JavaScript can manipulate and interact with the world inside your browser.
Think of methods as special verbs that tell JavaScript exactly what to do with your data. For example, you might want to convert a sentence to uppercase, find a specific item in a list, or listen for when someone clicks a button. These actions are all done through methods, which make programming more organized and fun. This article will guide you through essential JavaScript methods for beginners, showing how to use each one with simple, lively examples.
String Methods
Strings are like sentences or words made up of letters, numbers, and symbols. In JavaScript, strings are everywhere — from displaying messages to handling user input. Luckily, JavaScript provides many helpful string methods to explore, change, and check strings in creative ways. Let’s take a look at some of the most useful ones with fun examples.
.toUpperCase()
and .toLowerCase()
One common task is changing the case of letters. The .toUpperCase()
method turns all characters in a string into uppercase, like shouting in text. On the other hand, .toLowerCase()
makes all the letters lowercase — useful for normalizing user input or formatting messages.
const greeting = "Hello, Edward!";
console.log(greeting.toUpperCase()); // Outputs: HELLO, EDWARD!
console.log(greeting.toLowerCase()); // Outputs: hello, edward!
Even though you see the letters change, the original greeting
string is untouched. These methods return a new string with the changes — great for customizing display without affecting the original data.
.slice()
The .slice()
method works like scissors. It cuts a section out of the string and returns it. You give it a starting position and an ending position (the end is not included and is optional), and it gives you just that part.
const pizza = "Pepperoni Pizza";
const slice = pizza.slice(0, 9);
console.log(slice); // Outputs: Pepperoni
Here, we start at index 0 and stop before index 9. The result is the word “Pepperoni,” just like picking a slice from the start of a pizza.
.replace()
Another useful method is .replace()
. It swaps part of a string with something else. For example, you might want to replace a word in a sentence.
const sentence = "JavaScript is fun!";
const newSentence = sentence.replace("fun", "awesome");
console.log(newSentence); // Outputs: JavaScript is awesome!
Only the first match is replaced. If the word appears multiple times, only the first one changes — unless you use .replaceAll()
or regular expressions (that’s a topic for another day).
.includes()
Next, the .includes()
method helps you check if a certain word or character exists in a string — almost like scanning a message for a secret code.
const phrase = "The quick brown fox";
console.log(phrase.includes("fox")); // Outputs: true
console.log(phrase.includes("dog")); // Outputs: false
It simply returns true
or false
. This is perfect for conditionally checking content before showing a message, warning, or confirmation.
.startsWith()
and .endsWith()
Now let’s get fancy with .startsWith()
and .endsWith()
. These methods tell you if a string begins or ends with specific text.
const bookTitle = "Harry Potter and the Goblet of Fire";
console.log(bookTitle.startsWith("Harry")); // Outputs: true
console.log(bookTitle.endsWith("Fire")); // Outputs: true
console.log(bookTitle.endsWith("Stone")); // Outputs: false
These are very useful when sorting items, validating input, or filtering data by prefix or suffix.
.repeat()
Sometimes, you want to repeat a string multiple times. That’s exactly what .repeat()
does.
const magicWord = "Expelliarmus! ";
console.log(magicWord.repeat(3)); // Outputs: Expelliarmus! Expelliarmus! Expelliarmus!
In this fun example, the magical word is cast three times in a row! This method is perfect for adding emphasis, building patterns, or creating test strings.
.trim()
If you’re dealing with extra spaces, the .trim()
method is your best tool. It removes any whitespace from the start and end of the string — no more messy input boxes!
const userInput = " Gryffindor ";
console.log(userInput.trim()); // Outputs: Gryffindor
Only the leading and trailing spaces are removed — spaces inside the string stay untouched.
.split()
And finally, if you want to break a string into pieces, use the .split()
method. It divides the string into an array using a separator you choose, like a comma, space, or letter.
const houses = "Gryffindor,Hufflepuff,Ravenclaw,Slytherin";
const houseList = houses.split(",");
console.log(houseList);
// Outputs: ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]
Here, we turned one long string into an array of Hogwarts houses. Now you can work with each item separately — maybe show them in a list or let a user pick their favorite.
JavaScript string methods are not just powerful — they’re also fun to use. Whether you’re formatting text, checking content, or slicing and dicing your strings, there’s a method for every task. These tools help turn raw text into something interactive and meaningful.
Array Methods
Arrays are special containers in JavaScript that can hold multiple values — like a basketball team lineup where each player has their place. These values can be anything: numbers, strings, or even other arrays. Working with arrays becomes much easier when you use JavaScript’s built-in methods.
.push()
and .pop()
Let’s begin with adding and removing items. If you want to add something to the end of the list, the .push()
method is your best friend. To remove the last item, .pop()
steps in. Let’s see this in action using a pack of dog breeds:
const dogs = ["Beagle", "Bulldog", "Dalmatian"];
dogs.push("Labrador");
console.log(dogs); // Outputs: ["Beagle", "Bulldog", "Dalmatian", "Labrador"]
const removed = dogs.pop();
console.log(removed); // Outputs: Labrador
console.log(dogs); // Outputs: ["Beagle", "Bulldog", "Dalmatian"]
In the example above, we first add “Labrador” to our dog list using .push()
. Then, we remove it using .pop()
. Notice that the array updates immediately after each action, just like players subbing in and out of a game.
.unshift()
and .shift()
Now, let’s talk about the start of the array. Want to add a new player to the beginning of the team? Use .unshift()
. Need to remove the first one? .shift()
will handle that.
const dogs = ["Beagle", "Bulldog", "Dalmatian"];
dogs.unshift("Golden Retriever");
console.log(dogs); // Outputs: ["Golden Retriever", "Beagle", "Bulldog", "Dalmatian"]
let firstDog = dogs.shift();
console.log(firstDog); // Outputs: Golden Retriever
console.log(dogs); // Outputs: ["Beagle", "Bulldog", "Dalmatian"]
Here, “Golden Retriever” joins as the lead dog, and then we shift it off — just like a team captain stepping down.
.indexOf()
Now, what if you’re searching for something specific? That’s where .indexOf()
helps. It tells you the position of an item in the array. If it doesn’t find the item, it returns -1
, which means “not there.”
const dogs = ["Beagle", "Bulldog", "Dalmatian"];
console.log(dogs.indexOf("Bulldog")); // Outputs: 1
console.log(dogs.indexOf("Labrador")); // Outputs: -1
In our current dogs
array, “Bulldog” is at position 1 (remember, arrays start counting from 0). But “Labrador” was removed earlier, so it returns -1
.
.slice()
Let’s say you want to grab a part of an array — not change it, just get a piece. That’s what .slice()
does. It returns a new array from a part of the original, like slicing cake and keeping your slice.
const birds = ["Parrot", "Owl", "Eagle", "Falcon"];
const someBirds = birds.slice(1, 3);
console.log(someBirds); // Outputs: ["Owl", "Eagle"]
This method takes a start index and an end index (but doesn’t include the end). The original array stays untouched — which is great for keeping your data safe while still getting what you need.
.splice()
But what if you actually want to change the array by removing or inserting items? That’s where .splice()
comes in. It’s like performing surgery on an array — you can cut and add elements.
const reptiles = ["Lizard", "Snake", "Crocodile"];
reptiles.splice(1, 1, "Turtle");
console.log(reptiles); // Outputs: ["Lizard", "Turtle", "Crocodile"]
In this example, we start at index 1 (where “Snake” is), remove 1 item, and insert “Turtle” in its place. It’s a powerful method when you need to edit the array directly.
.concat()
Want to combine two arrays into one? The .concat()
method joins them together and gives you a fresh new array:
const cats = ["Siamese", "Persian"];
const moreCats = ["Maine Coon", "Bengal"];
const allCats = cats.concat(moreCats);
console.log(allCats); // Outputs: ["Siamese", "Persian", "Maine Coon", "Bengal"]
Both arrays stay untouched, and the result is a bigger team — ready to meow in harmony.
.reverse()
Sometimes, you want to flip an array around — maybe for a countdown or a reversed order. The .reverse()
method turns everything backward:
const countdown = [1, 2, 3, 4, 5];
countdown.reverse();
console.log(countdown); // Outputs: [5, 4, 3, 2, 1]
Just remember: .reverse()
does change the original array, so use it only when you really want the flip.
.includes()
We can’t forget .includes()
, which checks whether an item is in the array — like a quick “Is this on the team?” test.
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Banana")); // Outputs: true
console.log(fruits.includes("Kiwi")); // Outputs: false
It returns a simple true or false. This method is perfect when validating user input or filtering search results.
.join()
Lastly, let’s say you want to display your array items as one friendly string. .join()
turns the array into a sentence, using a separator you choose.
const languages = ["JavaScript", "Python", "Ruby"];
console.log(languages.join(", ")); // Outputs: JavaScript, Python, Ruby
This is great for making readable lists. Want to make it fun? Use emojis:
const languages = ["JavaScript", "Python", "Ruby"];
console.log(languages.join(" ❤️ ")); // Outputs: JavaScript ❤️ Python ❤️ Ruby
And that’s the charm of array methods — they help you manage lists, teams, or collections with ease, power, and sometimes even a little flair. Whether you’re slicing, splicing, or combining values, JavaScript arrays are ready to handle the action.
Number Methods
In JavaScript, numbers come with a few helpful methods to control how they look and behave. These methods are especially useful when working with money, scores, or measurements where precision matters.
.toFixed()
One common method is .toFixed()
. This method doesn’t change the actual number but gives you a string version with a fixed number of decimal places. It’s perfect when you want clean results like “93.46” instead of a long decimal like “93.4567”.
const score = 93.4567;
console.log(score.toFixed(2)); // Outputs: 93.46
In this example, the number 93.4567
is formatted to two decimal places, rounding it to "93.46"
. Notice it’s returned as a string — this makes it great for display in user interfaces, especially when showing prices, grades, or scores.
Math.round()
JavaScript includes a built-in Math
object that gives you access to many math tools. One of them is Math.round()
, which rounds a number to the nearest whole value. If the decimal is 0.5 or more, it goes up. If it’s less than 0.5, it goes down.
console.log(Math.round(4.5)); // Outputs: 5
console.log(Math.round(4.4)); // Outputs: 4
The first line rounds 4.5
up to 5
, while the second line rounds 4.4
down to 4
. This is handy when you want to make clean, whole-number decisions from floating-point values.
Math.floor()
If you always want to round down, no matter what the decimal part is, use Math.floor()
.
console.log(Math.floor(4.9)); // Outputs: 4
This takes the number 4.9
and removes everything after the decimal, giving you the next lowest whole number — in this case, 4
. It’s great when you want to cap something, like limiting a score or index.
Math.ceil()
On the other hand, Math.ceil()
always rounds up, even if the decimal is tiny.
console.log(Math.ceil(4.1)); // Outputs: 5
Even though 4.1
is just a little over 4, Math.ceil()
pushes it up to 5
. This is useful when you want to guarantee you’re not underestimating something, like the number of pages needed for a list.
Math.trunc()
Sometimes, you don’t want to round up or down — you just want to cut off the decimal part completely. That’s where Math.trunc()
comes in.
console.log(Math.trunc(4.9)); // Outputs: 4
console.log(Math.trunc(-4.9)); // Outputs: -4
The first line removes the .9
from 4.9
, giving you 4
. The second line shows that it works with negative numbers too — it cuts off the decimal without changing the sign. This method is great for slicing off the extra bits cleanly.
Math.abs()
Need to turn a negative number into a positive one? Use Math.abs()
to get the absolute value.
console.log(Math.abs(-7)); // Outputs: 7
This takes -7
and turns it into 7
. Absolute values are useful when direction doesn’t matter, like checking how far off a guess was in a game.
Math.max()
If you’re choosing between multiple numbers and need the biggest one, Math.max()
will pick the highest.
console.log(Math.max(10, 3, 27, 5)); // Outputs: 27
This returns 27
, the largest number in the list. It works just like asking, “Who’s the tallest in the group?”
Math.min()
To get the smallest number, Math.min()
does the opposite.
console.log(Math.min(10, 3, 27, 5)); // Outputs: 3
This gives you 3
, the lowest number in the group. It’s handy when you want to find the shortest time, the cheapest price, or the lowest score.
Number.isNaN()
Sometimes, calculations go wrong and give you something that’s not a real number. JavaScript calls that NaN
, which stands for “Not a Number.” To check if something is actually NaN
, use Number.isNaN()
.
console.log(Number.isNaN(5)); // Outputs: false
console.log(Number.isNaN("hello" / 2)); // Outputs: true
The first check returns false
because 5
is definitely a number. The second one divides a string by a number, which doesn’t make sense — so it returns true
. This helps you catch problems early, especially when dealing with user input or tricky math.
With these number methods, you can format, round, clean, compare, and verify values in just a few lines. Whether you’re building a calculator, handling scores in a game, or simply making your output look polished, JavaScript gives you all the tools to work with numbers with confidence and style.
Object Methods
Objects in JavaScript are collections of key-value pairs — like labeled containers that store information. Each key points to a specific value, and these are very useful when organizing structured data like player profiles, settings, or configurations. JavaScript offers several built-in methods to help you work with objects more easily.
Object.keys()
Sometimes, you might want to look at only the keys in an object — kind of like checking the labels on boxes. You can use Object.keys()
to get all the property names from an object as an array.
const player = {name: "Edward", position: "Guard", team: "Zambia"};
console.log(Object.keys(player)); // Outputs: ["name", "position", "team"]
Here, we have an object called player
with three pieces of information. Object.keys(player)
pulls out just the keys — not the values — and puts them in an array. This is useful when you want to loop through property names or display available options.
Object.values()
If you only care about the contents (the values) and not the labels, use Object.values()
instead. This gives you just the values stored inside the object.
const player = {name: "Edward", position: "Guard", team: "Zambia"};
console.log(Object.values(player)); // Outputs: ["Edward", "Guard", "Zambia"]
This line returns an array of the values in the same order as their keys: the name, position, and team. It’s helpful for showing user data or exporting object content.
Object.entries()
To get both the keys and the values together as pairs, you can use Object.entries()
. This turns the object into an array of smaller arrays, where each one contains a key and its matching value.
const player = {name: "Edward", position: "Guard", team: "Zambia"};
console.log(Object.entries(player));
// Outputs: [["name", "Edward"], ["position", "Guard"], ["team", "Zambia"]]
Now each pair is grouped together inside a sub-array. This is perfect when you want to loop through and display both the name and the value, like showing "name: Edward"
in a settings page.
.hasOwnProperty()
Sometimes you want to check if a specific key exists in an object. You can use the .hasOwnProperty()
method for that. It returns true
if the object has the key, and false
if it doesn’t.
const player = {name: "Edward", position: "Guard", team: "Zambia"};
console.log(player.hasOwnProperty("position")); // Outputs: true
console.log(player.hasOwnProperty("age")); // Outputs: false
In this example, the object does have a "position"
key, but no "age"
key. This method is great when you’re unsure what data is present and want to avoid errors.
Object.assign()
JavaScript also lets you combine objects using Object.assign()
. This method copies the values from one or more source objects into a target object. It’s useful when merging data or updating records.
const player = {name: "Edward", position: "Guard", team: "Zambia"};
const updates = {team: "Lusaka Eagles", age: 25};
const updatedPlayer = Object.assign({}, player, updates);
console.log(updatedPlayer);
// Outputs: {name: "Edward", position: "Guard", team: "Lusaka Eagles", age: 25}
We created a new object by merging the original player
object with the updates
. The team
value was replaced, and a new age
field was added. Object.assign()
makes it easy to update objects without changing the original.
Object.fromEntries()
Another modern way to work with objects is using Object.fromEntries()
. This is like the opposite of Object.entries()
. It takes an array of key-value pairs and turns it back into a full object.
const entries = [["name", "Edward"], ["position", "Guard"], ["team", "Zambia"]];
const newPlayer = Object.fromEntries(entries);
console.log(newPlayer);
// Outputs: {name: "Edward", position: "Guard", team: "Zambia"}
This turns an array of pairs into an object, making it very useful when you’re working with converted or transformed data.
These object methods let you explore, manipulate, and control structured data in your code. Whether you’re building a user profile, handling settings, or merging updates, JavaScript gives you powerful tools to work with objects clearly and efficiently.
Event Methods (DOM)
In JavaScript, the DOM (Document Object Model) allows you to interact with HTML elements on a webpage. One powerful way to do this is by responding to user actions — like clicking a button, moving a mouse, or typing in a box. These actions are called events, and JavaScript lets you connect functions to them using event methods.
.addEventListener()
The most common method is .addEventListener()
. It attaches a function to run when a specific event happens on an element. For example, you might want something fun to happen when a user clicks a button.
<!DOCTYPE html>
<html>
<head>
<title>Magic Button</title>
</head>
<body>
<button id="magicBtn">Click for Magic</button>
<script>
const magicBtn = document.getElementById('magicBtn');
magicBtn.addEventListener('click', () => {
alert('✨ You clicked the magic button!');
});
</script>
</body>
</html>
In this code, we first grab the button with getElementById()
, then use .addEventListener('click', ...)
to make something happen when it’s clicked. Here, it shows a fun alert. The browser listens for the event and responds when needed.
.removeEventListener()
Sometimes, you want to remove the event listener after it runs once. You can use .removeEventListener()
to stop it from triggering again.
<!DOCTYPE html>
<html>
<head>
<title>One-Time Alert</title>
</head>
<body>
<button id="onceBtn">Click Me Once</button>
<script>
const onceBtn = document.getElementById('onceBtn');
function showAlertOnce() {
alert('This will only run once.');
onceBtn.removeEventListener('click', showAlertOnce);
}
onceBtn.addEventListener('click', showAlertOnce);
</script>
</body>
</html>
Here, the function showAlertOnce
runs when the button is clicked. Inside the function, we immediately remove the listener, so the alert only happens the first time the user clicks the button.
event.target
Another helpful property is event.target
, which tells you which element triggered the event. This is useful when the same function is handling multiple elements.
<!DOCTYPE html>
<html>
<head>
<title>Multiple Buttons</title>
</head>
<body>
<button class="colorBtn">Red</button>
<button class="colorBtn">Blue</button>
<button class="colorBtn">Green</button>
<script>
const buttons = document.querySelectorAll('.colorBtn');
buttons.forEach(button => {
button.addEventListener('click', function(event) {
alert(`You clicked: ${event.target.textContent}`);
});
});
</script>
</body>
</html>
In this example, we attach the same listener to three buttons. When any of them is clicked, event.target.textContent
tells us which one it was — and we show that in an alert.
.addEventListener()
with other event types
You can also use .addEventListener()
for different types of events — not just clicks. For example, let’s run something when the mouse moves over an element.
<!DOCTYPE html>
<html>
<head>
<title>Hover Magic</title>
<style>
#box {
width: 200px;
height: 200px;
background-color: lightblue;
text-align: center;
line-height: 200px;
font-weight: bold;
}
</style>
</head>
<body>
<div id="box">Hover over me</div>
<script>
const box = document.getElementById('box');
box.addEventListener('mouseover', () => {
box.textContent = "🌟 You're hovering!";
box.style.backgroundColor = 'gold';
});
box.addEventListener('mouseout', () => {
box.textContent = "Hover over me";
box.style.backgroundColor = 'lightblue';
});
</script>
</body>
</html>
Here, we listen for the mouseover
event (when the mouse moves over the box) and the mouseout
event (when it leaves). This adds a fun visual effect and changes the text, which is great for interactive designs.
event.preventDefault()
If you ever need to stop an event from doing what it normally does — like stopping a form from submitting — you can use event.preventDefault()
.
<!DOCTYPE html>
<html>
<head>
<title>Prevent Submit</title>
</head>
<body>
<form id="loginForm">
<input type="text" placeholder="Username" required />
<button type="submit">Login</button>
</form>
<script>
const loginForm = document.getElementById('loginForm');
loginForm.addEventListener('submit', function(event) {
event.preventDefault();
alert('Form submission blocked for now.');
});
</script>
</body>
</html>
When the form is submitted, the event listener blocks it using event.preventDefault()
, and instead shows a custom alert. This is handy when you want to validate data before sending it or handle the submission with JavaScript instead of letting the browser reload the page.
These event methods give your web pages life and interactivity. Whether you’re listening for clicks, typing, or mouse moves, JavaScript lets you connect your code to user actions in a clean and powerful way.
Working with Dates
JavaScript’s Date
object is like a built-in calendar and clock. It helps you work with dates and times — perfect for birthdays, deadlines, timestamps, or showing today’s date on a page.
Creating a New Date
You start by creating a new date using:
const today = new Date();
.getDate()
, .getMonth()
, .getFullYear()
Then you can use different methods to get parts of the date:
const today = new Date();
console.log(`Today is: ${today.getDate()}/${today.getMonth() + 1}/${today.getFullYear()}`);
Here:
.getDate()
gives you the day of the month..getMonth()
gives you the month (0 for January, 11 for December), so we add+1
to get the correct human-friendly month..getFullYear()
gives you the full year like2025
.
.getDay()
Now let’s get the day of the week using .getDay()
:
const today = new Date();
const dayOfWeek = today.getDay();
console.log(dayOfWeek); // Outputs a number from 0 (Sunday) to 6 (Saturday)
If today is Monday, it will show 1
. You can use this with an array to show the name:
const today = new Date();
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
console.log(`It's ${days[today.getDay()]}`); // Outputs: It's Monday (or whichever day)
.getHours()
, .getMinutes()
, .getSeconds()
Want to get the current time? Use .getHours()
, .getMinutes()
, and .getSeconds()
:
const today = new Date();
const hours = today.getHours();
const minutes = today.getMinutes();
const seconds = today.getSeconds();
console.log(`Current time: ${hours}:${minutes}:${seconds}`);
This will print the current hour, minute, and second using your system’s clock.
Creating a Specific Date
You can also set a specific date and time by passing values to the Date()
constructor:
const birthday = new Date(1995, 2, 20); // March 20, 1995 (remember: 11 = December)
console.log(birthday.toDateString()); // Outputs: Mon Mar 20 1995
The format is: new Date(year, month, day)
. Just remember that months start at 0.
Creating a Date and Time Together
You can even create a date and time together:
const meeting = new Date(2025, 6, 20, 14, 30); // July 20, 2025, 2:30 PM
console.log(meeting.toString());
.setFullYear()
, .setMonth()
JavaScript also gives you methods to set parts of a date, like .setFullYear()
or .setMonth()
:
const eventDate = new Date();
eventDate.setFullYear(2030);
console.log(eventDate.getFullYear()); // Outputs: 2030
.toLocaleDateString()
, .toLocaleTimeString()
Lastly, to get a full readable string, try .toLocaleDateString()
and .toLocaleTimeString()
:
const today = new Date();
console.log(today.toLocaleDateString()); // Example: 7/14/2025
console.log(today.toLocaleTimeString()); // Example: 2:45:01 PM
These methods automatically format the date and time based on your system settings.
JavaScript’s Date
methods are great when you want to build timers, schedules, clocks, logs, or simply show the date in a nice way. Whether it’s checking if something is overdue or greeting users based on the time of day, the Date object has your back.
Combining Methods in Fun Examples
Let’s build a small interactive example that combines strings, arrays, and events. We’ll create a simple word collector where you enter a word, add it to a list, and show all words joined as a sentence.
<!DOCTYPE html>
<html>
<head>
<title>Word Collector</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
max-width: 400px;
margin: auto;
background-color: #f9f9f9;
}
input, button {
padding: 10px;
font-size: 16px;
margin-top: 10px;
width: 100%;
box-sizing: border-box;
}
p {
margin-top: 20px;
font-size: 18px;
color: #333;
}
</style>
</head>
<body>
<h2>Word Collector</h2>
<input id="wordInput" type="text" placeholder="Enter a word" />
<button id="addWord">Add Word</button>
<p id="sentence"></p>
<script>
const input = document.getElementById('wordInput');
const button = document.getElementById('addWord');
const sentence = document.getElementById('sentence');
let words = [];
button.addEventListener('click', () => {
let word = input.value.trim().toLowerCase();
if (word === "") {
alert("Please enter a word!");
return;
}
if (words.includes(word)) {
alert(`The word "${word}" is already added!`);
input.value = "";
return;
}
words.push(word);
input.value = "";
sentence.textContent = words.join(' ');
});
// Optional: Allow adding word by pressing Enter key
input.addEventListener('keyup', (event) => {
if (event.key === 'Enter') {
button.click();
}
});
</script>
</body>
</html>
Here, the user types words, which get converted to lowercase using .toLowerCase()
and stored in an array. Each time a word is added, the array joins into a sentence shown on the page.
Conclusion
JavaScript methods are essential tools that let beginners easily manipulate strings, arrays, numbers, objects, dates, and user interactions. By understanding how to use these built-in methods, you gain the power to write clear and engaging code that does more with less effort. Practicing these methods with fun examples like the word collector above can help you build confidence and unlock the potential of JavaScript.
References
If you want to learn more about JavaScript methods and how they work, these resources are excellent starting points:
- MDN Web Docs: String Methods
Great for understanding how to work with text in JavaScript. - MDN Web Docs: Array Methods
Learn how to add, remove, and search items in lists. - MDN Web Docs: Number Methods
Useful for formatting and working with numbers. - MDN Web Docs: Object Methods
Find out how to work with key-value pairs. - MDN Web Docs: Date
Learn to handle dates and times in JavaScript. - MDN Web Docs: EventTarget.addEventListener()
How to respond to user actions like clicks and keypresses.