💡 #JavaScript Global vs Local Variables (Simple Explanation) If you're learning JavaScript, understanding variable scope is a must 👇 🔹 Global Variables Declared outside any function Accessible from anywhere in your code Can be used across multiple functions Example: var name = "Avi"; function greet() { console.log(name); // Accessible here } 🔹 Local Variables Declared inside a function or block Accessible only within that function/block Helps avoid unwanted changes from outside Example: function greet() { var message = "Hello"; console.log(message); // Works here } console.log(message); // ❌ Error ⚡ Key Difference Global = accessible everywhere Local = accessible only inside its scope 👉 Tip: Prefer #local variables to keep your code clean and avoid bugs. Use #global where multiple parts of your app need the same value. #frontend #js #javascript
JavaScript Global vs Local Variables Explained
More Relevant Posts
-
Hey JavaScript devs 👋 Did you know `this` can silently disappear in 3 very common situations? 1. Detaching a method from its object const fn = obj.greet; fn(); // this → undefined 💀 2. Passing a method as a callback setTimeout(obj.greet, 0); // this → gone [1,2,3].forEach(obj.process); // same story 3. Arrow function in an object literal const obj = { name: 'Pavel', greet: () => console.log(this.name) // this → global, not obj }; The fix is always one of three things: `.bind()`, a wrapper arrow function, or class field arrow methods. Which one bit you the hardest? Drop it in the comments 👇 #JavaScript #WebDev #Frontend #JS
To view or add a comment, sign in
-
-
most developers don't know the difference between null , undefined and "" and it's breaking their React forms silently. - always initialise string state with ' ' not undefined - always initialise array state with [ ] not undefined - always initialise object state with { } not undefined here's why it matters beyond the warning: - undefined means "this was never set" - null means "this was intentionally set to nothing" - ' ' means "this exists but is currently empty" React treats these three things completely differently when rendering. your form works locally because you fill it in immediately. it breaks in production because someone submits without touching a field. initialise your state properly. #reactjs #typescript #webdevelopment #buildinpublic #javascript
To view or add a comment, sign in
-
-
🔥 10 JavaScript One-Liners Every Developer Should Know In this guide, we're sharing 10 tricks that you should know to up your JavaScript game. ✅ Swap Two Variables ✅ Check if a Value is an Array ✅ Generate a Random Integer (0 to N) ✅ Flatten a Deeply Nested Array ✅ Remove Duplicates from an Array ✅ Get the Last Element of an Array ✅ Get the Max or Min Value in Array ✅ Check if an Object is Empty ✅ Reverse a String ✅ Short-Circuit Default Values Save & share with your team! --- If you found this guide helpful, follow me, React.js | JavaScript Mastery for more tips, tutorials, and cheat sheets on web development. Let's stay connected! 🚀 #WebDevelopment #CheatSheet #Coding #CSS #Filters #UI #Frontend #JavaScript #ReactJS
To view or add a comment, sign in
-
React confused me today… for a simple .push() 😅 I was updating an array in state and did this: items.push(newItem) setItems(items) Pretty normal JavaScript, right? But the UI didn’t update. That’s where I got stuck. Then I realized what was actually happening. Arrays in JavaScript are stored by reference. So .push() doesn’t create a new array — it just modifies the existing one. React compared the old state and new state… and saw the same reference. So it thought: “Nothing changed.” 💡 The way I understand it now: Using .push() → same box 📦 Using spread → new box 📦✨ React only reacts when the box changes, not just what’s inside it. So the correct way: setItems(prevItems => [...prevItems, newItem]) Small thing, but it cleared up a lot for me. One more step forward 🚀 #ReactJS #JavaScript #Frontend #LearningInPublic
To view or add a comment, sign in
-
Have you come across something like this: 'this.setState({ [e.target.name]: e.target.value });' and wondered why those square brackets '[]' are there? If you are transitioning from basic JavaScript to React, this syntax can look a bit like an array hidden inside an object. But do not let it fool you. It is actually a powerful ES6 feature called Computed Property Names. Here is why those brackets are the secret sauce of efficient React forms. In standard JavaScript objects, if you write a key, it is treated as a literal string. If you write 'e.target.name: e.target.value' without the brackets, React will literally create a key named 'e.target.name' in your state. It will not care that your input’s name is 'username' or 'email.' It would just create a messy, broken state object. When you wrap a key in square brackets, you are telling JavaScript to evaluate the code inside the brackets first and use the result as the key name. If you type in an input where name='email', JavaScript sees '[e.target.name]' and resolves it to the string 'email'. This turns your code from a rigid list of instructions into a flexible, dynamic system. The biggest benefit here is scalability. It allows you to follow the DRY (Don't Repeat Yourself) principle. Without square brackets, you would need a separate handler function for every single input field. With them, you can write one universal 'handleChange' function that works for two inputs or two hundred. It keeps your code centralized and eliminates the risk of copy-paste bugs. As long as your input's name attribute matches the key in your 'this.state', you are golden. It is a simple ES6 trick that makes handling complex forms significantly easier. #ReactJS #Javascript #SoftwareEngineering #WebDevelopment #CodingTips #ES6
To view or add a comment, sign in
-
-
💡 React Tip of the Day Why do we use "className" instead of "class" in React? 🤔 👉 HTML: 👉 React: 👉 Why? "class" is a reserved keyword in JavaScript. Since JSX runs inside JavaScript, React uses "className" instead. 👉 What does it do? It applies CSS classes to your elements. ✔ Same styling ✔ Works just like HTML Small difference… but important 👍 #ReactJS #JavaScript #Frontend #WebDevelopment #TipOfTheDay
To view or add a comment, sign in
-
"Why does your API call run multiple times in React?" 🤯 Chances are… you're not using useEffect correctly. Let’s fix that 👇 🔹 What is useEffect? "useEffect" lets you perform side effects in React: - API calls 🌐 - Event listeners 🎧 - Timers ⏱️ 🔹 Basic Syntax useEffect(() => { // side effect code }, []); 🔹 Dependency Array (IMPORTANT) 👉 "[]" → Runs only once (on mount) 👉 "[value]" → Runs when value changes 👉 No dependency → Runs on every render ❌ 💻 Example: useEffect(() => { fetchData(); }, []); 🔹 Common Mistake Forgetting dependency array → leads to multiple API calls 😵 🚀 Pro Tip: Always think: “When should this effect run?” Then set dependencies accordingly. 💬 What mistake did you make when learning useEffect? 😄 #reactjs #javascript #webdevelopment #mern #developers
To view or add a comment, sign in
-
One small React habit that improved my code a lot: Stop putting everything in one component. Earlier, I used to write large components with too much logic. It worked… but became messy very quickly. Now I try to: • Break UI into smaller components • Keep logic separate • Reuse components wherever possible This makes the code cleaner and easier to scale. If you're learning React, start thinking in components, not pages. #reactjs #frontend #webdevelopment #javascript
To view or add a comment, sign in
-
-
Why do we need to call 'super(props)' in the constructor of a React component? JavaScript classes aren't magic. They are just syntactic sugar over prototypes. If you are still using (or have used) Class Components in React, you have likely typed 'super(props)' a thousand times. But do you actually know what happens if you forget it? In JavaScript, you cannot use the keyword 'this' in a constructor until you have called the parent constructor. Since your component extends 'React.Component', calling 'super()' is what actually initializes the 'this' object. If you try to access 'this.state' or 'this.props' before that call, JavaScript will throw a ReferenceError and crash your app. But why pass 'props' into it? React sets 'this.props' for you automatically after the constructor runs. However, if you want to access 'this.props' inside the constructor itself, you must pass them to 'super(props)'. If you just call 'super()', 'this.props' will be undefined until the constructor finishes execution. Most of us have moved to Functional Components where this isn't an issue. But understanding these fundamentals is what separates a developer who just writes code from one who understands the runtime. #ReactJS #Javascript #SoftwareEngineering #WebDevelopment #Coding #ProgrammingTips
To view or add a comment, sign in
-
🚨 I see developers jumping straight into React and Next.js — and struggling to debug the simplest bugs. Here's the uncomfortable truth: 👉 React is just JavaScript. 👉 Next.js is just JavaScript. 👉 Every framework you'll ever use... is just JavaScript. If your JS fundamentals are weak, you're building on sand. 🏚️ Here's what actually happens when you skip the basics: ❌ You copy-paste code without understanding it ❌ You can't debug — only Google ❌ Every new framework feels like starting from zero But when you master JS fundamentals first: ✅ Closures → you understand React hooks ✅ Event loop → you understand async/await & API calls ✅ Prototypes → you understand how JS objects really work ✅ Array methods → you write cleaner, readable React components Frameworks come and go. JavaScript stays. Invest time in the fundamentals. Your future self — and your teammates — will thank you. 🙌 ───────────────── 💬 Drop a comment: What JS concept clicked everything into place for you? #JavaScript #WebDevelopment #React #NextJS #Frontend #100DaysOfCode
To view or add a comment, sign in
More from this author
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
Nicely explained