💡 Think semicolons don’t matter in JavaScript? Think again. Here’s a subtle but powerful concept: Automatic Semicolon Insertion (ASI). At first glance, this code looks perfectly fine: const arr = [1, 2, 3] (function () { console.log("Hello 👋") })() But instead of printing "Hello 👋", it throws: ❌ TypeError: arr is not a function 👉 Why? JavaScript doesn’t automatically insert a semicolon after the array declaration. So it interprets the code like this: const arr = [1, 2, 3](function () { ... })() Now it tries to call arr as a function — and arrays aren’t callable. ✅ The Fix is simple: const arr = [1, 2, 3]; (function () { console.log("Hello 👋") })() Now everything works as expected. 🔍 Key Takeaways: • JavaScript uses ASI, but it’s not always reliable • Starting a line with (, [, or + can cause unexpected behavior • Missing semicolons can silently change how your code is interpreted • Always be explicit when your next line starts with an IIFE or expression 🚀 Pro Tip: Even if you prefer a “no-semicolon” style, make sure to add one before IIFEs or tricky expressions to avoid bugs that are hard to debug. ⚡ JavaScript isn’t just about writing code — it’s about understanding how the engine reads your code. #JavaScript #WebDevelopment #CodingTips #Frontend #Programming #CleanCode
JavaScript Semicolon Insertion Gotcha: Avoid Silent Bugs
More Relevant Posts
-
Understanding Reflow vs Repaint is crucial if you want to write high-performance front-end code. Every time JavaScript updates the DOM, the browser may need to recalculate layout (reflow) or just update pixels (repaint). Knowing the difference helps you avoid unnecessary rendering work and build faster, smoother applications. Small optimizations here can make a big impact on user experience #JavaScript #WebDevelopment #FrontendDevelopment #PerformanceOptimization #WebPerformance #Reflow #Repaint #DOM #BrowserRendering #Frontend #Coding #SoftwareDevelopment #FullStackDevelopment #Programming #Developers #TechEducation https://lnkd.in/gr3yq4U7
To view or add a comment, sign in
-
🚀 Understanding Prototypes in JavaScript (Simple Breakdown) 🔹 Every JavaScript object has a hidden property called [[Prototype]] 👉 It links to another object and allows inheritance 💡 Why Prototypes? Instead of creating duplicate methods for every object, JavaScript shares them using prototypes → saves memory ✅ 🔹 Example: toString() isn’t inside your object, but JS finds it through the prototype chain object → prototype → null 🔗 Prototype Chain (Search Order) Check the object Check its prototype Continue up the chain Stop at null 🔹 Constructor + Prototype Functions can use prototype to share methods: function Person(name) { this.name = name; } Person.prototype.sayHello = function() { console.log("Hello " + this.name); }; ✔ Method stored once, reused by all objects 🔹 proto vs prototype prototype → belongs to constructor __proto__ → belongs to object (actual link) p1.__proto__ === Person.prototype // true 🔥 Key Takeaways ✔ JavaScript uses prototype-based inheritance ✔ Objects inherit via prototype chain ✔ Memory efficient (shared methods) ✔ Core concept for interviews & real-world JS #JavaScript #WebDevelopment #Frontend #Coding #LearnToCode #Developers
To view or add a comment, sign in
-
💡 Short Circuiting in JavaScript — Explained Simply In JavaScript, I came across a powerful concept called Short Circuiting. 👉 In simple words: JavaScript stops checking further values as soon as the result is decided. 🔹 OR (||) Operator It returns the first TRUE (truthy) value it finds. Example: console.log(false || "Javascript"); ✔️ Output: "Javascript" Another example: console.log(false || 10 || 7 || 15); ✔️ Output: 10 👉 Why? Because JavaScript finds 10 (true value) and stops checking further values 🔹 My Practice Code 👨💻 console.log("Short circuit in OR operator"); console.log(false || "Javascript"); console.log(false || "OR Operator"); console.log(false || 3); console.log(false || 10 || 7 || 15 || 20); // short circuit in OR operator console.log(false || "Javascript - client side scripting language" || "HTML - structure of web page" || "CSS - Cascading Style Sheet" || "Bootstrap - Framework of CSS"); 🔹 Recap: ✔️ JavaScript returns the first truthy value ✔️ It does not check remaining values once result is found ✔️ This makes code faster and efficient 📌 In simple words: Short Circuiting = JavaScript stops early when result is found #JavaScript #WebDevelopment #Coding #Learning #Frontend #100DaysOfCode
To view or add a comment, sign in
-
🔍 JavaScript Concept You Might Have Heard (First-Class Functions/Citizens) You write this: function greet() { return "Hello"; } const sayHi = greet; console.log(sayHi()); // ? 👉 Output: Hello Wait… 👉 We assigned a function to a variable? 👉 And it still works? Now look at this 👇 function greet() { return "Hello"; } function execute(fn) { return fn(); } console.log(execute(greet)); // ? 👉 Passing function as argument? 👉 And calling it later? This is why JavaScript functions are called First-Class Functions 📌 What does that mean? 👉 Functions are treated like any other value 📌 What can you do with them? ✔ Assign to variables ✔ Pass as arguments ✔ Return from another function ✔ Store inside objects/arrays Example 👇 function outer() { return function () { return "Inside function"; }; } console.log(outer()()); // ? 👉 Function returning another function 📌 Why do we need this? 👉 This is the foundation of: ✔ Callbacks ✔ Closures ✔ Functional programming ✔ Event handling 💡 Takeaway: ✔ Functions are just values in JavaScript ✔ You can pass them, store them, return them ✔ That’s why they are “first-class citizens” 👉 If you understand this, you understand half of JavaScript 🔁 Save this for later 💬 Comment “function” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
Image Swap Functionality using JavaScript (getAttribute & setAttribute): I’m excited to share another JavaScript DOM project where I implemented an image swapping feature using getAttribute() and setAttribute(). In this project, there are two images, and when the “Swap Image” button is clicked: * The first image moves to the second position * The second image moves to the first position * This swapping continues on every click This project helped me understand how we can access and update element attributes dynamically to create interactive UI behavior. Key concepts I practiced: 1. DOM Manipulation – Selecting and updating elements dynamically 2. getAttribute() – Retrieving current image source values 3. setAttribute() – Swapping the src attributes between images 4. Event Handling – Performing actions on button click 5. Logic Building – Implementing swap functionality step by step Through this project, I clearly understood how getAttribute() and setAttribute() work and further strengthened my DOM manipulation and problem-solving skills. Building small projects like this is helping me gain more confidence in JavaScript. Checkout my full project code on github: https://lnkd.in/gqPQptPS Feedback and Suggestions are always welcome! 😊 #JavaScript #DOMManipulation #FrontendDevelopment #WebDevelopment #JavaScriptProjects #CodingJourney #LearningByDoing #BeginnerDeveloper #UIInteraction
To view or add a comment, sign in
-
🚀 CSS is getting smarter — almost like JavaScript!Did you know that modern CSS now supports conditional logic (like IF statements)? 🤯While we still don’t have a direct if...else syntax, features like: ✅ @supports → Apply styles if the browser supports a feature ✅ @container → Apply styles if the parent size matches ✅ :has() → Style elements if they contain specific content ✅ @media → Apply styles if screen conditions match…are making CSS more powerful than ever. 💡 Example: Default (acts like ELSE).card { background: white; }Condition (acts like IF)@media (max-width: 600px) { .card { background: black; } }✨ This shift is huge for frontend developers — less dependency on JavaScript for UI logic and more control directly in CSS.The future? Real @when / @else support is already being discussed 👀What do you think — will CSS replace small JS logic in UI soon?#CSS #WebDevelopment #Frontend #JavaScript #Programming #Developer #ReactJS
To view or add a comment, sign in
-
-
🔥 var vs let vs const in JavaScript (Explained Simply) Understanding the difference between `var`, `let`, and `const` is essential for writing clean and bug-free JavaScript code. Let’s break it down 👇 🔹 1️⃣ var #Example var name = "Amit"; var name = "Rahul"; // Re-declaration allowed ✅ Function scoped ✅ Can be re-declared and updated ⚠️ Hoisted with `undefined` ❌ Can cause unexpected bugs 👉 Avoid using `var` in modern JavaScript. 🔹 2️⃣ let #Example let age = 25; age = 30; // Update allowed ✅ Block scoped ❌ Cannot be re-declared in same scope ✅ Can be updated ✅ Safer than `var` 👉 Use `let` when the value needs to change. 🔹 3️⃣ const #Example const pi = 3.14; // pi = 3.1415; ❌ Error ✅ Block scoped ❌ Cannot be re-declared ❌ Cannot be updated ✅ Must initialize at declaration 💡 For objects/arrays → You can modify properties, but not reassign the reference. 🚀 Best Practice ✔️ Use `const` by default ✔️ Use `let` when reassignment is required ❌ Avoid `var` Writing cleaner code starts with choosing the right variable declaration. #JavaScript #WebDevelopment #Frontend #Programming #CodingTips #Developers
To view or add a comment, sign in
-
-
Day 3: Hoisting — The JavaScript "Magic" That Isn't Magic at All! 🎩✨ Today, I tackled one of the most famous (and often misunderstood) concepts in JavaScript: Hoisting. If you've ever wondered why you can call a function before you even define it in your code, you've witnessed Hoisting in action! 🤔 What is Hoisting? Hoisting is a mechanism where variables and function declarations are moved to the top of their containing scope during the Memory Allocation Phase, before the code even starts executing. 🔍 Under the Hood (The Execution Context) Remember the "Big Box" (Execution Context) from Day 1? Here is what happens during the Memory Phase: Variables (var): JS allocates memory for variables and initializes them with a special value: undefined. Functions: JS stores the entire function body in memory. This is why: Calling a function at Line 1 works perfectly! ✅ Accessing a var at Line 1 returns undefined instead of an error! ⚠️ 💻 The Browser Demo (The Call Stack) Watching this live in the Sources tab of Chrome DevTools was a game-changer. Seeing the Global scope populate with variables before the first line of code executed made everything click. 💡 Interview Tip: When asked "What is Hoisting?", don't just say "it moves code to the top." Better Answer: "Hoisting is the process where the JS Engine allocates memory for variables and functions during the Creation Phase of the Execution Context. This allows us to access functions and variables even before they are initialized in the code, though var will return undefined until the execution reaches its assignment." Next up: Diving into how let and const handle hoisting differently (The Temporal Dead Zone!). Are you a var, let, or const person? Let's discuss below! 👇 #JavaScript #WebDevelopment #Hoisting #NamasteJavaScript #CodingInterviews #FrontendEngineer #ProgrammingLogic #JSFundamentals
To view or add a comment, sign in
-
-
🧠 Day 22 — JavaScript Array Methods (map, filter, reduce) If you work with arrays, these 3 methods are a must-know 🚀 --- ⚡ 1. map() 👉 Transforms each element 👉 Returns a new array const nums = [1, 2, 3]; const doubled = nums .map(n => n * 2); console.log(doubled); // [2, 4, 6] --- ⚡ 2. filter() 👉 Filters elements based on condition const nums = [1, 2, 3, 4]; const even = nums.filter(n => n % 2 === 0); console.log(even); // [2, 4] --- ⚡ 3. reduce() 👉 Reduces array to a single value const nums = [1, 2, 3]; const sum = nums.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 6 --- 🧠 Quick Difference map → transform filter → select reduce → combine --- 🚀 Why it matters ✔ Cleaner & functional code ✔ Less loops, more readability ✔ Widely used in React & real apps --- 💡 One-line takeaway: 👉 “map transforms, filter selects, reduce combines.” --- Master these, and your JavaScript will feel much more powerful. #JavaScript #ArrayMethods #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
Ever felt like JavaScript is just… pretending to be object-oriented? Like you write a function, slap a .prototype on it, and boom - suddenly it's a “class”? 😄 Now enter the "new" keyword. And this is where things get interesting. Because "new" is not just syntax. It’s doing a bunch of hidden work for you. Let’s break it down: You write this: function User(name) { this.name = name; } const user1 = new User("John"); Looks simple, right? But under the hood, JavaScript is doing FOUR steps automatically: - It creates a brand new empty object - It links that object to User.prototype - It sets this inside User to that new object - It returns the object (unless you explicitly return something else) So essentially, "new" is like your invisible assistant. Without new, you'd have to manually do all of this: const obj = {}; Object.setPrototypeOf(obj, User.prototype); User.call(obj, "John"); And honestly… nobody wants to write that every time. - new is not about “creating a class instance” - It’s about orchestrating object creation + prototype linkage + execution context JavaScript doesn’t magically become OOP. It’s still doing what it always does - just giving us a shortcut. #JavaScript #WebDevelopment #Programming #Coding
To view or add a comment, sign in
Explore related topics
- Tips for Writing Readable Code
- Writing Functions That Are Easy To Read
- Writing Readable Code That Others Can Follow
- Coding Best Practices to Reduce Developer Mistakes
- How to Write Clean, Error-Free Code
- How to Add Code Cleanup to Development Workflow
- Writing Elegant Code for Software Engineers
- Advanced Techniques for Writing Maintainable Code
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