Many developers assume slice() and substring() in JavaScript are interchangeable. They’re not. While both extract parts of a string, their edge-case behavior is very different - and misunderstanding this can lead to subtle bugs in production code. 🔹 slice(start, end) ✔ Supports negative indexes ✔ Does NOT swap arguments ✔ More predictable and modern Examples: "Hello World".slice(0, 5) // "Hello" "Hello World".slice(-5) // "World" "Hello World".slice(5, 0) // "" 🔹 substring(start, end) ❌ Negative indexes treated as 0 ✔ Automatically swaps arguments Examples: "Hello World".substring(0, 5) // "Hello" "Hello World".substring(-5) // "Hello World" "Hello World".substring(5, 0) // "Hello" (auto-swapped) Professional takeaway: In modern JavaScript development, slice() is generally the safer and more explicit choice. Rule of thumb: When in doubt, prefer slice(). If you're preparing for interviews or writing clean production code, this small distinction matters more than you think. #JavaScript #WebDevelopment #Frontend #CodingTips
JavaScript slice() vs substring() differences
More Relevant Posts
-
Day 15: The this Keyword in JavaScript this is one of the most misunderstood concepts in JavaScript 🤯 Its value depends on HOW a function is called, not where it is written. 🔹 1️⃣ Global Scope console.log(this); 👉 In browser → window 👉 In Node → {} (module.exports) 🔹 2️⃣ Inside a Regular Function function show() { console.log(this); } show(); 👉 In non-strict mode → window 👉 In strict mode → undefined 🔹 3️⃣ Inside an Object Method const user = { name: "Shiv", greet: function() { console.log(this.name); } }; user.greet(); 👉 this refers to the object → user 🔹 4️⃣ Arrow Function const user = { name: "Shiv", greet: () => { console.log(this); } }; user.greet(); 👉 Arrow functions do NOT have their own this 👉 They inherit from their lexical scope 🔥 Key Rule this depends on: ✔️ How the function is called ✔️ Whether it’s arrow or regular ✔️ Strict mode 🧠 Why Important? ✔️ Core interview topic ✔️ Important in React ✔️ Needed for call, apply, bind #JavaScript #thisKeyword #Frontend #Webdevelopment #learnInPublic
To view or add a comment, sign in
-
🔍 Understanding ‘this’ and window in JavaScript Many JavaScript developers get confused about how ‘this’ relates to the window object. Here’s a simple breakdown: 👉 In the global scope: ‘this’ refers to the global object. In browsers, the global object is window. Eg: console.log(this === window); // true 👉 Inside a regular function: ‘this’ still points to window (in non-strict mode). Eg: function show() { console.log(this); } show(); // window 👉 Inside an object method: ‘this’ refers to the object that calls the method. Eg: const user = { name: "Jim", greet() { console.log(this.name); } }; user.greet(); // Jim 👉 Inside an arrow function: Arrow functions don’t have their own ‘this’. They inherit ‘this’ from the surrounding scope. Eg: const obj = { name: "Jim", greet: () => { console.log(this.name); } }; obj.greet(); // undefined (this is window) 💡 Key Takeaway: • window is the global object in browsers • ‘this’ depends on how a function is called • Arrow functions inherit this #JavaScript #WebDevelopment #Frontend #Coding
To view or add a comment, sign in
-
Most JavaScript developers use objects every day without knowing how they truly work under the hood. ⚙️ When we define a property like obj.name = 'Alex', we assume it's just a simple key-value pair. But JavaScript is implicitly creating a "Property Descriptor" — a hidden set of configuration flags that define how that property behaves. In 2026, master engineers use these descriptors to build robust, library-grade architectures that prevent misuse. THE "HIDDEN WORLD" OF YOUR OBJECTS: Every property has attributes you rarely see, but can control via Object.defineProperty(): 🔹 writable: false — Makes a property read-only. Essential for protecting constants or configurations post-initialization. 🔹 enumerable: false — Hides properties from loops (for...in) and Object.keys(). This is how framework authors attach metadata to objects without polluting your iterations. 🔹 configurable: false — The ultimate lockdown. It prevents the property from being deleted or having its descriptors changed again. WHY THIS MATTERS BEYOND THEORY: If you are building shared components, core utilities, or managing complex state, you can't rely on other developers "just knowing" not to mutate a critical setting. By explicitly defining descriptors, you move from "convention" (hoping they don't touch it) to "enforcement" (the engine ensures they can't touch it). It’s the difference between writing code that works and writing code that is resilient. How often do you reach for Object.defineProperty in your daily work, or do you rely on standard object literals? Let's discuss below! 👇 #JavaScript #SoftwareArchitecture #WebDevelopment #DeepDive #CodingTips #AdvancedJS
To view or add a comment, sign in
-
-
🔥 Debouncing vs Throttling in JavaScript User events can fire hundreds of times per second. Examples: • Typing in a search bar • Scrolling • Window resizing If your search input calls an API on every keystroke, performance will suffer. That’s where Debouncing and Throttling help. 🟢 Debouncing Runs the function only after the user stops typing. Perfect for search inputs. function debounce(fn, delay){ let timer; return (...args)=>{ clearTimeout(timer); timer = setTimeout(()=>fn(...args), delay); }; } Example: Typing Angular → only 1 API request, not 7. 🔵 Throttling Runs a function once every X milliseconds, no matter how many times the event fires. Best for scroll or resize events. function throttle(fn, limit){ let waiting=false; return (...args)=>{ if(!waiting){ fn(...args); waiting=true; setTimeout(()=>waiting=false, limit); } }; } ⚡ Quick Rule ✔ Debounce → Final result matters (Search) ✔ Throttle → Continuous updates (Scroll) Small techniques like these can greatly improve frontend performance. Do you use debounce or throttle more in your projects? 👀 #JavaScript #Angular #Frontend #WebDevelopment #Performance
To view or add a comment, sign in
-
-
You say you’re “comfortable with JavaScript”? Cool. Let’s test that. Answer these in the comments 👇 🧠 1. What will this output? Why? 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + []); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + {}); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨({} + []); Most developers get at least one wrong. ⚡ 2. Predict the output: 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘰𝘶𝘵𝘦𝘳() { 𝘭𝘦𝘵 𝘤𝘰𝘶𝘯𝘵 = 0; 𝘳𝘦𝘵𝘶𝘳𝘯 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘪𝘯𝘯𝘦𝘳() { 𝘤𝘰𝘶𝘯𝘵++; 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘤𝘰𝘶𝘯𝘵); }; } 𝘤𝘰𝘯𝘴𝘵 𝘧𝘯 = 𝘰𝘶𝘵𝘦𝘳(); 𝘧𝘯(); 𝘧𝘯(); 𝘧𝘯(); What concept is this testing? 🔥 3. What’s the difference between these two? 𝘖𝘣𝘫𝘦𝘤𝘵.𝘧𝘳𝘦𝘦𝘻𝘦(𝘰𝘣𝘫); 𝘖𝘣𝘫𝘦𝘤𝘵.𝘴𝘦𝘢𝘭(𝘰𝘣𝘫); When would you use one over the other in production? 🧩 4. True or False? 𝘵𝘺𝘱𝘦𝘰𝘧 𝘯𝘶𝘭𝘭 === "𝘰𝘣𝘫𝘦𝘤𝘵" 𝘐𝘧 𝘵𝘳𝘶𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 𝘐𝘧 𝘧𝘢𝘭𝘴𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 🚀 5. Async trap — what happens here? 𝘢𝘴𝘺𝘯𝘤 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘵𝘦𝘴𝘵() { 𝘳𝘦𝘵𝘶𝘳𝘯 42; } 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘵𝘦𝘴𝘵()); What exactly gets logged? If you can answer all 5 confidently, you’re not just “using” JavaScript. You understand it. Drop your answers below 👇 Let’s see who’s interview-ready. #javascript #frontenddeveloper #codinginterview #webdevelopment #softwareengineering #DAY73
To view or add a comment, sign in
-
Say Goodbye to JavaScript Date Object Headaches! For years, developers have struggled with the built-in Date object in JavaScript—it's mutable, inconsistent, and a major pain when dealing with time zones or complex date arithmetic. Most of us have relied on external libraries like Moment.js or date-fns to get the job done. But the future is here: the Temporal API is arriving as a new built-in standard, and it's a game-changer! 🚀 Temporal provides a robust, modern, and reliable way to handle dates and times. Here’s why you should be excited: 🔒 Immutability: Every Temporal object is immutable, which eliminates a major source of bugs in date manipulation. 🌍 First-Class Time Zones: It has explicit, robust support for time zones and daylight saving time (DST). ➗ Safe Arithmetic: Performing calculations like adding or subtracting days is predictable and straightforward with methods like add() and subtract(). 🎯 Clear Data Types: Instead of one generic Date object, Temporal offers distinct types for different use cases: Instant: For exact points in time. PlainDate, PlainTime, PlainDateTime: For wall-clock dates and times without a specific time zone. ZonedDateTime: For handling time-zoned timestamps. Major browsers are actively implementing the proposal. You can start experimenting with it today using a polyfill or check out the official TC39 documentation. It's time to level up our date-handling skills! Who's ready to make the switch? #JavaScript #WebDev #Frontend #Temporal #Programming #Coding #TechNews
To view or add a comment, sign in
-
-
🚨 90% of JavaScript Developers Get This Wrong (Even with 2–4 years of experience 👀) No frameworks. No async tricks. Just pure JavaScript fundamentals. 🧠 Output-Based Question (Set + Type Checking) const s = new Set(); s.add(5); console.log(s.has('5')); ❓ What will be printed? ❌ Don’t run the code 🧠 Think like the JavaScript engine A. true B. false C. error D. undefined 👇 Drop ONE option only (no explanations yet 👀) ⚠️ Why This Question Matters Most developers assume: • JavaScript auto-converts types • '5' and 5 are basically the same • Collections behave like loose equality All three assumptions can break real applications. 🎯 What This Actually Tests • How Set stores values • Strict equality (===) behavior • Primitive type comparison • Why type consistency matters in production When this mental model is unclear: • Cache checks fail • Permission checks break • Duplicate detection becomes unreliable Strong JavaScript developers don’t rely on “automatic conversion”. They understand how values are actually stored and compared. 💡 I’ll pin the breakdown after a few answers. #JavaScript #JSFundamentals #CodingInterview #WebDevelopment #FrontendDeveloper #FullStackDeveloper #DevelopersOfLinkedIn #ProgrammingTips
To view or add a comment, sign in
-
-
Null vs Undefined: JavaScript's Twin Voids – What's the Difference?.................. In JavaScript, null and undefined both represent emptiness, but they have distinct meanings. undefined is the default value for uninitialized variables, missing function arguments, or non-existent object properties – it signals that a value hasn't been assigned. null, on the other hand, is an intentional assignment used to explicitly indicate "no value" or an empty object reference. A quirky historical bug makes typeof null return "object", while undefined is a proper type. They are loosely equal (null == undefined), but strictly different (null === undefined is false). Both are falsy, yet null converts to 0 in arithmetic, while undefined becomes NaN. In JSON, null is preserved, but undefined properties are omitted. Mastering this distinction prevents subtle bugs in everyday web development. #webdev #javascript #programming #coding #developer #frontend #backend #fullstack #js #webdevelopment #softwareengineering #tech
To view or add a comment, sign in
-
-
💡 The Secret Behind JavaScript Closures – It’s Like Russian Nesting Dolls Think of a function as a doll that can hold another doll inside it. When you create a smaller doll , an inner function, it remembers the shape of the bigger doll that placed it there. Even after you put the bigger doll away, the smaller one still knows its size and can use it. In JavaScript that “memory” is a closure – a function that keeps access to the variables from the place where it was created. Why does this matter? Closures let you keep data private, create factory functions, and avoid global variables. Imagine you need a counter that only your button can increase. You write a function that returns another function. The inner function adds one to a hidden variable and returns the result. Each time you click, the hidden variable stays alive because the inner function closes over it. Quick example: function makeCounter, , let total = 0 return function, , total = total + 1 return total let clickCount = makeCounter, , clickCount, , // 1 clickCount, , // 2 The inner function still sees “total” even though makeCounter finished running. A recent habit study I shared shows developers who code 30 minutes a day improve their skills 20% faster, and mastering closures is a big step toward that growth. Did this help? Save it for later. Check if your scripts use closures wisely and watch your code become cleaner. #WebDevelopment #LearnToCode #WordPress #CodingTips #TechEducation #WebDesign #JavaScript #Frontend #HTML #CSS #Programming #Developer #TechTips #CareerGrowth #CodingLife
To view or add a comment, sign in
-
One of my favorite JavaScript one-liners: .filter(Boolean) Filtering out falsy values from an array meant chaining conditions and hoping I hadn't missed an edge case. When you pass Boolean as a callback to .filter(), JavaScript calls Boolean(item) on every element. Anything falsy - null, undefined, 0, "", false, NaN - gets removed. What you're left with is a clean array of only meaningful values. It's not just about writing less code. It's about communicating intent clearly. This pattern shines especially in real-world scenarios: cleaning up API responses, processing user input, or combining .map() and .filter() to transform and sanitize data in a single chain. #JavaScript #WebDevelopment #SoftwareEngineering #CleanCode #Frontend #Programming #JS #CodeQuality #TechTips #Developer --- I post about web engineering, front-end and soft skills in development. Follow me here: Irene Tomaini
To view or add a comment, sign in
-
Explore related topics
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