10 JS Functions You Can't Ignore

10 JS Functions You Can't Ignore

There are numerous functions in JavaScript that every developers should master.

Here's a list of ten functions:

  1. querySelector and querySelectorAll
  • querySelector: returns the first element that matches a specified CSS selector.

  • querySelectorAll: returns a NodeList representing a list of elements that match the specified group of selectors.

const element = document.querySelector('#myId');
const elements = document.querySelectorAll('.myClass');
  1. addEventListener

Allows developers to listen for events on DOM elements and execute a function in response to those events.

const button = document.getElementById('myButton');
button.addEventListener('click', function() {
    // do something when the button is clicked
});
  1. fetch

Used to make network requests (fetching data from an API) and handle responses using Promises.

fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
  1. map

Creates a new array by applying a function to each element of an existing array.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
  1. filter

Creates a new array with all elements that pass the test implemented by the provided function.

const numbers = [1, 2, 3, 4];
const evens = numbers.filter(num => num % 2 === 0);
  1. reduce

applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
  1. setTimeout and setInterval
  • setTimeout: Executes a function after a specified delay (in milliseconds).

  • setInterval: Calls a function at specified intervals (in milliseconds).

setTimeout(() => {
    console.log('Delayed function executed');
}, 1000);

setInterval(() => {
    console.log('Function called every second');
}, 1000);
  1. JSON.parse and JSON.stringify
  • JSON.parse: Parses a JSON string and returns a JavaScript object.

  • JSON.stringify: Converts a JavaScript object or value to a JSON string.

const jsonStr = '{"key": "value"}';
const obj = JSON.parse(jsonStr);

const obj = { key: 'value' };
const jsonString = JSON.stringify(obj);
  1. Array.isArray

Checks if a given value is an array

const arr = [1, 2, 3];
if (Array.isArray(arr)) {
    console.log('It is an array');
}
  1. Promise

represents the eventual completion or failure of an asynchronous operation and its resulting value.

const fetchData = () => {
    return new Promise((resolve, reject) => {
        // asynchronoous oparetion
        if (success) {
            resolve('Data successfully fetched');
        } else {
            reject('Error fetching data');
        }
    });
};

fetchData()
    .then(data => console.log(data))
    .catch(error => console.error(error));

Keep in mind that the choice of functions may vary depending on the specific requirements of a project.