DEV Community

Cover image for 22 JavaScript Functions You'll Use 99% of The Time 💯🔥
Arjun Vijay Prakash
Arjun Vijay Prakash

Posted on

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

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!");
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!');
});
Enter fullscreen mode Exit fullscreen mode

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"}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!"
Enter fullscreen mode Exit fullscreen mode

🙌 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: Linktree.

Happy Coding! 🚀
Thanks for 22097! 🤗

Top comments (20)

Collapse
 
moopet profile image
Ben Sinclair

I don't know how much I'm like your "average" JS developer since it's not a main part of my job.

As a single data point, while I use most of these, I never (or almost never) use these:

  • setInterval
  • setTimeout
  • reduce
  • reverse
  • isArray
Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

Of all of these, the only thing I don't use a lot is reverse, though it appears in my code in several places. I think you end up with these more often when you use JS on the front and back end.

The one I use a ton and isn't here is flat and occasionally flatMap.

Collapse
 
ludamillion profile image
Luke Inglis

I was going to post basically the same list. :)

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Agree! These are simple functions that make the development easier but yes, few of them are not really useful, it really depends from dev to dev.

Thanks for the comment!

Collapse
 
lexlohr profile image
Alex Lohr

I'm missing String.prototype.replace. Regular expressions are regularly helpful, especially with a replacer function.

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Yeah! I'll make sure I add them in the second part, Thanks!

Collapse
 
patzi275 profile image
Patrick Zocli

It's a pleasure to read you

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Thanks for the comment, Patrick! I appreciate those kind words.

Collapse
 
bjoentrepreneur profile image
Bjoern

Nice cheat sheet. Thanks for taking the time and posting this

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Welcome!

Collapse
 
masekere profile image
Gift Masekere

it seems l had forgotten to use splice(), thank you for posting,

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

My pleasure!

Collapse
 
krakoss profile image
krakoss

very useful information Thank you very much for this article

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

I'm glad you liked it!

Collapse
 
jeffchavez_dev profile image
Jeff Chavez

Thanks for this. These functions are helpful.

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

My pleasure!

Collapse
 
ivan20121 profile image
Ivan

Awesome! Thank you! Good work

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

I'm glad it was helpful!

Collapse
 
terabytetiger profile image
Tyler V. (he/him)

Solid list 👍🏻

I was expecting to see at least 1 that I had never used before, but I use all of these fairly frequently.

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Of course, you'll use them 99% of the time. By the way, thanks for the insight, I'll make sure to include some interesting ones in my coming posts!

Thanks!