22 JavaScript Functions You’ll Use 99% of The Time 💯🔥

Rmag Breaking News

The functions that follow are fundamental to web development and javascript programming in general, simplifying tasks such as debugging ** using the old and new console.log(), **manipulating the DOM, and handling JSON data.

Knowing and using these functions is like building the backbone of the fundamentals of this language.

Mastering these tools will also surely streamline the coding process resulting in a good developer experience.

TL;DR

Console and Debugging
-> console.log(…args)

Timing
-> setTimeout(callback, delay)
-> setInterval(callback, interval)

DOM Manipulation and Event Handling
-> querySelectorAll(selector)
-> addEventListener(event, callback)

JSON Handling
-> JSON.parse(jsonString)
-> JSON.stringify(object)

Array Manipulation (Higher-Order Functions)
-> forEach(callback)
-> map(callback)
-> filter(callback)
-> reduce(callback, initialValue)

Array Operations
-> slice(start, end)
-> splice(start, deleteCount, …items)
-> indexOf(element)
-> includes(element)
-> sort(compareFunction)
-> reverse()
-> isArray(value)

String Manipulation
-> split(separator)
-> join(separator)
-> toLowerCase(), toUpperCase()
-> trim()

Console and Debugging:
0️⃣1️⃣ console.log(…args)
⇒ Outputs messages or objects to the console for debugging purposes.

// console.log(…args)

console.log(“Hello World!”);

Timing:
0️⃣2️⃣ setTimeout(callback, delay)
⇒ Executes a function after a specified delay in milliseconds.

0️⃣3️⃣ setInterval(callback, interval)
⇒ Repeatedly executes a function at specified intervals.

// setTimeout(callback, delay)

setTimeout(function() {
console.log(“This message will appear after 3 seconds.”);
}, 3000);
// Runs the anonymous function after 3000 milliseconds (3 seconds)

// setInterval(callback, interval)

function printCounter() {
let count = 0;
setInterval(function() {
console.log(“Count:”, count++);
}, 1000);
}

printCounter(); // Prints count every second

DOM Manipulation and Event Handling:
0️⃣4️⃣ querySelectorAll(selector)
⇒ Returns a NodeList containing all the elements that match the specified selector.

0️⃣5️⃣ addEventListener(event, callback)
⇒ Attaches an event handler function to an HTML element.

// querySelectorAll(selector)
console.log(“querySelectorAll(selector)”);
const container = document.getElementById(‘container’);
const links = container.querySelectorAll(‘a’);
// Accessing the href attribute of each link

// Iterate over the NodeList
links.forEach(link => {
console.log(link.href);
});

// addEventListener(event, callback)
console.log(“addEventListener(event, callback)”);
const button = document.getElementById(‘myButton’);

button.addEventListener(‘click’, function() {
console.log(‘Button clicked!’);
});

JSON Handling:
0️⃣6️⃣ JSON.parse(jsonString)
⇒ Parses a JSON string and returns a JavaScript object.

0️⃣7️⃣ JSON.stringify(object)
⇒ Converts a JavaScript object into a JSON string.

// JSON.parse(jsonString)
console.log(“JSON.parse(jsonString)”);
const jsonString = ‘{“name”: “John”, “age”: 30, “city”: “New York”}’;
const jsonObject = JSON.parse(jsonString);

console.log(jsonObject.name);
// Output: John
console.log(jsonObject.age);
// Output: 30
console.log(jsonObject.city);
// Output: New York

// JSON.stringify(object)
console.log(“JSON.stringify(object)”);
const person = { name: ‘John’, age: 30, city: ‘New York’ };
const jsonString2 = JSON.stringify(person);

console.log(jsonString2);
// Output: {“name”:”John”,”age”:30,”city”:”New York”}

Array Manipulation (Higher-Order Functions):
0️⃣8️⃣ forEach(callback)
⇒ Executes a provided function once for each array element.

0️⃣9️⃣ map(callback)
⇒ Creates a new array with the results of calling a provided function on every element.

1️⃣0️⃣ filter(callback)
⇒ Creates a new array with elements that satisfy a provided condition.

1️⃣1️⃣ reduce(callback, initialValue)
⇒ Reduces an array to a single value by applying a function for each element.

const numbers = [1, 2, 3, 4, 5];

// forEach(callback)
console.log(“forEach:”);
numbers.forEach(num => {
console.log(num);
});

// Output:
// 1
// 2
// 3
// 4
// 5

// map(callback)
const doubledNumbers = numbers.map(num => num * 2);
// Output: [2, 4, 6, 8, 10]

