Type Safety and Runtime Validation in JavaScript with Zod and JSDoc Combining Zod's runtime validation with JSDoc's type annotations to achieve type safety in JavaScript without TypeScript. https://lnkd.in/deBkW-Gj #javascript
Type Safety with Zod & JSDoc in JavaScript
More Relevant Posts
-
𝗧𝗶𝗽𝘀 𝗳𝗼𝗿 𝗪𝗿𝗶𝘁𝗶𝗻𝗴 𝗕𝗲𝘁𝘁𝗲𝗿 𝗖𝗼𝗱𝗲 𝗳𝗮𝘀𝘁 You're stuck with JavaScript errors. You see "Cannot read property" errors. This happens when your code expects something to exist, but it does not. TypeScript can help you avoid these errors. TypeScript is like a safety net for your code. It checks for bugs before you run your code. Here's what it does: - Tells you when you're accessing properties that do not exist - Helps with autocompleting your objects - Documents your code through types - Helps you refactor your code without fear To get started with TypeScript, you need: - Cheatsheets for syntax - The handbook to get oriented - A solid grasp of tsconfig.json Start with a small project and use strict mode. You will learn more from one strict project than from ten tutorials. Let's look at an example: fetching and displaying a user. We can define a User interface with id, name, and email. Then we can use this interface to fetch a user. TypeScript will catch typos and help with autocompleting. But we need to handle edge cases. We can use optional chaining to safely access properties. We can also use type guards to validate the API response at runtime. Some popular frameworks for TypeScript are: - Next.js / React with Zod or Valibot - NestJS with class-validator and class-transformer Remember to: - Use explicit interfaces - Check for null and undefined - Use union types for all states - Validate API responses at runtime Source: https://lnkd.in/g3KQZXbV
To view or add a comment, sign in
-
When I first learned JavaScript async code… my functions looked like this: then → then → then → then 😭 Classic Callback Hell. It was unreadable and impossible to debug. So I broke everything down and created a beginner-friendly guide on: 👉 Promises 👉 Async/Await 👉 Writing clean async code If you’re learning JS or React, this will save you hours. Read here: 🔗 https://lnkd.in/gs_yQ_Mp #JavaScript #FrontendDeveloper #Coding #LearnToCode
To view or add a comment, sign in
-
TypeScript has a reputation problem! People think it's JavaScript with extra syntax to make the compiler happy. It's not. Used right, it changes how you design code, not just how you annotate it. Some myths: "Types make your code safer"... Only at compile time. They vanish at runtime. Your API can still return garbage. "TypeScript catches bugs"... Only the bugs you model. any and as put you right back in JavaScript with extra steps. "Strict mode is overkill"... It's the whole point. Without it, you're not using TypeScript. You're using TypeScript-flavored JavaScript. The article walks through one function, refactored four times. Same fetch call. Each version catches more bugs. The final version validates at runtime, not just compile time. Full article: https://lnkd.in/gh-v7EZu #TypeScript #WebDev #CleanCode
To view or add a comment, sign in
-
If you work with JavaScript, you know how often you forget small but important details. I put together a complete JavaScript quick reference guide that covers: – fundamentals – arrays & objects – async / await – DOM manipulation – advanced concepts with real examples It’s meant to be bookmarked and reused. Read here: https://lnkd.in/gNun7kxB
To view or add a comment, sign in
-
New to JavaScript? Learn how comparison operators like ==, ===, >, and < really work through simple, hands-on examples. Understand your code’s decisions—read the full guide now!
To view or add a comment, sign in
-
🧠 The Call Stack in JavaScript — Simplified JavaScript executes code using something called the call stack. It follows one simple rule: Last In, First Out (LIFO). Every time a function runs, it gets pushed onto the stack, and when it finishes, it gets popped off. Understanding this small concept makes debugging errors like “Maximum call stack size exceeded” much easier. It also helps you truly understand recursion and how JavaScript executes code step by step. Read more here 👉 https://lnkd.in/g2CCpCqs #JavaScript #WebDevelopment #Programming
To view or add a comment, sign in
-
Ever wondered what actually happens behind the scenes when JavaScript runs your code? 🤔 How Variables & Functions Work Behind the Scenes in JavaScript Today I focused on understanding what actually happens inside the JavaScript engine when we write variables and functions — and it completely changed how I read JS code. 🧠 Step 1: JavaScript Creates an Execution Context Before executing any code, JavaScript creates an Execution Context. This happens in two phases: 1. Creation Phase (Memory Allocation Phase) In this phase, JavaScript scans the entire code before running it and prepares memory. ✔ Variables var variables are allocated memory and initialized with undefined let and const are also allocated memory, but they stay in the Temporal Dead Zone (TDZ) until initialized ✔ Functions Function declarations are stored fully in memory (function body included) Function expressions & arrow functions behave like variables and depend on var / let / const 👉 This is the real reason hoisting exists. 2.Execution Phase (Code Runs Line by Line) Now JavaScript starts executing the code: Variables get their actual values Functions are executed when they are called A new Function Execution Context is created for every function call Each context is pushed to the Call Stack After execution, it is removed from the stack Why Functions Can Be Called Before Declaration? because function declarations are fully hoisted during the creation phase. 💡 Key Takeaways JavaScript doesn’t execute code directly — it prepares first Hoisting is a byproduct of the creation phase var, let, and const differ because of how memory is allocated Understanding execution context makes debugging much easier. Mastering the basics is what truly levels up a developer. Thanks to Anshu Pandey and Sheryians Coding School #JavaScript #JavaScriptbasics #ES6 #JSEngine #coding
To view or add a comment, sign in
-
-
“JS Fundamentals Series #1: Execution Context & Call Stack” Behind every line of JavaScript lies a hidden world of execution contexts and stacks — let’s uncover it 👇 Whenever a JavaScript program runs, the JS engine creates a Global Execution Context (GEC), a Global Object, and a special this variable. Think of the Execution Context as a big container with two parts: 1. Memory Component 2. Code Component 🔄 The whole JavaScript code gets executed in two phases:- 1. Memory creation phase: All the variables and functions are assigned memory in the form of "key: value" pairs inside the Memory Component. Variables are assigned a special keyword called "undefined" until their value is initialized. Functions are assigned their whole body as it is. 2. Code execution phase: Inside Code Component, each piece of code gets executed, only one command will get executed at a time and won't move onto the next until the current command is executed. Whenever a function is called/invoked, a new Local Execution Context is created inside the Code Component. 📚 Call Stack This is where all the Execution Contexts are executed in a particular order. It follows a principle known as LIFO - Last In First Out. 💡 Why this matters: Understanding the call stack helps me debug recursion errors, async issues, and write cleaner, more predictable code. 🚀 Next up: I’ll dive into Scope Chain & Lexical Environment. Stay tuned! #JavaScript #Frontend #WebDevelopment #NamasteJS #LearningJourney
To view or add a comment, sign in
-
-
🧠 Call Stack, Queues & Task Types — The Foundation of Async JavaScript To understand async behavior in Node.js, you need to know four core parts: • Call Stack • Callback Queue • Microtask Queue • Macrotask Queue Let’s break them down simply. 📍 Call Stack — Where code executes The Call Stack is where JavaScript runs functions. It follows one rule: 👉 Last In, First Out (LIFO) Example: function one() { two(); } function two() { console.log("Hello"); } one(); Execution: • one() pushed • two() pushed • console.log() runs • two() removed • one() removed If the stack is busy, nothing else can run. ⚡ Microtask Queue (Higher Priority) This queue is more important than the macrotask queue. Examples: • Promise.then() • queueMicrotask() • process.nextTick() (Node-specific) Microtasks run: 👉 Immediately after the stack becomes empty 👉 Before any macrotask runs 📬 Callback Queue (Macrotask Queue) This is where async callbacks wait. Examples: • setTimeout • setInterval • setImmediate These do NOT go to the stack directly. They wait in the Macrotask Queue. 🔄 Execution Order Rule Every cycle: 1️⃣ Run synchronous code (Call Stack) 2️⃣ Empty all microtasks 3️⃣ Run one macrotask 4️⃣ Repeat This priority system is why Promise callbacks run before setTimeout. 🎯 Key Insight JavaScript isn’t “randomly async”. It follows a strict priority system: Call Stack → Microtasks → Macrotasks #Nodejs #Javascript #Backenddevelopment #Webdevelopment #LearningByDoing
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
Another approach, which I borrowed from the world of data-oriented programming, is to type everything up with Zod, but only validate during local development (and not prod) due to obvious perf. concerns. I ended up publishing the following utility to that end: https://github.com/schalkventer/zod-dev