🚀 LeetCode #283 — Move Zeroes (JavaScript Edition) This problem teaches array manipulation, in-place updates, and the pointer technique — perfect for frontend interviews. Below are 3 clear ways to solve it (beginner-friendly). I use both the traditional temp, swap and the modern destructuring so learners can pick what they understand best. 🧩 Approach 1 — One Loop (Swapping Elements) function moveZeroes(nums) { let p = 0; // next position for a non-zero for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { if (i !== p) { // ✅ Only swap when needed let temp = nums[p]; nums[p] = nums[i]; nums[i] = temp; // traditional swap — beginners find this clear } p++; } } return nums; } ⚙️ Possible Minor Improvements You can simplify the code by avoiding the swap when p === i. This avoids unnecessary swapping when the element is already in the correct position. Cleaner version 👇 var moveZeroes = function(nums) { let p = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { if (i !== p) { // ✅ Only swap when needed [nums[p], nums[i]] = [nums[i], nums[p]]; } p++; } } return nums; }; 💡 Why it’s better: When elements are already in order, this avoids unnecessary writes — a small tweak, but cleaner and slightly more efficient! 💬 For learners [nums[p], nums[i]] = [nums[i], nums[p]]; is called Array Destructuring Assignment in JavaScript. Example: [a, b] = [b, a]; It’s a modern, shorter, and cleaner way to swap two values without using a temporary variable. 🧠 Approach 2 — Two Loops (Copy and Fill) function moveZeroes(nums) { let x = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { nums[x] = nums[i]; x++; } } for (let i = x; i < nums.length; i++) { nums[i] = 0; } return nums; } ✅ How it works: The first loop copies all non-zero values to the front (no swapping needed). The second loop fills the remaining positions with zeros. If zeros are already at the end, the second loop just reassigns them — still simple O(n) work. 🔍 Why Use 2 Loops Instead of Swapping? When you use swapping, each non-zero element is moved one by one — even if it’s already in the correct place. The two-loop version just copies forward, making the logic easier to reason about and the code cleaner. 💡 Fun Fact for Learners Both methods run in O(n) time and use O(1) extra space. Using temp is the traditional swap (slight speed boost). Using [a, b] = [b, a] is the modern JS swap. The two-loop version is cleaner when zeros are already near the end. 💬 In short: 👉 Both methods are correct. 👉 The 2-loop version is cleaner and beginner-friendly. 👉 The 1-loop swap version is efficient and teaches in-place thinking. Which one do you prefer — Classic Swap, Modern Destructuring, or Clean Two-Loop? 😄 Let’s discuss in comments 👇 #JavaScript #CodingJourney #FrontendDevelopment #DeveloperTips #LearnByDoing
"3 Ways to Move Zeroes in JavaScript Array"
More Relevant Posts
-
Day 15/100 Day 6 of JavaScript Understanding Functions in JavaScript ? In JavaScript, functions are the building blocks of reusable code. They allow you to group statements that perform a specific task and execute them whenever needed — instead of writing the same code multiple times. What is a Function? A function is a block of code designed to perform a particular task. You can think of it as a machine — you give it some input (parameters), it processes it, and gives you an output (return value). Basic Function Syntax // Function Declaration function greet(name) { return `Hello, ${name}!`; } // Function Call console.log(greet("Appalanaidu")); Output: Hello, Appalanaidu! Here’s what’s happening: function greet(name) → defines a function named greet that takes one parameter, name. return → sends the output back to where the function was called. greet("Appalanaidu") → calls the function and passes "Appalanaidu" as the argument. Types of Functions in JavaScript Function Declaration function add(a, b) { return a + b; } console.log(add(5, 3)); // 8 Function Expression const multiply = function(x, y) { return x * y; }; console.log(multiply(4, 2)); // 8 Arrow Function (ES6) const divide = (a, b) => a / b; console.log(divide(10, 2)); // 5 Anonymous Function setTimeout(function() { console.log("This runs after 2 seconds"); }, 2000); Why Use Functions? Reusable — Write once, use multiple times Organized — Makes code clean and structured Testable — Easy to debug small blocks Scalable — Ideal for modular and maintainable applications Key Takeaway: Functions are the heart of JavaScript programming. They make your code efficient, readable, and easy to maintain — a must-know for every developer. #10000coders
To view or add a comment, sign in
-
Month 2: JavaScript Advanced & React 🚀 JavaScript ES6+ (Week 1-2) Arrow Functions: const add = (a, b) => a + b; Shorter syntax! Destructuring: const {name, age} = user; const [first, second] = array; Spread/Rest: const newArr = [...oldArr, 4, 5]; const sum = (...nums) => nums.reduce((a,b) => a+b); Template Literals: const msg = `Hello ${name}`; Async/Await: const getData = async () => { const res = await fetch(url); const data = await res.json(); } Handle APIs without blocking! Array Methods: map: Transform items filter: Filter by condition reduce: Single value find: First match Modules: export const name = "John"; import {name} from './file'; Daily: 2-3 hours practice Day 1-7: Functions, destructuring, spread Day 8-14: Async/await, array methods React Fundamentals (Week 3-4) Setup: npx create-react-app my-app npm start Components: function Welcome() { return <h1>Hello!</h1>; } Props: function Greeting({name}) { return <h1>Hi {name}</h1>; } <Greeting name="John" /> useState: const [count, setCount] = useState(0); <button onClick={() => setCount(count + 1)}>+</button> useEffect: useEffect(() => { fetch('api').then(res => res.json()); }, []); API calls, side effects! Events: <button onClick={handleClick}>Click</button> <input onChange={(e) => setValue(e.target.value)} /> Conditional Rendering: {isLoggedIn ? <Dashboard /> : <Login />} Lists: {users.map(user => <div key={user.id}>{user.name}</div>)} Always use key! Daily: 3-4 hours Day 15-21: Components, props, state Day 22-30: useEffect, events, projects Month 2 Projects Project 1: Weather App Search city Display temp, conditions 5-day forecast Loading state API: OpenWeather Time: 3 days Project 2: Movie Search Search movies Display poster, title Click details Favorites API: OMDB Time: 3 days Project 3: E-commerce Listing Product cards Filter by category Search Add to cart Cart count Time: 4 days Resources React: react.dev (official docs) Traversy Media (YouTube) Web Dev Simplified Practice: Convert Month 1 projects to React Build daily components Daily Schedule Morning (1.5 hrs): Learn concepts Evening (2.5 hrs): Code projects Night (1 hr): Revise, debug Total: 4-5 hours Checklist Week 2: ✅ Arrow functions ✅ Async/await ✅ Array methods ✅ Fetch API Month 2: ✅ React setup ✅ Components created ✅ useState, useEffect ✅ API integration ✅ 3 projects built Common Mistakes ❌ Skip JS, jump to React ❌ Use class components ❌ Forget keys in lists ❌ Direct state mutation ❌ No error handling Pro Tips ✅ Functional components only ✅ Destructure props ✅ Small components ✅ Handle loading/errors ✅ Console.log debug Self-Test Can you: Create components? ✅ Use useState? ✅ Fetch API with useEffect? ✅ Map arrays? ✅ Handle events? ✅ All YES: Month 3 ready! 🎉 GitHub Month 2 end: 7+ projects uploaded README each Daily commits 🟩 Clean structure Motivation Month 1: Basics Month 2: React exciting! 🔥 Fact: 70% frontend jobs need React! Next Preview Month 3: React Router Context API Month 3 mein aur powerful! 🚀
To view or add a comment, sign in
-
💡JavaScript Series | Topic 2 | Part 1 — JavaScript’s Type System & Coercion — The Subtle Power Behind Simplicity 👇 JavaScript’s biggest strength — flexibility — can also be its trickiest part. To write bug-free, production-grade code, you must understand how its type system and type coercion really work. 🧱 The Foundation: JavaScript’s Type System JavaScript defines 7 primitive types, each with a specific role 👇 typeof 42; // 'number' typeof 'Hello'; // 'string' typeof true; // 'boolean' typeof undefined; // 'undefined' typeof null; // ⚠️ 'object' (a long-standing JS quirk) typeof Symbol(); // 'symbol' typeof 123n; // 'bigint' ✅ Everything else — arrays, functions, and objects — falls under the object type. ⚡ Dynamic Typing in Action In JavaScript, variables can change type during execution 👇 let value = 10; // number value = "10"; // now string value = value + 5; // '105' (string concatenation!) 👉 Lesson: Dynamic typing = flexibility + danger. It saves time, but you must stay alert to implicit conversions. 🔄 Type Coercion – When JavaScript “Helps” You Type coercion happens when JavaScript automatically converts types during comparisons or operations. console.log(1 + "2"); // '12' (number → string) console.log(1 - "2"); // -1 (string → number) console.log(1 == "1"); // true (loose equality) console.log(1 === "1"); // false (strict equality) ✅ Use === (strict equality) to avoid hidden coercion bugs. ⚠️ JavaScript tries to be helpful — but that “help” can silently break logic. 🧠 Why It Matters Understanding JS types makes your code: 🧩 More predictable ⚙️ Easier to debug 🚀 Faster in performance (engines optimize consistent types) 💬 My Take: JavaScript’s type system isn’t broken — it’s powerful but misunderstood. Mastering coercion and types is what separates good developers from great engineers. 👉 Follow Rahul R Jain for real-world JavaScript & React interview questions, hands-on coding examples, and performance-focused frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #TypeCoercion #WebDevelopment #Coding #TypeSystem #NodeJS #ReactJS #NextJS #TypeScript #InterviewPrep #WebPerformance #DeveloperCommunity #RahulRJain
To view or add a comment, sign in
-
Day:19 1. History of JavaScript * JavaScript was created in 1995 by Brendan Eich. * It was initially called Mocha, then Live Script, and finally JavaScript. * Developed for use in web browsers to make websites interactive. * Became a standard (ECMAScript) for cross-browser compatibility. 2. Increment and Decrement Increment (++): increases a variable’s value by one. Example: x++; // adds 1 to x Decrement (--): decreases a variable’s value by one. Example: x--; // subtracts 1 from x Can be prefix (++x) or postfix (x++)—the difference is when the value changes in an expression. 3. Variable and Constant Variable: stores data that can change. Declared using let or var. Constant: stores data that doesn't change. Declared using const. Example: let age = 18; (can be changed), const pi = 3.14; (cannot change value after assignment) 4. Data Types JavaScript has several data types: Number (e.g., 12, 3.14) String (e.g., "hello world") Boolean (true, false) Undefined (variable declared but not assigned) Null (explicitly set to no value) Object (arrays, objects, functions) Symbol (unique identifiers, ES6) 5. Alert, Prompt, Confirm alert("message") — shows a popup with a message. prompt("message") — asks user to input a value, returns what they type. confirm("message") — asks for OK/Cancel, returns true for OK, false for Cancel. 6. Concatenation Combining strings using + operator. Example: "Hello " + "World" gives "Hello World" Can also join numbers and strings: 5 + " apples" gives "5 apples" Quick examples:
To view or add a comment, sign in
-
🔍 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴? Hoisting is JavaScript’s default behavior of 𝗺𝗼𝘃𝗶𝗻𝗴 𝗱𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻𝘀 (𝗻𝗼𝘁 𝗶𝗻𝗶𝘁𝗶𝗮𝗹𝗶𝘇𝗮𝘁𝗶𝗼𝗻𝘀) 𝘁𝗼 𝘁𝗵𝗲 𝘁𝗼𝗽 𝗼𝗳 𝘁𝗵𝗲𝗶𝗿 𝘀𝗰𝗼𝗽𝗲 𝗯𝗲𝗳𝗼𝗿𝗲 𝗰𝗼𝗱𝗲 𝗲𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻. In simpler terms — during the compilation phase, JavaScript "scans" your code and allocates memory for variables and function declarations before executing it. That’s why you can use certain functions or variables before they’re defined in your code! 📘 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 console.log(myVar); // Output: undefined var myVar = 10; Behind the scenes, JavaScript treats this like: var myVar; // Declaration hoisted console.log(myVar); // undefined myVar = 10; // Initialization happens here ➡️ var is hoisted and initialized with undefined. However, if you use let or const, they’re hoisted too — but not initialized, leading to a ReferenceError if accessed before declaration. console.log(myLet); // ❌ ReferenceError let myLet = 20; ⚙️ 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 sayHello(); // ✅ Works! function sayHello() { console.log("Hello, World!"); } ➡️ Function declarations are hoisted completely (both the name and definition). But function expressions are not fully hoisted: sayHi(); // ❌ TypeError: sayHi is not a function var sayHi = function() { console.log("Hi!"); }; 💡 𝗪𝗵𝘆 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗠𝗮𝘁𝘁𝗲𝗿𝘀 𝟭. 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗖𝗼𝗻𝘁𝗲𝘅𝘁: Helps you reason about how JS interprets and runs your code. 𝟮. 𝗔𝘃𝗼𝗶𝗱 𝗕𝘂𝗴𝘀: Prevents confusion around “undefined” or “ReferenceError”. 𝟯. 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗔𝗱𝘃𝗮𝗻𝘁𝗮𝗴𝗲: Hoisting is a frequent JS interview question — understanding it deeply gives you an edge. 🧠 𝗧𝗼𝗽 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 #𝟮 Q: What is Hoisting in JavaScript, and how does it affect variable and function declarations? A: Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. var is hoisted and initialized with undefined. let and const are hoisted but not initialized (Temporal Dead Zone). Function declarations are fully hoisted, while function expressions are not. 🎯 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 1. JavaScript hoists declarations, not initializations. 2. var behaves differently from let and const. 3. Function declarations can be used before they’re defined — but function expressions cannot. #JavaScript #Hoisting #WebDevelopment #InterviewPreparation #TechTips #JavaScriptInterviewQuestions
To view or add a comment, sign in
-
🔄 Callback Functions in JavaScript — Simplified In JavaScript, functions are first-class citizens, which means we can pass them as arguments to other functions, return them, or store them in variables. A callback function is simply a function passed as an argument to another function and executed later, often after some operation completes. 🧠 Why We Use Callbacks Callbacks are especially useful when dealing with asynchronous operations — such as fetching data from an API, reading files, or handling events — where we want code to run after a certain task completes. 💡 Example function greetUser(name, callback) { console.log(`Hello, ${name}!`); callback(); } function showMessage() { console.log("Welcome to JavaScript callbacks!"); } // Passing showMessage as a callback greetUser("Abdul", showMessage); Output : Hello, Abdul! Welcome to JavaScript callbacks! Here, showMessage is a callback function that runs aftergreetUser() finishes its main task. ⚙️ Real-World Example (Asynchronous) console.log("Start"); setTimeout(() => { console.log("Callback executed after 2 seconds"); }, 2000); console.log("End"); Output : Start End Callback executed after 2 seconds 👉 setTimeout() takes a callback that runs after 2 seconds — demonstrating asynchronous behavior. 🚀 In Short ✅ A callback function is : • A function passed as an argument to another function • Executed after the main function finishes • Essential for handling asynchronous tasks 💬 Final Thought Callback functions are the foundation of asynchronous programming in JavaScript. Modern approaches like Promises and async/await were built on top of this very concept.
To view or add a comment, sign in
-
-
💡JavaScript Series | Topic 3 | Part 1 — JavaScript Scoping and Closures 👇 Understanding how scope and closures work isn’t just useful — it’s fundamental to writing predictable, bug-free JavaScript. These concepts power everything from private variables to callbacks and event handlers. Let’s break it down 👇 🧱 Lexical Scope — The Foundation JavaScript uses lexical (static) scoping, which means: ➡️ The structure of your code determines what variables are accessible where. Think of each scope as a nested box — variables inside inner boxes can “see outward,” but outer boxes can’t “peek inward.” 👀 // Global scope — always visible let globalMessage = "I'm available everywhere"; function outer() { // This is a new scope "box" inside global let outerMessage = "I'm available to my children"; function inner() { // The innermost scope let innerMessage = "I'm only available here"; console.log(innerMessage); // ✅ Own scope console.log(outerMessage); // ✅ Parent scope console.log(globalMessage); // ✅ Global scope } inner(); // console.log(innerMessage); // ❌ Error: Not accessible } // console.log(outerMessage); // ❌ Error: Not accessible outer(); 🧠 Key takeaway: You can look outward (from inner to outer scopes), but never inward (from outer to inner). ⚙️ var vs let vs const — The Scope Trap How you declare variables changes their visibility: Keyword Scope Type Notes var Function-scoped Leaks outside blocks (❌ risky) let Block-scoped Safer, modern choice (✅ recommended) const Block-scoped Immutable, great for constants Example 👇 if (true) { var a = 1; // function scoped let b = 2; // block scoped } console.log(a); // ✅ 1 console.log(b); // ❌ ReferenceError ✅ Best Practice: Always use let or const — they prevent scope leakage and weird bugs. 🧠 Why This Matters 🔒 Helps create encapsulation and private variables. 🧩 Avoids naming conflicts and unexpected overwrites. ⚙️ Powers closures, async callbacks, and higher-order functions. 💬 My Take: Mastering scope is like mastering the rules of gravity in JavaScript — it’s invisible, but it controls everything you build. Up next: Part 2 — Closures: How Functions Remember 🧠 👉 Follow Rahul R Jain for real-world JavaScript & React interview questions, hands-on coding examples, and performance-focused frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #Closures #Scope #LexicalScope #WebDevelopment #Coding #ReactJS #NodeJS #NextJS #TypeScript #InterviewPrep #WebPerformance #DeveloperCommunity #RahulRJain #TechLeadership #CareerGrowth
To view or add a comment, sign in
-
💡 JavaScript Series | Topic 6 | Part 1 — ES6+ Modern Features: A Deep Dive 👇 Today’s JavaScript is a completely different language than it was two decades ago. The ES6+ revolution brought a wave of modern features that fundamentally changed how we write, structure, and think about JavaScript. Knowing these features isn’t just about keeping up — it’s essential for writing cleaner, faster, and more maintainable code. 🚀 Let’s start with one of the most transformative: 👉 Arrow Functions and the Evolution of this ⚙️ The Problem with Traditional Functions In traditional JavaScript functions, the value of this depends on how a function is called — not where it’s defined. If called as a method → this refers to the object. If called standalone → this refers to the global object (or undefined in strict mode). That flexibility often led to confusion — especially in event handlers or callbacks. 💡 Arrow Functions: A Modern Fix Arrow functions introduced in ES6 changed the game. They don’t bind their own this — instead, they lexically inherit it from their surrounding scope. 👉 In other words, arrow functions remember the value of this where they were created — just like closures remember variables. 🧩 Example: The Button Problem class Button { constructor() { this.clicked = false; this.text = "Click me"; } // ❌ Traditional function - 'this' gets lost addClickListener() { document.addEventListener('click', function() { this.clicked = true; // 'this' points to the DOM element, not Button }); } // ✅ Arrow function - 'this' is preserved addClickListenerArrow() { document.addEventListener('click', () => { this.clicked = true; // 'this' correctly refers to the Button instance }); } } 💥 In the first version, this refers to the DOM element that fired the event. In the arrow function version, this remains bound to the Button instance — clean, predictable, and elegant. 🧠 Why Arrow Functions Matter ✅ Solve the long-standing this confusion in JavaScript ✅ Make callbacks and event handlers cleaner ✅ Great for closures, functional programming, and React hooks ✅ Encourage more readable and maintainable async code 💬 My Take: Arrow functions are more than syntax sugar — they represent a mindset shift. They help developers write context-aware, concise, and lexically scoped code. Once you understand how this behaves in arrow functions, asynchronous JavaScript suddenly makes perfect sense. ⚡ 👉 Follow Rahul R Jain for real-world JavaScript and React interview questions, hands-on coding examples, and performance-driven frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #ES6 #ArrowFunctions #LexicalScope #WebDevelopment #Coding #ReactJS #NodeJS #NextJS #TypeScript #InterviewPrep #Closures #AsyncProgramming #WebPerformance #DeveloperCommunity #RahulRJain #TechLeadership #CareerGrowth
To view or add a comment, sign in
-
🧩 Understanding “Palindrome Number” in JavaScript — Beginner Friendly 💡 When I first learned about palindrome numbers (like 121 or 1223221), I got confused by one simple question: 👉 “Why do we need another variable like original to store the number?” Let’s break it down 👇 🔍1️⃣What happens inside the loop? This part confuses many learners at first. When you use the same variable inside the loop (like x or n), you keep changing it in every iteration: let x = 121; let rev = 0; while (x > 0) { let rem = x % 10; rev = 10 * rev + rem; x = Math.floor(x / 10); } console.log("x =", x); // 👉 0 console.log("rev =", rev); // 👉 121 🧠 Inside the loop, you are dividing x each time → x = 0 at the end. So when the loop ends, you lose the original number. That’s why we store it first 👇 let original = x; Then at the end: return original === rev; ✅ This way, you still have the original value to compare. 🧩 2️⃣ When you don’t need original If you pass the number as a parameter, JavaScript creates a copy of it — so the outer value stays safe even if the inner one changes. let n = 121; function palindrome(num) { let rev = 0; while (num > 0) { let rem = num % 10; rev = 10 * rev + rem; num = Math.floor(num / 10); } return rev; } let result = palindrome(n); console.log("n =", n); // 👉 still 121 console.log("result =", result); // 👉 121 ✅ Here you don’t need original because: The function gets a copy of n (numbers are passed by value). Inside the function, only that copy (num) becomes 0. The outer n never changes — it still holds the original number. 🧠 So you can safely compare like: if (n === result) console.log("Palindrome"); 🔍 3️⃣ Why x is 0 even outside the loop That’s a very smart question 👏 — and it shows real understanding of JavaScript. Because in JavaScript, variables declared with let inside the same function share the same function scope — not separate scopes for loops. That means: You used the same variable x inside and outside the loop. Each time in the loop you did x = Math.floor(x / 10). When the loop finishes, x keeps its last modified value → 0. 💡 In short: while doesn’t create a new scope — so x keeps changing even outside the loop. ✅ If you want to keep the original safe → copy it before modifying: let original = x; ✨I shared this because I know how small confusions like these can stop learning flow. Small things like these make a big difference when learning JavaScript logic. If this helped you understand the “original” confusion, drop a 💬 or ❤️ to help other learners too! #JavaScript #CodingJourney #FrontendDevelopment #DeveloperTips #LearnByDoing
To view or add a comment, sign in
-
Hey Devs! 🖖🏻 You need to create a variable in JavaScript. Do you reach for var, let, or const? They might seem similar, but choosing the right one is a hallmark of a modern JavaScript developer and is crucial for writing clean, bug-free code. Let's break down the differences. The Three Keywords for Declaring Variables In modern JavaScript, you have three choices. Here’s how to think about them: 👴 var: The Old Way (Avoid in Modern Code) Analogy: Think of var as posting a note on a giant, public bulletin board. It's visible everywhere within its function, which can lead to unexpected bugs where variables "leak" out of blocks like if statements or for loops. The Verdict: Due to its confusing scoping rules (function-scope vs. block-scope), you should avoid using var in modern JavaScript. It's considered a legacy feature. 🧱 let: The Modern Re-assignable Variable Analogy: Think of let as writing a value on a whiteboard. You can erase it and write something new later on. Key Features: Block-Scoped: This is the game-changer. A variable declared with let only exists within the "block" (the curly braces {...}) where it's defined. This is predictable and prevents bugs. Mutable: You can update or re-assign its value. When to use it: Use let only when you know a variable's value needs to change. The most common use case is a counter in a loop (for (let i = 0; ...)). 💎 const: The Modern Constant Analogy: Think of const as a value carved into a stone tablet. You cannot change the initial assignment. Key Features: Block-Scoped: Just like let. Immutable Assignment: You cannot re-assign a new value to a const variable. This makes your code safer and easier to reason about. Important Nuance: If a const holds an object or an array, you can still change the contents of that object or array (e.g., add an item to the array). You just can't assign a completely new object or array to the variable. Your Modern Workflow This simple rule will serve you well: Default to const for everything. If you realize you need to re-assign the value later, change it to let. Almost never use var. This "const by default" approach makes your code more predictable. When another developer sees let, it's a clear signal that this variable is intentionally designed to change. What was your 'aha!' moment when you finally understood the difference between let and const? Save this post as a fundamental JS concept! Like it if you're a fan of writing modern JavaScript. 👍 What's the most common mistake you see new developers make with var, let, and const? Let's discuss below! 👇 #JavaScript #JS #ES6 #WebDevelopment #FrontEndDeveloper #Coding
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