How to Use Common JavaScript Functions with Practical Examples image

How to Use Common JavaScript Functions with Practical Examples

Facebook
Twitter
LinkedIn
WhatsApp
Email

Table of Contents

In the world of web development, mastering JavaScript is essential for building dynamic and interactive applications. To become proficient, it’s crucial to understand how to use common JavaScript functions effectively. Functions like map, filter, and reduce are the building blocks of modern JavaScript programming, allowing you to manipulate arrays and objects with ease. In this guide, we’ll explore these and other essential JavaScript functions through practical examples, helping you to apply them in real-world scenarios.

1. console.log(...args)

Purpose: Outputs messages or objects to the console for debugging purposes.

Example:

javascript
console.log('Hello, World!'); console.log({ name: 'John', age: 30 });

2. setTimeout(callback, delay)

Purpose: Executes a function after a specified delay in milliseconds.

Example:

javascript
setTimeout(() => { console.log('This message appears after 2 seconds'); }, 2000);

Output (after 2 seconds):

This message appears after 2 seconds

3. setInterval(callback, interval)

Purpose: Repeatedly executes a function at specified intervals in milliseconds.

Example:

javascript
let counter = 0; const intervalId = setInterval(() => { console.log('Counter:', counter++); if (counter > 5) { clearInterval(intervalId); // Stops the interval after 5 iterations } }, 1000);

Output (every second):

makefile

Counter: 0 Counter: 1 Counter: 2 Counter: 3 Counter: 4 Counter: 5

4. querySelectorAll(selector)

Purpose: Returns a NodeList containing all elements that match the specified CSS selector.

Example:

javascript
// HTML: <p class="text">First paragraph</p> <p class="text">Second paragraph</p> const paragraphs = document.querySelectorAll('.text'); paragraphs.forEach((p) => console.log(p.textContent));

Output:

sql

First paragraph Second paragraph

5. addEventListener(event, callback)

Purpose: Attaches an event handler function to an HTML element.

Example:

javascript
document.querySelector('button').addEventListener('click', () => { console.log('Button was clicked!'); });

Output: (When the button is clicked)

css

Button was clicked!

6. JSON.parse(jsonString)

Purpose: Parses a JSON string and returns a JavaScript object.

Example:

javascript
const jsonString = '{"name": "Alice", "age": 25}'; const user = JSON.parse(jsonString); console.log(user.name); // Outputs: Alice

7. JSON.stringify(object)

Purpose: Converts a JavaScript object into a JSON string.

Example:

javascript
const user = { name: "Alice", age: 25 }; const jsonString = JSON.stringify(user); console.log(jsonString); // Outputs: '{"name":"Alice","age":25}'

 

8. forEach(callback)

Purpose: Executes a provided function once for each array element.

Example:

javascript
const numbers = [1, 2, 3]; numbers.forEach((num) => console.log(num * 2));

Output:

2 4 6

9. map(callback)

Purpose: Creates a new array with the results of calling a provided function on every element.

Example:

javascript
const numbers = [1, 2, 3]; const doubled = numbers.map((num) => num * 2); console.log(doubled); // Outputs: [2, 4, 6]

 

10. filter(callback)

Purpose: Creates a new array with elements that satisfy a provided condition.

Example:

javascript
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter((num) => num % 2 === 0); console.log(evenNumbers); // Outputs: [2, 4]

 

11. reduce(callback, initialValue)

Purpose: Reduces an array to a single value by applying a function for each element.

Example:

javascript
const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((accumulator, current) => accumulator + current, 0); console.log(sum); // Outputs: 10

 

12. slice(start, end)

Purpose: Returns a shallow copy of a portion of an array between specified start and end indices.

Example:

javascript
const numbers = [1, 2, 3, 4, 5]; const sliced = numbers.slice(1, 4); console.log(sliced); // Outputs: [2, 3, 4]

 

13. splice(start, deleteCount, ...items)

Purpose: Changes the array content by removing/replacing elements and/or adding new elements.

Example:

javascript
const numbers = [1, 2, 3, 4, 5]; numbers.splice(2, 1, 10); // Removes 1 element at index 2 and adds 10 console.log(numbers); // Outputs: [1, 2, 10, 4, 5]

 

14. indexOf(element)

Purpose: Returns the first index at which a given element can be found in the array, or -1 if not present.

Example:

javascript
const numbers = [1, 2, 3, 4, 5]; console.log(numbers.indexOf(3)); // Outputs: 2 console.log(numbers.indexOf(6)); // Outputs: -1

15. includes(element)

Purpose: Determines whether an array includes a certain element, returning true or false.

Example:

javascript
const numbers = [1, 2, 3, 4, 5]; console.log(numbers.includes(3)); // Outputs: true console.log(numbers.includes(6)); // Outputs: false

 

16. sort(compareFunction)

Purpose: Sorts the elements of an array based on the provided function or default sorting order.

Example:

javascript
const numbers = [5, 3, 8, 1]; numbers.sort((a, b) => a - b); // Sorts in ascending order console.log(numbers); // Outputs: [1, 3, 5, 8]

 

17. reverse()

Purpose: Reverses the order of the elements in an array.

Example:

javascript
const numbers = [1, 2, 3]; numbers.reverse(); console.log(numbers); // Outputs: [3, 2, 1]

 

18. isArray(value)

Purpose: Checks if a given value is an array, returning true or false.

Example:

javascript
console.log(Array.isArray([1, 2, 3]));
// Outputs: true console.log(Array.isArray("Hello"));
// Outputs: false


These examples demonstrate how to use each of these common JavaScript functions in practical scenarios. Understanding and applying these functions will help you become more proficient in JavaScript programming.

Leave a Comment

Related Blogs

Scroll to Top