I recently explored how JavaScript’s number type behaves under IEEE 754-and what I found surprised me. While most developers (myself included) focus on ECMAScript compliance, I learned that even standards-compliant code can produce unexpected results in mission-critical systems. Here is what I learned, with real-world examples that show why precision matters. For example, 0.1 + 0.2 === 0.3 returns false in JavaScript due to binary floating-point precision. This is not a bug-it is IEEE 754 doing its job. IEEE 754 in Action: Unsafe comparison const a = 0.1; const b = 0.2; const sum = a + b; console.log(sum); // 0.30000000000000004 console.log(sum === 0.3); // false Safe Comparison Using Tolerance function nearlyEqual(x, y, epsilon = 1e-10) { return Math.abs(x - y) < epsilon; } console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true This method checks if two numbers are close enough, which is the recommended approach for comparing floats. Safer Arithmetic with Integers const priceCents = 10 + 20; // 0.1 + 0.2 -> 10 + 20 const totalCents = priceCents * 100; // 3000 console.log(totalCents / 100); // 30 Use integers for money, counts, and critical logic to avoid rounding surprises. Decimal Libraries for Precision HTML <script type="module"> import Decimal from ''https://lnkd.in/gi4T53Fe'; const x = new Decimal('0.1'); const y = new Decimal('0.2'); const z = x.plus(y); console.log(z.toString()); // "0.3" </script> /* Use Node.js with ES Modules If you're using Node.js, either: Rename your file to .mjs Or add "type": "module" to your package.json */ import Decimal from 'decimal.js'; const x = new Decimal('0.1'); const y = new Decimal('0.2'); const z = x.plus(y); console.log(z.toString()); // "0.3" // Use require() in CommonJS (Node.js) const Decimal = require('decimal.js'); const x = new Decimal('0.1'); const y = new Decimal('0.2'); const z = x.plus(y); console.log(z.toString()); // "0.3" Libraries like decimal.js or Big.js offer exact decimal arithmetic, ideal for financial and mission-critical applications. This got me curious about real-world consequences of precision loss. I came across examples like: Patriot Missile Failure (1991): 0.34 sec drift due to rounding -> 28 lives lost Ariane 5 Rocket Explosion (1996): float-to-int overflow -> $370M loss Knight Capital (2012): float error in trading logic -> $440M loss in 45 mins Medical devices: insulin pumps miscalculating dosage due to float rounding These are not edge cases-they are reminders that even basic arithmetic can be dangerous in the wrong context. I am not an IoT or finance expert, but this learning made me rethink how I handle numbers in code. For critical logic, I now prefer: Using integers (e.g., cents instead of dollars) Leveraging BigInt or libraries like decimal.js Adding runtime checks for IEEE 754 compliance Avoiding implicit float-to-int conversions Have you ever run into float precision issues in your own projects?
How JavaScript's Number Type Behaves Under IEEE 754
More Relevant Posts
-
#9: From Loop Newbie to Array Method Pro in JavaScript! 🚀 Today’s journey took me from basic loops to mastering powerful array methods. If you’ve ever wondered when to use for…of, for…in, forEach, map, filter, or reduce — this post is for YOU 👇 🔁 1. for…of – Best for Iterating Over Iterables (Array / Map) ✅ Returns full value ✅ Can use destructuring in Maps for (const [key, value] of myMap) { console.log(key, value); } ❌ Doesn’t work on plain objects (not iterable). 📍 2. for…in – Works on Objects & Arrays (Keys Only) ✅ Best for objects: for (const key in myObject) { console.log(key, myObject[key]); } ⚠ On arrays, it gives indexes, not values. ❌ Doesn’t work on Map. 📦 3. forEach() – Simple, Clean, No Return ✅ Great for looping arrays ✅ Accepts callback (value, index, array) ✅ Can pass an external function coding.forEach((item, index, arr) => console.log(item, index)); ❌ Doesn’t return anything (undefined always). 🗺️ 4. map() – Returns a New Array ✅ 🔹 Used when you want to transform data. const newArr = nums.map(num => num * 2); ✅ map() → RETURNS ❌ forEach() → DOES NOT RETURN 🧽 5. filter() – Keeps Only What Matches ✅ 🔍 Creates an array based on a condition. const filtered = nums.filter(num => num > 4); ✅ Returns only items that meet criteria. ⛓️ 6. Method Chaining = Cleaner Power Moves ⚡ const result = nums .map(num => num * 10) .map(num => num + 1) .filter(num => num > 50); 📉 7. reduce() – Converts Everything to a Single Value Used for totals, sums, or combining data. const total = prices.reduce((acc, curr) => acc + curr, 0); ✅ Perfect for shopping cart totals, analytics, etc. 🎯 Where You Stand Now: Level → Concept 🟢 Beginner → for...in, for...of 🟡 Intermediate → forEach, map, filter 🔴 Pro → reduce, chaining, destructuring in loops ✨My Takeaway: Once you understand array methods like map, filter, and reduce, you write less code, cleaner logic, and think more like a JavaScript pro. 💡 🧠 Which one confused you the most when you started learning loops in JS? Comment below — let’s grow together! 👇🔥 #JavaScript #WebDevelopment #LearningEveryday #Frontend
To view or add a comment, sign in
-
🚀 Deep Clone an Object in JavaScript (without using JSON methods!) Ever tried cloning an object with const clone = JSON.parse(JSON.stringify(obj)); and realized it breaks when you have functions, Dates, Maps, or undefined values? 😬 Let’s learn how to deep clone an object the right way - without relying on JSON methods. What’s the problem with JSON.parse(JSON.stringify())? t’s a quick trick, but it: ❌ Removes functions ❌ Converts Date objects to strings ❌ Skips undefined, Infinity, and NaN ❌ Fails for Map, Set, or circular references So, what’s the alternative? ✅ Option 1: Use structuredClone() (Modern & Fast) Available in most modern browsers and Node.js (v17+). structuredClone() handles Dates, Maps, Sets, and circular references like a champ! structuredClone() can successfully clone objects with circular references (where an object directly or indirectly references itself), preventing the TypeError: Converting circular structure to JSON that occurs with JSON.stringify(). ✅ Option 2: Write your own recursive deep clone For learning purposes or environments without structuredClone(). ⚡ Pro Tip: If you’re working with complex data structures (like nested Maps, Sets, or circular references), use: structuredClone() It’s native, fast, and safe. Final Thoughts Deep cloning is one of those "simple but tricky" JavaScript topics. Knowing when and how to do it properly will save you hours of debugging in real-world projects. 🔥 If you found this helpful, 👉 Follow me for more JavaScript deep dives - made simple for developers. Let’s grow together 🚀 #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #LearnJavaScript #Programming #DeveloperCommunity #AkshayPai #WebDev #ES6 #JSDeveloper #JavaScriptTips #JavaScriptObjects #JavaScriptClone #JavaScriptCloneObject
To view or add a comment, sign in
-
-
🚀✨ JavaScript BASICS:: Objects & Prototypes:- What, Why, and How 🚀✨ 🤔 What are They? 🤔 - Objects Think of objects as boxes 📦 that hold related info (data) and actions (functions). Example: a person with name and age stored as properties. - Prototypes Prototypes are “blueprints” 🏗️ or hidden links objects use to share methods and properties. They let objects borrow functionality instead of copying it everywhere. 💡Why Do We Need Them? 💡 - Objects They organize your code by grouping related data and functions together. Imagine grouping your contacts with their phone numbers and emails neatly in one place! - Prototypes They save memory and avoid repetition by sharing common methods across many objects. Instead of rewriting the same function in every object, just write it once on the prototype! 🔨 How to Use Them? 🔨 - Objects Create with simple syntax using {} or constructor functions: /*___________Code_Start___________*/ const person = { name: "Anna", age: 25 }; function Person(name) { this.name = name; } const bob = new Person("Bob"); /*___________Code_End___________*/ - Prototypes Add shared methods to prototypes so every object can use them: /*___________Code_Start___________*/ Person.prototype.greet = function() { console.log(`Hello, I am ${this.name}`); }; bob.greet(); // Hello, I am Bob /*___________Code_End___________*/ Or create objects linked to prototypes: /*___________Code_Start___________*/ const animal = { speak() { console.log("Animal sound"); } }; const dog = Object.create(animal); dog.speak(); // Animal sound /*___________Code_End___________*/ In short: - Objects = your data containers 📦 - Prototypes = shared blueprints 🏗️ Together they make your JavaScript code smarter, cleaner, and faster! ⚡ ⚠️ Note:- This post is for #interview preparation purposes only. Avoid using prototype manipulation techniques like Object.setPrototypeOf() in real-time production code due to performance and maintainability issues. #JavaScript #CodingBasics #Objects #Prototypes #BeginnerFriendly #ReactJS #ReactNative #LearnToCode #DevTips
To view or add a comment, sign in
-
⚡ JavaScript Typed Methods — Working with the Right Data! 💻 Ever heard of typed methods in JavaScript? 🤔 They’re built-in ways to work with specific data types like numbers, strings, arrays, and more! Each data type has its own special methods to make your coding life easier. --- 💬 Let’s Break It Down 👇 🧮 Number Methods: Used for math and conversions. let num = 3.14159; console.log(num.toFixed(2)); // 3.14 console.log(Number.isInteger(num)); // false 🧠 Tip: toFixed() rounds numbers; isInteger() checks if it’s a whole number! --- ✍️ String Methods: Used for text manipulation. let name = "JavaScript"; console.log(name.toUpperCase()); // JAVASCRIPT console.log(name.includes("Script")); // true 🔥 Great for formatting and searching text! --- 📦 Array Methods: Help manage lists of data. let fruits = ["apple", "banana", "mango"]; fruits.push("orange"); console.log(fruits.join(", ")); // apple, banana, mango, orange ✅ push() adds new items; join() combines them into one string! --- 💡 Object Methods: Used to handle key-value pairs. let user = { name: "Azeez", age: 25 }; console.log(Object.keys(user)); // ["name", "age"] 🔍 Helps you explore and manage object data efficiently. --- 🚀 Why Typed Methods Matter: They make your code cleaner, faster, and smarter 💪 Instead of writing long custom functions, you use built-in tools that JavaScript already provides! --- 🔥 In short: Typed methods are like mini superpowers for each data type — once you know them, coding becomes way easier and more fun! 😎 #JavaScript #CodingTips #WebDevelopment #JSBeginners #Frontend #LearnJS #CodeSmart
To view or add a comment, sign in
-
-
“Why does this behave so weird in JavaScript? 🤯 Let’s finally make sense of it!” If you’ve ever shouted at your screen because this suddenly became undefined — you’re not alone 😅 Let’s break down how this works across different scenarios with simple examples 👇 🧩 1️⃣ Arrow Function Defined Directly in Object const person = { name: "Suverk", greet: () => console.log(`Hi ${this.name}`) }; person.greet(); // ❌ undefined 🧠 Why? Arrow functions don’t have their own this. They lexically inherit this from their surrounding scope — which here is the global (not person). ✅ Fix: Use a regular function: greet() { console.log(`Hi ${this.name}`); } 🧩 2️⃣ Arrow Function Inside a Regular Method const person = { name: "Suverk", greet: function() { const arrow = () => console.log(this.name); arrow(); } }; person.greet(); // ✅ "Suverk" 🧠 Why? The arrow function inherits this from where it was created — inside greet, and this inside greet = person. ✅ Works perfectly because of lexical scoping. 🧩 3️⃣ Regular Function Inside Another Regular Function const person = { name: "Suverk", greet: function() { function inner() { console.log(this.name); } inner(); } }; person.greet(); // ❌ undefined 🧠 Why? When you call inner() as a plain function, it’s not attached to any object. So this defaults to global (or undefined in strict mode). ✅ Fixes: // Option 1 const self = this; function inner() { console.log(self.name); } // Option 2 function inner() { console.log(this.name); } inner.bind(this)(); // Option 3 const inner = () => console.log(this.name); 🧩 4️⃣ Detached Method Reference const person = { name: "Suverk", greet() { console.log(this.name); } }; const use = person.greet; use(); // ❌ undefined 🧠 Why? this depends on how a function is called. You’ve just taken the function reference — the link to person is gone. ✅ Fix: const use = person.greet.bind(person); use(); // ✅ "Suverk" In JavaScript, this depends on how a function is called — except for arrow functions, which depend on where they’re defined. 💬 Have you ever been tricked by this before? Drop your comment below 👇 — let’s make others learn faster than we did 😅 #JavaScript #Frontend #WebDevelopment #Angular
To view or add a comment, sign in
-
⚡ SK – Mastering Array Methods: map(), filter(), reduce(), and find() in JavaScript 💡 Explanation (Clear + Concise) Array methods are the power tools of JavaScript — they make data transformation cleaner, functional, and readable. As a React developer, you use them daily — to render lists, filter data, and compute state. 🧩 Real-World Example (Code Snippet) const products = [ { name: "Laptop", price: 1000 }, { name: "Phone", price: 600 }, { name: "Tablet", price: 400 }, ]; // 🗺️ map() – transform data const productNames = products.map(p => p.name); // 🔍 filter() – select matching items const affordable = products.filter(p => p.price < 800); // ➕ reduce() – compute totals const totalPrice = products.reduce((sum, p) => sum + p.price, 0); // 🧭 find() – get first matching item const phone = products.find(p => p.name === "Phone"); console.log(productNames, affordable, totalPrice, phone); ✅ Why It Matters in React: map() is used to render lists dynamically filter() helps with search or category filtering reduce() is great for analytics (total revenue, cart total, etc.) 💬 Question: Which array method do you use most in your React projects — and why? 📌 Follow Sasikumar S for more daily dev reflections, real-world coding insights & React mastery. 🤝 Connect Now: sasiias2024@gmail.com 💟 Visit: sk-techland.web.app ❤️ Follow our LinkedIn Page for more React & JavaScript growth tips. #JavaScript #ReactJS #FrontendDeveloper #ArrayMethods #CodingJourney #WebDevelopment #JSFundamentals #CareerGrowth #map #filter #reduce
To view or add a comment, sign in
-
-
🧠 JavaScript typeof Explained: Understanding Data Types Made Simple When coding in JavaScript, one of the most common tasks is checking what type of data you’re working with. That’s where the typeof operator comes in! --- 💡 What is typeof? typeof is a built-in JavaScript operator that tells you the type of a variable or value. It’s like asking JavaScript: > “Hey, what exactly is this thing I’m working with?” --- 🧩 Syntax: typeof variableName; or typeof(value); --- 🔍 Examples: typeof "Hello"; // "string" typeof 42; // "number" typeof true; // "boolean" typeof {}; // "object" typeof []; // "object" (arrays are technically objects) typeof undefined; // "undefined" typeof null; // "object" (a known JavaScript quirk!) typeof function(){}; // "function" --- 🪄 Why It Matters The typeof operator is super useful when: Debugging your code 🐞 Validating user input 🧍♂️ Writing clean, bug-free programs 💻 --- ⚙️ Pro Tip: If you want to check if something is an array, don’t use typeof. Instead, use: Array.isArray(value); --- 🚀 Final Thoughts: Understanding the typeof operator helps you master JavaScript’s dynamic typing system. It’s a simple but powerful tool for keeping your code organized and error-free. Start experimenting with typeof today—you’ll quickly see how handy it is! #codecraftbyaderemi #webdeveloper #html #javascript #frontend
To view or add a comment, sign in
-
-
Creating a Modelica web app by chatting with Lovable At the Modelica & FMI conference, Martin Otter and I gave a tutorial about making a customized web app for Modelica simulations using the Modiator API for compilation and simulation in the browser. We provided simple templates showing the Modiator coupling. We had also experimented with using Perplexity and GitHub Copilot for generating the needed HTML and JavaScript code. However, the coupling to the Modiator API needed to be done with JavaScript coding. The Lovable tool (https://lovable.dev/) promises "Create apps and websites by chatting with AI". So let's explore this. Question: "Make a web app for simulation of Modelica models". I got a web app with an editor for Modelica text, input fields for simulation control and a plot window (similar to Modicalc 👏). A second order spring damper system was shown in the text editor and when pushing the Simulate button, the result was plotted. Great! The results appeared quickly so I asked: Question: "How is simulation done?". Answer: "Currently, the simulation is mock/simulated - it doesn't actually parse or execute the Modelica code you see in the editor. ... Would you like me to explain how to integrate a real Modelica simulation engine". Question: "How to use Modiator" Answer: "I'm not familiar with "Modiator" - could you clarify what you're referring to?" Question: "I mean the api of https://lnkd.in/dVTaBBFM." Answer: "I couldn't find public API documentation for https://lnkd.in/dVTaBBFM. ..." Lovable asked for documentation or "Example API calls" I sent one of the templates we used in the tutorial (HTML, Javascript and Modelica code) Answer: "Integrated Modiator API for real Modelica simulations—your app now runs actual model simulations instead of mock data." Question: "It says that simulation was successful, but I don't se any plots" After some iterations regarding logs, I wrote: Question: "Note that for each variables in the trajectories, the times are stored in the times array and the response is stored in the response array. ... Would you plot x and v?" See result below: It worked out remarkable well. It is certainly worth exploring more regarding how to control features, layout, diagnostics and styling. But it is impressive how Lovable could utilize a template and a hint to figure enough about the Modiator API. (Partial API documentation is now published https://lnkd.in/duW_CVFr)
To view or add a comment, sign in
-
-
🧠 Chapter 2: Data Types + Type System 💻 JavaScript – Learn Everything Series #JavaScript #Coding #Cognothink Every value in JavaScript has a type. The type tells us what kind of data it is — a number, text, boolean, object, etc. There are two main types of data 👇 🔹 Primitive Types (stored directly) 1️⃣ String → Text "Hello", 'World' 2️⃣ Number → Any numeric value 5, -10, 3.14 3️⃣ Boolean → True or False true, false 4️⃣ Undefined → Declared but not assigned let x; // undefined 5️⃣ Null → Empty value on purpose let y = null; 6️⃣ Symbol → Unique identifier 7️⃣ BigInt → Very large number 12345678901234567890n 🔹 Reference Types (stored by reference) 📦 Object { name: "Harsh", age: 26 } 📦 Array [10, 20, 30] 📦 Function function greet() {} 🧩 These are stored in memory as references, not copied directly. 🔍 typeof Operator Check what type a value is: typeof "Hi" // "string" typeof 99 // "number" typeof true // "boolean" typeof undefined // "undefined" typeof null // "object" ❗ (old JS bug) typeof [] // "object" typeof {} // "object" typeof function(){}// "function" 🔁 Type Conversion (Coercion) JavaScript sometimes changes types automatically: "5" + 1 // "51" → number to string "5" - 1 // 4 → string to number true + 1 // 2 null + 1 // 1 undefined + 1 // NaN ⚠️ Be careful! It can be confusing. ⚖️ == vs === 5 == "5" // true (checks value only) 5 === "5" // false (checks value + type) ✅ Always use === for clear and correct results. 🧪 NaN – Not a Number typeof NaN // "number" Funny but true — “Not a Number” is actually a number 😄 💡 Truthy and Falsy Falsy values → false, 0, "", null, undefined, NaN Everything else is truthy — even "0", "false", [], {} if ("0") console.log("Runs"); // "0" is truthy ✨ In Short ✅ 7 Primitive Types ✅ 3 Reference Types ✅ Use typeof to check ✅ Use === for safety ✅ Watch out for coercion 💬 Which data type or bug confused you the most when you started learning JavaScript? Share in the comments 👇 #JavaScript #WebDevelopment #Coding #LearnJS #Cognothink #Frontend #Backend #FullStack #JSBasics
To view or add a comment, sign in
-
🧠 Understanding JavaScript toString(): Converting Data to Text In JavaScript, everything revolves around data — and sometimes, you need to turn that data into text. That’s where the toString() method comes in! The toString() method converts numbers, booleans, arrays, and objects into string format, making them easy to display or manipulate. --- 🔹 Basic Syntax variable.toString() This simply returns the string version of the variable. --- 🧩 Example 1: Numbers let num = 100; console.log(num.toString()); // "100" Now, the number 100 becomes the string "100". --- 🧩 Example 2: Booleans let isActive = true; console.log(isActive.toString()); // "true" --- 🧩 Example 3: Arrays let fruits = ["apple", "banana", "mango"]; console.log(fruits.toString()); // "apple,banana,mango" Arrays are converted into comma-separated strings. --- 🧩 Example 4: Dates let today = new Date(); console.log(today.toString()); // "Wed Oct 08 2025 10:30:00 GMT+0000 (Coordinated Universal Time)" --- 💡 Why Use toString()? ✅ Display data on web pages ✅ Convert values before concatenation ✅ Debug or log readable outputs --- 🚀 Quick Tip You can also use String() (a global function) to achieve the same result: let value = 42; console.log(String(value)); // "42" --- In short: The toString() method is your go-to tool whenever you need to see what your data looks like in text form. It’s small but mighty — and essential for any JavaScript developer! 💪 #JavaScript #FrontendDevelopment #WebDevelopment #CodingTips #LearnJavaScript
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