There are numerous functions in JavaScript that every developers should master.
Here's a list of ten functions:
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');
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
});
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));
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);
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);
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);
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);
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);
Checks if a given value is an array
const arr = [1, 2, 3];
if (Array.isArray(arr)) {
console.log('It is an array');
}
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));