Posts

Showing posts with the label JavaScript for Beginners

๐Ÿง  How to Use indexOf() in JavaScript – Complete Guide with Examples

Image
๐Ÿ” What is indexOf() in JavaScript? The indexOf() method in JavaScript is used to find the position (index) of a specific element within a string or array . If the item is not found, it returns -1 . ๐Ÿงช Syntax For Strings: string.indexOf(searchValue, startIndex) For Arrays: array.indexOf(searchElement, fromIndex) ๐Ÿ“˜ How indexOf() Works in Strings const text = "JavaScript is amazing"; console.log(text.indexOf("Script")); // Output: 4 ✅ Case Sensitivity: console.log(text.indexOf("script")); // Output: -1 Note: indexOf() is case-sensitive. ๐Ÿ” Finding the First Occurrence const sentence = "I love JavaScript because JavaScript is fun!"; console.log(sentence.indexOf("JavaScript")); // Output: 7 ๐Ÿ•ต️‍♂️ Find All Occurrences in a String const str = "JS is cool. JS is powerful. JS is everywhere!"; let index = str.indexOf("JS"); while (index !== -1) { console.log("Found at:", index); ...

๐Ÿง  Master JavaScript's map(), filter(), and reduce() Methods with Easy Examples!

Image
๐Ÿง  Understanding map() , filter() & reduce() in JavaScript - Simplified! JavaScript offers powerful array methods to work with data efficiently. Among them, the trio of map() , filter() , and reduce() are must-know tools for every developer. This guide will break them down with simple examples that you can copy and run in your browser or code editor. ๐Ÿ” map() – Transform Every Element The map() method creates a new array by transforming each element of the original array. const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled); // Output: [2, 4, 6, 8] ๐Ÿ’ก Use map() when you want to apply a function to each item and return a new array. ๐Ÿ” filter() – Keep What You Need The filter() method returns a new array containing elements that match a condition. const numbers = [1, 2, 3, 4, 5]; const even = numbers.filter(num => num % 2 === 0); console.log(even); // Output: [2, 4] ๐Ÿ’ก Use fil...