// filter(callback)
const evenNumbers = numbers.filter(num => num % 2 === 0);
// [2, 4]

// reduce(callback, initialValue)
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
// 15

Array Operations:
1️⃣2️⃣ slice(start, end)
⇒ Returns a shallow copy of a portion of an array between specified start and end indices.

1️⃣3️⃣ splice(start, deleteCount, …items)
⇒ Changes the array content by removing/replacing elements and/or adding new elements.

1️⃣4️⃣ indexOf(element)
⇒ Returns the first index at which a given element can be found in the array, or -1 if not present.

1️⃣5️⃣ includes(element)
⇒ Determines whether an array includes a certain element, returning true or false.

1️⃣6️⃣ sort(compareFunction)
⇒ Sorts the elements of an array based on the provided function or default sorting order.

1️⃣7️⃣ reverse()
⇒ Reverses the order of the elements in an array.

1️⃣8️⃣ isArray(value)
⇒ Checks if a given value is an array, returning true or false.

// slice(start, end)
const array = [1, 2, 3, 4, 5];
const slicedArray = array.slice(1, 4);
console.log(“slice:”, slicedArray);
// Output: [2, 3, 4]

// splice(start, deleteCount, …items)
const spliceArray = [1, 2, 3, 4, 5];
spliceArray.splice(2, 2, ‘a’, ‘b’);
console.log(“splice:”, spliceArray);
// Output: [1, 2, “a”, “b”, 5]

// indexOf(element)
const indexOfArray = [‘apple’, ‘banana’, ‘cherry’];
const indexOfCherry = indexOfArray.indexOf(‘cherry’);
console.log(“indexOf:”, indexOfCherry);
// Output: 2

// includes(element)
const includesArray = [1, 2, 3, 4, 5];
const includesValue = includesArray.includes(3);
console.log(“includes:”, includesValue);
// Output: true

// sort(compareFunction)
const sortArray = [3, 1, 4, 1, 5];
sortArray.sort((a, b) => a – b);
console.log(“sort:”, sortArray);
// Output: [1, 1, 3, 4, 5]

// reverse()
const reverseArray = [‘a’, ‘b’, ‘c’, ‘d’];
reverseArray.reverse();
console.log(“reverse:”, reverseArray);
// Output: [‘d’, ‘c’, ‘b’, ‘a’]

// isArray(value)
const isArrayValue = [1, 2, 3];
const isArray = Array.isArray(isArrayValue);
console.log(“isArray:”, isArray);
// Output: true

String Manipulation:
1️⃣9️⃣ split(separator)
⇒ Splits a string into an array of substrings based on a specified separator.

2️⃣0️⃣ join(separator)
⇒ Joins all elements of an array into a string, separated by the specified separator.

2️⃣1️⃣ toLowerCase(), toUpperCase()
⇒ Converts a string to lowercase or uppercase.

2️⃣2️⃣ trim()
⇒ Removes whitespace from both ends of a string.

// split(separator)
const sentence = “Hello, world! How are you?”;
const words = sentence.split(‘ ‘);
console.log(“split:”, words);
// Output: [“Hello,”, “world!”, “How”, “are”, “you?”]

// join(separator)
const fruits = [‘Apple’, ‘Banana’, ‘Orange’];
const fruitString = fruits.join(‘, ‘);
console.log(“join:”, fruitString);
// Output: “Apple, Banana, Orange”

// toLowerCase(), toUpperCase()
const mixedCase = “Hello WoRLd”;
const lowerCase = mixedCase.toLowerCase();
const upperCase = mixedCase.toUpperCase();
console.log(“toLowerCase:”, lowerCase);
// Output: “hello world”
console.log(“toUpperCase:”, upperCase);
// Output: “HELLO WORLD”

// trim()
const stringWithWhitespace = ” Hello, world! “;
const trimmedString = stringWithWhitespace.trim();
console.log(“trim:”, trimmedString);
// Output: “Hello, world!”

🙌 Final Thoughts

As we wrap up our discussion the above functions, I ask you to share your insights.

What other functions do you find all necessary in your web development or mainly JavaScript projects?

Don’t hesitate to share your thoughts and useful functions in the comments below!

I hope you liked the article! ❤️

Connect with me: LinkedIn.

Explore my YouTube Channel! If you find it useful.

Please give my GitHub Projects a star ⭐️

Happy Coding! 🚀
Thanks for 22097! 🤗

Leave a Reply

Your email address will not be published. Required fields are marked *