Reversing a string in JavaScript can be done in more than one way. I revisited this problem today and tried three approaches, each with a different mindset: // 1. Using built-in methods const reverse1 = (str) => str.split("").reverse().join(""); // 2. Using a loop (more control) function reverse2(str) { let result = ""; for (let i = str.length - 1; i >= 0; i--) { result += str[i]; } return result; } // 3. Using reduce (functional style) const reverse3 = (str) => str.split("").reduce((acc, char) => char + acc, ""); console.log(reverse1("hello")); //"olleh" console.log(reverse2("hello")); //"olleh" console.log(reverse3("hello")); //"olleh" Methods I used: • Built-in methods → concise and readable • Loop → full control and clarity • reduce → functional and expressive This reminded me that in real projects, how you think about a problem matters as much as the answer itself. Still learning, still building, still showing up. #JavaScript #FrontendDevelopment #LearningInPublic #JuniorDeveloper
Reversing Strings in JavaScript: 3 Approaches Compared
More Relevant Posts
-
🚀 A JavaScript forEach() Mistake At first glance, this looks correct: const numbers = [1, 2, 3, 4]; const result = numbers.forEach(num => num * 2); console.log(result); Expected: [2, 4, 6, 8] Actual output: undefined Why? Because forEach() does not return a new array. It only executes a function for each element. So result becomes undefined. If you want to transform data, use map(). ✅ Correct approach: const numbers = [1, 2, 3, 4]; const result = numbers.map(num => num * 2); console.log(result); Now the output is: [2, 4, 6, 8] Small difference in method. Big difference in behavior. In JavaScript, choosing the right array method matters more than the logic itself. What array method confused you the most when you started? #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering
To view or add a comment, sign in
-
-
🚀 Process vs Thread – Simple Explanation (With JavaScript Twist) Many developers confuse Process and Thread. Let’s understand this in the simplest way. 🧠 What is a Process? A Process is an independent running program. Example: VS Code is a process. Chrome is another process. If Chrome crashes, VS Code does not stop. Why? Because both have separate memory space. ⚙️ What is a Thread? A Thread is a worker inside a process. One process can have multiple threads. All threads share the same memory. Think of it like: Process = Company Threads = Employees inside the company 🔥 JavaScript – Single Threaded? Yes. JavaScript is single-threaded. But that does NOT mean it handles only one request at a time. It means: ➡️ It executes one instruction at a time in the call stack. JavaScript uses: Event Loop Callback Queue Web APIs This makes it non-blocking and asynchronous. So JS supports concurrency, even though it runs on a single thread. 🦀 What about Rust / C++? Languages like Rust and C++ support true multi-threading. That means: Multiple threads Real parallel execution Better CPU core utilization 💡 Final Understanding Process = Independent program Thread = Worker inside process JavaScript = Single-threaded but async Rust/C++ = Multi-threaded with real parallelism Understanding this clears a lot of backend and system design confusion. #SystemDesign #JavaScript #Multithreading #BackendDevelopment #Rust #WebDevelopment
To view or add a comment, sign in
-
📘 Day 69: JavaScript Loops (for & while) 🔹 Loops in JavaScript • Loops are used to repeat a block of code multiple times • Helpful for continuous iteration and data processing • <br> is often used with document.writeln() to print on new lines 🔸 For Loop 💡 Structure: for(start; condition; step) • Executes code while the condition is true • Order in JS: 1️⃣ Initialize → 2️⃣ Check condition → 3️⃣ Print → 4️⃣ Increment Example: for(let i=0;i<10;i++) prints 0–9 🔸 Start, Stop, Step • i=0 → start • i<10 → stop condition • i+=2 or i+=3 → step (skip values) • Useful for controlling iteration speed 🔸 For…of Loop • Used to print values from: ✅ Arrays ✅ Sets ✅ Maps Example: for(let i of array) → prints elements one by one 🔸 For…in Loop • Used mainly for Objects • Prints keys (indexes/properties) To print key + value: object[key] Example output: Name : John 🔸 While Loop • Runs while condition is true • Manual increment is required Example: while(i<=10) 🔸 Step in While Loop • Controlled using i+=2, i+=3, etc. • Helps skip numbers and reduce iterations ✨ Today’s focus was mastering iteration techniques in JavaScript — a core skill for handling arrays, objects, and dynamic data efficiently. #JavaScript #Day69 #WebDevelopment #JSLoops #ForLoop #WhileLoop #CodingJourney #FrontendDevelopment #LearnJavaScript #ProgrammingBasics #DeveloperJourney
To view or add a comment, sign in
-
🧠Mastering JavaScript — One Concept at a Time (2/32) Today I am very happy because my understanding of hoisting, scope, and sharing with you is now complete. 🔥Scope in Real Life Scope simply means: Where can I access this variable? Block Scope → Code inside {} like in loops, if , etc. Function Scope → Code inside a function let and const follow block scope. var ignores block scope — which leads to bugs. 🧨Hoisting JavaScript prepares memory before running code. It moves all declarations to the top — this is called hoisting. But: var is hoisted and set to undefined let and const are hoisted but not initialised — so accessing them early gives ReferenceError ⚠Common Confusions (JS Reality Checks) const doesn't make things fully constant. It protects the variable, not the value. var is outdated — it's better to use let and const let and const behave similarly, but const gives more safety use it when you're not planning to reassign. 🧠 Mindset Rule Use const by default. Use let only when you plan to change the value. Avoid var — it belongs to the past. Revisiting these fundamentals makes JavaScript feel less “magical” and more predictable. In the next post, I’ll go deeper into how the Data Type and Type System. How long did it take you to understand scope and hoisting truly? #JavaScript #LearningInPublic #WebDevelopment #FrontendDevelopment #MasteringJavaScript
To view or add a comment, sign in
-
🔍 Prototypes and this in JavaScript — going beyond the syntax into the actual mechanics. Here's what's worth knowing: 🧬 On Prototypes Methods aren't copied to every object instance. They live once on the prototype — all instances share them via reference. That's how JS stays memory efficient even with thousands of objects. Every method lookup is a live chain traversal, every single time. Object.create is pure prototype wiring — it sets the [[Prototype]] of a new object. That's it. 🎯 On this — four rules, in priority order 1️⃣ new binding → this = newly created object 2️⃣ Explicit binding → .call() .apply() .bind() — you decide 3️⃣ Implicit binding → obj.method() — this = object left of the dot 4️⃣ Default binding → standalone call — this = window or undefined Arrow functions sit outside all four rules — they inherit this lexically from wherever they were defined. ⚠️ The classic trap js setTimeout(this.log, 1000); // this is lost Detach a method from its object and this evaporates. Fix → arrow wrapper, .bind(), or bind in the constructor. Each has different tradeoffs. 🧠 On EventEmitters and memory Per-instance state must always be initialized in the constructor. If it accidentally lands on the prototype — every instance shares the same object. Emitting on one instance fires callbacks registered on all instances. Silent. No error thrown. Every .on() listener holds a closure reference — keeping objects alive in memory long after they're "destroyed." Always implement .off(). Always clean up. Follow along — sharing one deep dive at a time. 🚀 #JavaScript #Prototypes #FrontendEngineering #WebPerformance #PlatformEngineering
To view or add a comment, sign in
-
𝗪𝗵𝘆 𝘁𝘆𝗽𝗲𝗼𝗳 𝗻𝘂𝗹𝗹 𝗶𝘀 "𝗼𝗯𝗷𝗲𝗰𝘁" — 𝗧𝗵𝗲 𝟯𝟬-𝗬𝗲𝗮𝗿 𝗕𝘂𝗴 𝗧𝗵𝗮𝘁 𝗪𝗼𝗻’𝘁 𝗗𝗶𝗲 🐛 If you’ve ever debugged JavaScript and seen typeof null === 'object', you probably thought your code was broken. It’s not you. It’s one of the oldest "mistakes" in web history. Here’s the deep dive into why this quirk exists and why we’re stuck with it forever: 𝟭. 𝗧𝗵𝗲 "𝟭𝟬-𝗗𝗮𝘆" 𝗢𝗿𝗶𝗴𝗶𝗻 𝗦𝘁𝗼𝗿𝘆 ⏱️ In 1995, Brendan Eich created JavaScript in just 10 days. In that rush, the engine's internal structure used a "type tag" system to identify data. ● 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 were assigned the tag 000. ● 𝗻𝘂𝗹𝗹, representing a null pointer, was represented as all zeros (0x00). Because the engine checked for the 000 tag to identify objects, and null consists entirely of zero bits, the typeof operator incorrectly flagged it as an object. 𝟮. 𝗧𝗵𝗲 𝗔𝘁𝘁𝗲𝗺𝗽𝘁𝗲𝗱 𝗙𝗶𝘅 🛠️ There was actually a proposal to "fix" this in ECMAScript 6 so that typeof null would return 'null'. So, why didn't it happen? 𝟯. 𝗧𝗵𝗲 "𝗗𝗼𝗻'𝘁 𝗕𝗿𝗲𝗮𝗸 𝘁𝗵𝗲 𝗜𝗻𝘁𝗲𝗿𝗻𝗲𝘁" 𝗥𝘂𝗹𝗲 🌐 Backward compatibility is the golden rule of the web. Millions of websites and legacy libraries rely on this specific bug for their logic. Changing it now would "break the internet," causing countless sites to crash. As Brendan Eich himself noted: “𝘐𝘵’𝘴 𝘵𝘰𝘰 𝘭𝘢𝘵𝘦 𝘵𝘰 𝘧𝘪𝘹.” 𝗧𝗵𝗲 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 𝗳𝗼𝗿 𝗗𝗲𝘃𝘀: ✅ Never use typeof to check for null. ✅ Always use strict equality: myVar === null. ✅ Pro Tip: To check if something is actually a valid object, use: myVar !== null && typeof myVar === 'object'. JavaScript isn’t perfect, but its quirks are what make its history so fascinating. What’s your "favorite" JavaScript bug or quirk? Let’s discuss in the comments! 👇 #JavaScript #WebDevelopment #Programming #SoftwareEngineering #CodingLife #TechHistory #Frontend
To view or add a comment, sign in
-
-
Most developers reach for IDs, classes, or extra state before remembering this: JavaScript already gives you a clean way to attach structured metadata directly to DOM elements. If you have ever used data-* attributes in HTML, you can access them in JavaScript through the dataset property. No parsing. No brittle string manipulation. No unnecessary DOM lookups. It is simple, readable, and surprisingly underused. This pattern is especially useful for event delegation, lightweight UI state, dynamic lists, and keeping behaviour close to the element it belongs to. Small details like this make frontend systems cleaner and easier to reason about without introducing extra abstractions. Not everything needs global state. Sometimes the platform already solved the problem. In the example attached, notice how `data-user-id` becomes `dataset.userId`. Hyphenated attributes automatically convert to camelCase. It is a small feature, but small features compound into cleaner, more maintainable frontend code. What is one underrated JavaScript feature you think more developers should use? Github Gist: https://lnkd.in/d6pjMP7J #webdevelopment #javascript #cleancode
To view or add a comment, sign in
-
-
🚀 JavaScript Hoisting Explained Clearly Most developers hear about hoisting… But very few truly understand what actually happens behind the scenes. Let’s break it down. When JavaScript runs your code, it does NOT execute it line by line immediately. First, it creates something called the Execution Context. There are two main phases: 1️⃣ Creation Phase (Hoisting Phase) 2️⃣ Execution Phase 🔵 Creation Phase (Hoisting Phase) During this phase: • Memory is allocated for variables and functions • Function declarations are stored completely in memory • var variables are initialized with undefined • let and const are hoisted but remain in the Temporal Dead Zone (TDZ) Example that works: greet(); function greet() { console.log("Hello"); } Example that throws an error: sayHi(); const sayHi = function () { console.log("Hi"); }; Reason: Only the variable is hoisted, not the function expression. 🔴 Execution Phase Now JavaScript executes the code line by line. • Variables receive their actual values • Functions run when called Important Insight Hoisting does NOT mean JavaScript moves your code to the top. It means JavaScript allocates memory before execution begins. If you understand hoisting deeply, you automatically understand: • Execution Stack • Scope Chain • Closures • TDZ • var vs let vs const Master this concept once, and JavaScript starts making real sense. #JavaScript #WebDevelopment #Frontend #ExecutionContext #Hoisting #LearnToCode #Programming #Developers
To view or add a comment, sign in
-
-
Today I practiced an important JavaScript concept: Flattening a nested array manually using loops. Instead of using the built-in .flat() method, I implemented the logic myself to deeply understand how flattening actually works. 🧠 Problem Given this array: [1, [2, 3], [4, 5], 6] Return: [1, 2, 3, 4, 5, 6] 🔍 My Approach Created an empty result array. Looped through each element of the main array. Checked if the current element is an array using Array.isArray(). If it’s an array: Loop through it Push each inner element individually into result If it’s not an array: Push it directly into result 💡 Key Line That Does the Magic result.push(arr[i][j]); This line: Accesses elements inside the nested array Pushes them individually into the final result Removes one level of nesting 🎯 What I Learned How nested loops work in real problems The difference between pushing an array vs pushing its elements What “one-level flattening” actually means How .flat() works internally ⏱ Time Complexity O(n) — every element is visited once. Building fundamentals > memorizing shortcuts. Next step: Flatten deeply nested arrays using recursion 🔥 #JavaScript #FrontendDeveloper #ProblemSolving #WebDevelopment #100DaysOfCode #DSA #LearningInPublic
To view or add a comment, sign in
-
Day 67 of me reading random and basic but important dev topicsss..... Today I read about the Advanced JavaScript Range Properties & Methods..... Yesterday, I looked at the fundamentals of creating a Range in the DOM. Today, I explored the properties and convenience methods that make traversing and building these ranges highly efficient. When integrating raw DOM logic into frameworks like React, knowing these native shortcuts saves us from writing manual, bug-prone offset calculations. Core Range Properties: When we inspect a Range object, it gives us crucial contextual data: * startContainer / startOffset: The exact node and position where the range begins. * endContainer / endOffset: The node and position where the range ends. * collapsed: A boolean. true if the start and end are at the exact same point (think of a blinking text cursor with no characters highlighted). * commonAncestorContainer: The deepest parent element that fully wraps the entire range. (Incredibly useful for validating if a user's selection is contained within a specific UI component!). Pro Methods (Skip the math!): Instead of calculating exact indexes with setStart and setEnd, you can leverage semantic methods: * setStartBefore(node) / setStartAfter(node): Drops the boundary right outside a target node. * selectNode(node): Creates a range that encompasses the entire node, including its outer HTML tags. * selectNodeContents(node): Selects only the inside of the node......perfect for instantly capturing all the text inside a <div> or <p>. * collapse(toStart): Instantly shrinks the range to just its starting or ending cursor point. Keep Learning!!!!!! #JavaScript #WebDevelopment #DOM #FrontendDev
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