Common Methods Every Developer Should Know
JavaScript is a versatile programming language that is used extensively in web development. As a developer, it's essential to be familiar with common JavaScript methods to write efficient and clean code. In this cheatsheet, we'll cover some of the most commonly used methods in JavaScript.String Methods
1. toUpperCase() and toLowerCase()
These methods allow you to convert a string to uppercase or lowercase, respectively.
const text = "Hello, World!";
const upperCaseText = text.toUpperCase(); // "HELLO, WORLD!"
const lowerCaseText = text.toLowerCase(); // "hello, world!"
2. trim()
trim() removes whitespace from both ends of a string.
const text = " Hello, World! ";
const trimmedText = text.trim(); // "Hello, World!"
3. split()
split() divides a string into an array of substrings based on a specified delimiter.
const text = "apple,banana,cherry";
const fruits = text.split(","); // ["apple", "banana", "cherry"]
Array Methods
1. push() and pop()
push() adds elements to the end of an array, while pop() removes and returns the last element.
const fruits = ["apple", "banana"];
fruits.push("cherry"); // ["apple", "banana", "cherry"]
const removedFruit = fruits.pop(); // "cherry"
2. forEach()
forEach() executes a provided function once for each array element.
const numbers = [1, 2, 3];
numbers.forEach((number) => {
console.log(number); // 1, 2, 3
});
3. map()
map() creates a new array by applying a function to each element of an existing array.
const numbers = [1, 2, 3];
const doubledNumbers = numbers.map((number) => number \* 2); // [2, 4, 6]
Object Methods
1. hasOwnProperty()
hasOwnProperty() checks if an object has a specific property.
const person = { name: "John", age: 30 };
const hasName = person.hasOwnProperty("name"); // true
const hasAddress = person.hasOwnProperty("address"); // false
2. keys()
keys() returns an array of an object's property names.
const person = { name: "John", age: 30 };
const properties = Object.keys(person); // ["name", "age"]
3. values()
values() returns an array of an object's property values.
const person = { name: "John", age: 30 };
const values = Object.values(person); // ["John", 30]
Conclusion
These are just a few of the many methods available in JavaScript. By mastering these common methods, you'll be well-equipped to work with strings, arrays, and objects effectively in your JavaScript projects. Take the time to practice and explore these methods further to become a more proficient JavaScript developer.