Day 19/100 Day 10 of JavaScript Mastering String Methods in JavaScript In JavaScript, strings are sequences of characters used to represent text. But what makes them truly powerful are the built-in string methods that help us manipulate and analyze text efficiently. Let’s explore some of the most useful ones 1. length — Find String Length Returns the number of characters in a string. let name = "JavaScript"; console.log(name.length); // Output: 10 Useful when you need to validate input length, like passwords or usernames 2. toUpperCase() & toLowerCase() — Change Case Converts all characters to upper or lower case. let lang = "javascript"; console.log(lang.toUpperCase()); // JAVASCRIPT console.log(lang.toLowerCase()); // javascript Handy for case-insensitive comparisons. 3. includes() — Check if a Word Exists Checks if a string contains a specific substring. let sentence = "Learning JavaScript is fun!"; console.log(sentence.includes("JavaScript")); // true Perfect for search or filter functions. 4. indexOf() & lastIndexOf() — Find Positions Finds the index of the first or last occurrence of a substring. let text = "Hello JavaScript world!"; console.log(text.indexOf("JavaScript")); // 6 console.log(text.lastIndexOf("o")); // 19 Useful for locating specific patterns in strings. 5. slice() — Extract a Portion Extracts part of a string based on index range. let str = "JavaScript"; console.log(str.slice(0, 4)); // "Java" Often used to trim text or extract keywords. 6. replace() — Replace Text Replaces a substring with another. let msg = "I love JavaScript!"; console.log(msg.replace("JavaScript", "Python")); // "I love Python!" Useful for content formatting or dynamic text updates. 7. trim() — Remove Extra Spaces Removes whitespace from both ends of a string. let input = " Hello World! "; console.log(input.trim()); // "Hello World!" Essential for cleaning user input. 8. split() — Convert String to Array Splits a string into an array based on a delimiter. let fruits = "apple,banana,grape"; console.log(fruits.split(",")); // ["apple", "banana", "grape"] Commonly used when processing CSV data. 9. charAt() — Get Character by Index Returns the character at a specific index. let word = "Hello"; console.log(word.charAt(1)); // "e" 10. concat() — Join Multiple Strings Combines two or more strings. let first = "Hello"; let second = "World"; console.log(first.concat(" ", second)); // "Hello World" Alternative to using + for string concatenation. Quick Tip: All string methods return new strings — they don’t modify the original one since strings in JavaScript are immutable. Final Thought: Mastering string methods helps you handle text data like a pro — from formatting user inputs to processing dynamic content. #10000coders #JavaScript #WebDevelopment #CodingTips #LearnJavaScript #Developers #LinkedInLearning
"Mastering JavaScript String Methods: A Guide"
More Relevant Posts
-
Day 18/100 Day 9 of JavaScript Arrow Functions in JavaScript — A Modern & Cleaner Way to Write Functions In modern JavaScript (ES6+), arrow functions provide a shorter and more elegant way to write functions. They make your code concise and improve readability, especially when working with callbacks or array methods like .map(), .filter(), and .reduce(). What is an Arrow Function? An arrow function is simply a compact syntax for defining functions using the => (arrow) symbol. Syntax: const functionName = (parameters) => { // block of code }; It’s equivalent to: function functionName(parameters) { // block of code } Example: Traditional vs Arrow Function Traditional Function: function add(a, b) { return a + b; } console.log(add(5, 3)); // Output: 8 Arrow Function: const add = (a, b) => a + b; console.log(add(5, 3)); // Output: 8 Cleaner and shorter! Key Features of Arrow Functions : No function keyword — Makes your code concise. Implicit return — If the function body has only one statement, the result is automatically returned (no need for return). Lexical this binding — Arrow functions don’t have their own this. They inherit this from the parent scope — making them great for use inside callbacks or class methods. Example: Lexical this function Person() { this.name = "Appalanaidu"; setTimeout(() => { console.log(this.name); // Works perfectly! }, 1000); } new Person(); // Output: Appalanaidu If we had used a regular function inside setTimeout, this would be undefined or refer to the global object — not the instance. Arrow functions solve that issue neatly. Quick Recap Shorter syntax Implicit return Lexical this Great for callbacks Example Use Case: Array Mapping const numbers = [1, 2, 3, 4]; const squares = numbers.map(num => num * num); console.log(squares); // Output: [1, 4, 9, 16] Arrow functions make such one-liners elegant and easy to read! Final Thought Arrow functions are not just syntactic sugar — they’re a modern JavaScript feature that simplifies code and makes your logic cleaner. Once you start using them, you’ll rarely go back to the old way! #10000coders
To view or add a comment, sign in
-
🚀 JavaScript String Methods: Mastering Text Manipulation When working with strings in JavaScript, methods are your secret weapon! They help you transform, search, and manipulate text with ease. Whether you’re formatting user input or displaying dynamic content, knowing string methods will make your coding life much smoother. 🔤 What Are String Methods? String methods are built-in functions that allow you to perform operations on strings. Since strings are immutable (they can’t be changed directly), these methods return new strings instead of altering the original. ⚙️ Popular JavaScript String Methods Let’s explore some of the most commonly used string methods 👇 1. length – Returns the length of the string. let word = "JavaScript"; console.log(word.length); // 10 2. toUpperCase() / toLowerCase() – Converts text to uppercase or lowercase. console.log("hello".toUpperCase()); // "HELLO" console.log("WORLD".toLowerCase()); // "world" 3. indexOf() / lastIndexOf() – Finds the position of a substring. console.log("frontend".indexOf("end")); // 4 4. slice() / substring() / substr() – Extracts a portion of a string. console.log("developer".slice(0, 3)); // "dev" 5. replace() – Replaces part of a string with another string. console.log("I love CSS".replace("CSS", "JavaScript")); // "I love JavaScript" 6. includes() – Checks if a string contains a specific word. console.log("coding is fun".includes("fun")); // true 7. trim() – Removes whitespace from both ends of a string. console.log(" Hello World ".trim()); // "Hello World" 8. split() – Splits a string into an array. console.log("red,green,blue".split(",")); // ["red", "green", "blue"] 9. concat() – Joins two or more strings together. console.log("Hello".concat(" ", "World")); // "Hello World" 💡 Pro Tip Instead of concat(), you can use the + or template literals: let name = "Azeez"; console.log(`Hello, ${name}!`); // "Hello, Azeez!" #webdeveloper #javascript #followers
To view or add a comment, sign in
-
-
🌈 DAY 58 – JavaScript Arrays (21 Must Know Methods) 🚀🔥 Today I practiced JavaScript ARRAY Methods in depth and this topic is super important for Frontend Interviews + Real Project Coding. Why Arrays Matter? Arrays are used in 👉 API Data | JSON Parsing | UI Rendering | Filters | Searching | Sorting | Analytics 💡 21 Array Methods I learned Today (with simple understanding) 1️⃣ push() – Add element at END Syntax: array.push(value) 2️⃣ pop() – Remove LAST element Syntax: array.pop() 3️⃣ unshift() – Add element at START Syntax: array.unshift(value) 4️⃣ shift() – Remove FIRST element Syntax: array.shift() 5️⃣ indexOf() – Find index of element (first match) Syntax: array.indexOf(value) 6️⃣ lastIndexOf() – Find last matched index Syntax: array.lastIndexOf(value) 7️⃣ includes() – Check exists or not Syntax: array.includes(value) 8️⃣ length – Get Array size Syntax: array.length 9️⃣ slice() – returns NEW array (original not changed) Syntax: array.slice(start,end) 🔟 splice() – Add / Remove / Replace inside original array Syntax: array.splice(start,deleteCount,item/s) 11️⃣ concat() – Merge arrays (original not changed) Syntax: array.concat(array2) 12️⃣ toString() – Convert array → comma string Syntax: array.toString() 13️⃣ join() – Join using custom symbol Syntax: array.join("-") 14️⃣ map() – Transform elements → NEW array Syntax: array.map((element)=>{ return value }) 15️⃣ find() – Returns First element that matches condition Syntax: array.find((item)=> condition) 16️⃣ findIndex() – Returns index of first match Syntax: array.findIndex((item)=> condition) 17️⃣ sort() – Sort ASC / DESC Syntax: array.sort((a,b)=> a-b) 18️⃣ reverse() – Reverse order Syntax: array.reverse() 19️⃣ copyWithin() – Copy values inside same array Syntax: array.copyWithin(target,start,end) 20️⃣ flat() – Flatten nested arrays Syntax: array.flat(depth) 21️⃣ new Array() – Create array using constructor Syntax: new Array(value) 📌 What I Realized Today Professional Developers don’t write loops everywhere… They use correct Array Method → Clean Code → Faster Development → Less Bugs ✅ Day 58 Completed 💯 Consistency → Growth → Skill Upgrade 📈🔥 special thanks to Harish M,Bhagavathula Srividya,Manivardhan Jakka,Spandana Chowdary,10000 Coders #javascript #webdevelopment #frontenddeveloper #techlearning #jsarrays #codingjourney #100daysofcode #dailycoding #softwaredeveloper #interviewpreparation #webdevcommunity #learningeveryday #linkedinfamily #programmerlife #careerbuilding
To view or add a comment, sign in
-
The Object: The Organized Container of JavaScript 🗃️ In JavaScript, the Object is king. Everything that isn't a simple, raw value (like a number, text, or true/false) is treated as an Object. It's the primary way the language groups data and actions together to model real-world concepts, like a user, a car, or a settings menu. The Real-World Analogy: The Backpack 🎒 Think of a JavaScript Object as a Backpack. ⏩ It holds different items inside. ⏩ It has actions you can perform on it (like zipping it up or emptying it). The Two Parts of Every Object An Object is essentially a collection of key-value pairs, where the "key" is a label (a string) and the "value" is the actual data. These pairs are categorized into two types: 1. Properties (The Items Inside) Properties are the data or values an object holds. They describe the object. 👉 Concept: a. Property The items inside the backpack JavaScript Example: color: "red" b. Key (Name) Backpack Analogy: The label on the item's tag (e.g., brand). javaScript Example: brand c. Value Backpack Analogy: The actual item (e.g., "Nike"). javaScript Example: "Nike" 👉 How to Access: You access a property using dot notation or bracket notation. ⏩ myBackpack.brand ⏩ myBackpack["color"] 2 Methods (The Actions It Can Do) Methods are functions (actions) stored as properties within the object. They define what the object knows how to do. 👉 Concept Method Backpack Analogy:The ability to zip up the backpack or empty its contents JavaScript Example empty: function() { ... } 👉 How to Execute: You execute a method by following the object and method name with parentheses (). ✔️ myBackpack.empty() ➡️ JavaScript's Core Object Types JavaScript uses the Object structure for almost all complex data, which is why you see it everywhere: ➡️ Object Type 👉 Plain Object A single entity or configuration. Example : { name: "Shola", isAdmin: true } 👉 Array An ordered list of items. Examples: [10, 20, 30] (An Array is a special type of Object). 👉 Function A block of runnable code. Example: Functions are technically callable objects with properties. 👉 Date A specific point in time. Example: new Date() The Object and Inheritance The reason the Object is so fundamental is because of Inheritance. Every standard Object in JavaScript (unless explicitly disabled) has a secret link to an Object Prototype. ⏩ Analogy: The Backpack you bought is based on a blueprint (the Prototype). Even though you didn't define a toString() method for your backpack, it automatically inherits that method from the master Object Prototype, allowing it to display itself as a string if needed. This prototype chain is how JavaScript objects share common functionality, making the language incredibly flexible but also sometimes challenging to debug.
To view or add a comment, sign in
-
-
🍏 JavaScript Daily Bite #8: Understanding Constructors Prototypes allow us to reuse properties across multiple instances — especially for methods. Constructor functions take this further by automatically setting the [[Prototype]] for every object created. ⚙️ Constructor Functions Constructors are just functions called with the new operator. Every instance created from a constructor automatically inherits from its prototype property. Key Concepts Constructor.prototype becomes the [[Prototype]] of all instances Constructor.prototype.constructor references the constructor function itself Returning a non-primitive from a constructor overrides the default instance 🧩 Classes vs Constructor Functions ES6 classes are syntactic sugar over constructor functions — the underlying behavior is the same. You can still manipulate Constructor.prototype to modify behavior across all instances. 🔧 Mutating Prototypes Since all instances share the same prototype object, mutating it changes behavior for every instance. However, reassigning the entire Constructor.prototype object is problematic because: Older instances will still reference the old prototype The constructor link may be lost, breaking user expectations and built-in operations 🧱 Constructor Prototype vs Function Prototype Constructor.prototype is used when creating instances. It’s separate from Constructor.[[Prototype]], which points to Function.prototype. ⚙️ Implicit Constructors of Literals Literal syntaxes in JavaScript automatically set their [[Prototype]]: Object literals → Object.prototype Array literals → Array.prototype RegExp literals → RegExp.prototype This is why array methods like map() or filter() are available everywhere — they live on Array.prototype. 🚫 Monkey Patching Warning Extending built-in prototypes (e.g., Array.prototype) is dangerous because it: Risks forward compatibility if new methods are added to the language Can “break the web” by changing shared behavior The only valid reason is for polyfilling newer features safely. 🧬 Building Longer Inheritance Chains Constructor.prototype becomes the [[Prototype]] of instances — and that prototype itself can inherit from another. Default chain: instance → Constructor.prototype → Object.prototype → null To extend the chain, use Object.setPrototypeOf() to link prototypes explicitly. In modern syntax, this corresponds to class Derived extends Base. ⚠️ Avoid legacy patterns: Object.create() can build inheritance chains but reassigns prototype, removes constructor, and can introduce subtle bugs. ✅ Best practice: Mutate the existing prototype with Object.setPrototypeOf() instead. 🌱 Next in the Series → Functions & Prototypes: A Deeper Dive #JavaScript #WebDevelopment #Frontend #Programming #LearnToCode #TechEducation #SoftwareDevelopment #JSDailyBite
To view or add a comment, sign in
-
✍️ JavaScript Tip: Optional Chaining (?.) If you’ve ever tried accessing something deep inside an object and got an error like: Cannot read property 'x' of undefined You're not alone 😅 This happens a lot when you're not sure if a value exists. For example, you’re trying to access user.profile.picture.url, but profile might be missing or picture might not be there. Without checking every step, JavaScript throws an error and your app can crash ❌ It use to happen to me too🥲 I once ran into a bug while building a simple post form where users could optionally add tags through a tags input. Everything was working fine but form submission was slow. Then decided to optimize the image upload flow by compressing images on the front end and uploading them all at once to Cloudinary, which made the form submit faster. While testing, I filled only the required fields and left out the optional tags. That’s when the form crashed. The backend expected a string to split into an array, but since tags was undefined, calling .split(',') threw an error. A simple fix like tags?.split(',') || [] would’ve handled it safely. That’s when optional chaining really made sense to me. ✅ You might be wondering what optional chaining really does to safeguard your code. Let me explain😎 Optional chaining (?.) lets you safely access nested values without having to check each level manually. Instead of writing: if (user && user.profile && user.profile.picture) { // ... } You can simply write: user?.profile?.picture?.url If anything in that chain doesn’t exist (undefined or null), JavaScript just returns undefined instead of crashing 😌 🤔 What’s Really Happening When you use optional chaining (?.), JavaScript checks step by step: 1. Does the part before ?. exist? 2. If yes, it continues 3. If not, it stops and returns undefined It skips the rest of the chain once something is missing. No errors. No drama ✅ 😀 A Simple Example const user = { name: "Ferdinand" }; console.log(user?.profile?.email); // undefined, no error In this case, since profile doesn't exist, JavaScript doesn't even try to check email. It just returns undefined safely. 🔥 When You Should Use It ✅ When working with API data ✅ When reading optional user input ✅ When you’re unsure if certain data exists ✅ When accessing settings or config data It makes your code shorter, cleaner, and safer. ⚠️ But watch out Optional chaining only stops on undefined or null. If a value is false, 0, or an empty string (""), it continues as normal. Also, don’t use it everywhere blindly. It can hide bugs if you're not sure what should or shouldn't be optional 🤨
To view or add a comment, sign in
-
-
#CodingTips #BackendDevelopment #WebDevelopment #Nodejs #Expressjs #SoftwareEngineering #SoftwareDevelopment #Programming The reduce() is one of powerful #JavaScript method and also one of most confusing JavaScript method that even many developers sometimes misunderstand. the JavaScript reduce() method has many functionalities including: - It can be used for grouping objects within an array - It can be used for optimizing performance by replacing filter() method with reduce() in many circumstances - It can be used for summing an array - It can be used for flatten a list of arrays And many more. Of course I am not gonna explain it one by one. But here, I am gonna explain it to you generally, about how does reduce() method work in JavaScript? Now, let's take a look at the code snippet below. At the beginning of iterations, the accumulator (written with the sign {}) starts with the initial empty object. It's just {} (an empty object). While the currentItem is the object with the data inside like: {car_id: 1, etc}. Assume currentItem is: {car_id: 1, etc}, then when below code is executed: if (acc[currentItem.car_id]) Its like the accumulator {} will check if the currentItem.car_id, which is 1 is exist or not?. But because at the beginning is just only {} (an empty object), then it will execute the code below: acc[currentItem.car_id] = [currentItem]; It means it will generate a group of current car_id 1 with its object data, related to car id 1. So, the accumulator becoming like this: { 1: [ // coming from acc[currentItem.car_id {car_id: 1, etc} // coming from currentItem ] } And looping... Still looping until it will check again if acc[currentItem.car_id] (which is car_id is 1 for example) is exist. Because it exist, then acc[currentItem.car_id].push(currentItem); So the result will be like below: { 1: [ {car_id: 1, etc} // coming from currentItem {car_id: 1, etc} // new coming from current item ] } And it always iterate all the data until reach out the end of records. And once it's done, the final result will be like below: { 1: [ {car_id: 1, etc} {car_id: 1, etc} ], 2: [ {...}, {...}, ... ] 3: [ {...}, {...}, ... ] ... } I hope this explanation helps you to understand how JavaScript reduce() method works? Back then, I had a nightmare and difficulties to understand it, but when I know it, I started to realize how powerful it is.
To view or add a comment, sign in
-
-
Types of Errors in JavaScript: * JavaScript is a powerful language, but even a small mistake can lead to unexpected errors. * Understanding these errors helps us debug faster and write cleaner code. Here are the 5 main types of errors in JavaScript: 1. Syntax Error Definition: * Occurs when the code is written incorrectly and JavaScript cannot understand it. * It happens before execution (during parsing). Example: console.log("Hello World" // Missing parenthesis Error Message: * Uncaught SyntaxError: missing ) after argument list Explanation: * JS expected a ) but didn’t find one. These are simple typos that break code instantly. 2. Reference Error Definition: * Occurs when trying to access a variable that doesn’t exist or is out of scope. Example: console.log(name); // name not defined Error Message: * Uncaught ReferenceError: name is not defined Explanation: * This means JS cannot find the variable in memory. * Always declare variables before using them! 3. Type Error Definition: * Occurs when a value is not of the expected type, or a property/method doesn’t exist on that type. Example: let num = 10; num.toUpperCase(); // Not valid on numbers Error Message: * Uncaught TypeError: num.toUpperCase is not a function Explanation: * Only strings can use .toUpperCase(). * TypeErrors often happen due to wrong variable usage. 4. Range Error Definition: Occurs when a number or value is outside its allowed range. Example: let arr = new Array(-5); // Negative length not allowed Error Message: * Uncaught RangeError: Invalid array length Explanation: * Array sizes must be non-negative. * You’ll see this error when loops, recursion, or array sizes go beyond limits. 5. URI Error Definition: * Occurs when using encodeURI() or decodeURI() incorrectly with invalid characters. Example: decodeURI("%"); // Invalid escape sequence Error Message: * Uncaught URIError: URI malformed Explanation: * URI (Uniform Resource Identifier) functions expect valid encoded URLs. * Always validate URLs before decoding! Conclusion * Errors are not your enemies—they’re your best teachers. * By understanding these core JavaScript errors, you’ll spend less time debugging and more time building awesome things. KGiSL MicroCollege #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #LearnToCode #JS #ErrorHandling #CodeNewbie #SoftwareEngineering #WebDesign #Developers #CodeTips #ProgrammingLife #CleanCode #WebApp #DeveloperCommunity #CodeDaily #BugFixing #JSDeveloper #TechCommunity #100DaysOfCode #WomenInTech #FullStackDeveloper #FrontendDeveloper #SoftwareDeveloper #CodingJourney #TechLearning #CodeBetter #TechEducation
To view or add a comment, sign in
-
-
#4 Just wrapped up an intense session on the backbone of JavaScript: Arrays and Objects. These aren't just data structures; they're the building blocks for everything we do. Here’s a quick rundown of my key takeaways: JavaScript Deep Dive: Taming Arrays & Objects! 🚀 📌 Arrays: The Ordered Lists More than just [1, 2, 3], arrays are powerhouses with methods that can make or break your code. The Mutable vs. Immutable Showdown: slice(): The polite one. It takes a copy of a section without disturbing the original. splice(): The disruptive one. It removes/replaces elements in the original array. (A classic interview question! ✅) Combining Arrays: Forget push(array) which creates nested arrays! Use concat() or the more modern Spread Operator ... to cleanly merge arrays. Powerful Prototypes: Methods like Array.from() to create arrays from array-like objects (like a string) and flat() to flatten nested arrays are game-changers. 📌 Objects: The Key-Value Kings Objects store structured data, and mastering them is non-negotiable. Two Ways to Create: Object Literals: const obj = { key: 'value' } (Most common) Constructor: Object.create() (Creates a singleton) Constructor method with new Object() Accessing Properties: You can use dot notation (obj.key) or bracket notation (obj["key"]). Bracket notation is essential for keys with spaces or dynamically generated keys. Symbol as a Key: You can use a Symbol for a unique, non-enumerable property key. A hidden gem for defining special properties. Object.freeze() vs. Object.seal(): - freeze(): Makes an object immutable. No changes, additions, or deletions. - seal(): Allows modification of existing properties, but prevents adding or removing new ones. 🔥 Leveling Up: Higher-Order Functions & Destructuring Array Methods that Shine: - map(): Transform each element. (Create a new array of doubled values). - filter(): Select elements based on a condition. - reduce(): Boil down the array to a single value (like a sum). - forEach(): Execute a function for each element (but doesn't return a new array like map). Destructuring Magic: This is a syntax superpower! - Arrays: const [first, second] = myArray - Objects: const { name, email } = userObject It makes code incredibly clean and readable, especially in function parameters and React props. 💡 The Big Revelation: Understanding the difference between shallow copy and deep copy is crucial when working with these structures to avoid unintended side effects. It's amazing how much power is packed into these fundamentals. The more you learn, the more you realize how elegant and powerful JavaScript can be. What's your favorite JavaScript array or object method? Any "aha!" moments when you first understood destructuring? Share below! 👇 #JavaScript #Programming #WebDevelopment #Coding #LearnToCode #SoftwareEngineering #Arrays #Objects #Destructuring #LinkedInLearning #Tech
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development