So you're trying to verify types in TypeScript - it's a thing. But here's the deal, JavaScript doesn't really care about types at runtime. TypeScript types are basically erased after compilation, leaving you with just JavaScript values. You can do runtime checks, though - like checking if something's a string with `typeof x === "string"`, or if it's a Date object with `x instanceof Date`. Or, you know, checking if an object has a certain property with `"swim" in animal`. And then there's the `animal.kind === "fish"` check - that's a good one too. TypeScript uses these checks to narrow down union types, which is pretty cool. For example, you can use `typeof` narrowing in a function like `padLeft` - it takes a padding value that can be either a number or a string, and an input string. Or, you can use `instanceof` narrowing in a function like `logValue` - it takes a value that can be either a Date object or a string. And then there's the `"in"` narrowing - that's useful when you have a type like `Fish` that has a `swim` method. You can also reuse a check across multiple places using type predicates - like the `isFish` function that checks if an animal is a fish. It's like, you can use it to filter an array of animals and get only the fish. If you can change the data shape, using a `kind` property is a good idea - like, you can have a `Fish` type with a `kind` property that's set to `"fish"`. It's just easier that way. So, to sum it up: use JavaScript checks to narrow types, and type predicates to reuse the narrowing - that's the way to do it. Check out this article for more info: https://lnkd.in/gFKxe3ZE #TypeScript #TypeVerification #JavaScript
TypeScript Types Erased at Runtime, Use JavaScript Checks
More Relevant Posts
-
So JavaScript has this thing called hoisting. It's like a behind-the-scenes magic trick. Variables and functions get moved to the top of their scope. This happens way before the code actually runs, during the memory creation phase. Only the declarations get hoisted, not the actual values. Think of it like setting up a stage - you're just putting the props in place, but not actually using them yet. JavaScript runs in two phases: memory creation and code execution. During the memory creation phase, variables declared with var are like empty boxes - they're initialized with undefined. Function declarations, on the other hand, are like fully formed actors - they're stored in memory, ready to go. This means you can access variables before you've even assigned a value to them. It's like trying to open an empty box - you'll just get undefined. But if you try to access a variable that doesn't exist at all, JavaScript will throw a ReferenceError - it's like trying to open a box that's not even there. Here's the thing: function declarations are fully hoisted, so you can call them before they're even declared. But function expressions are like variables - they're hoisted as undefined, so trying to call them as a function will throw a TypeError. For example, consider this code: var x = 7; function getName() {...}. You can call getName() before it's declared, and it'll work just fine. But if you try to access x before it's assigned a value, you'll just get undefined. It's all about understanding how hoisting works in JavaScript. Check out this article for more info: https://lnkd.in/g_Jh4Vd8 #JavaScript #Hoisting #Coding
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
-
-
Day 3: JavaScript Hoisting — Magic or Logic? Yesterday, we learned that JavaScript creates memory for variables before it executes the code. Today, let’s see the most famous (and sometimes confusing) result of that: Hoisting. What is Hoisting? Hoisting is a behavior where you can access variables and functions even before they are initialized in your code without getting an error. Wait... why didn't it crash? 🤔 If you try this in other languages, it might throw an error. But in JS: During Memory Phase: JS saw var x and gave it the value undefined. It saw the function getName and stored its entire code. During Execution Phase: When it hits console.log(x), it looks at memory and finds undefined. When it hits getName(), it finds the function and runs it! ⚠️ The "Let & Const" Trap Does hoisting work for let and const? Yes, but with a catch! They are hoisted, but they are kept in a "Temporal Dead Zone". If you try to access them before the line where they are defined, JS will throw a ReferenceError. Pro Tip: Always define your variables at the top of your scope to avoid "Hoisting bugs," even though JS "magically" handles them for you. Crucial Takeaway: Hoisting isn't code physically moving to the top; it’s just the JS Engine reading your "ingredients" before "cooking" (Phase 1 vs Phase 2). Did you know about the Temporal Dead Zone? Let me know in the comments! #JavaScript #WebDev #100DaysOfCode #Hoisting #CodingTips #FrontendDeveloper
To view or add a comment, sign in
-
-
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
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
-
JavaScript Fundamentals - Part 3 Hoisting It is behavior of processing declarations before executing code. In simple terms: - JavaScript knows about variables and functions before running the code - This happens during the memory creation phase of an execution context So, hoisting is not moving code upward rather its preparing memory upfront. Why hoisting exists - its is side effect of how JS creates execution contexts. Before execution: - memory is allocated - identifiers are registered - scope is set up This allows: - function calls before their definition - predictable scope resolution Hoisting by Declaration Type var hoisting console.log(a); var a = 10; What happens: - a is hoisted - initialized with undefined - assigned 10 during execution So, console.log(a); // undefined Function Declaration Hoisting sayHi(); function sayHi(){ console.log("Hi"); } What happens: - entire function is hoisted - function can be called before declaration let and const Hoisting console.log(b); let b = 20; // ReferenceError: Cannot access 'b' before initialization What happens: - b is hoisted - but not initialized - exists in TDZ - Function Expressions sayHello(); var sayHello = function() { console.log("Hello"); }; What happens; - sayHello is hoisted as undefined - function body is not hoisted Result: TypeError: sayHello is not a function TDZ -it is the time between entering a scope and initializing let or const variable - variable exists - but cannot be accessed - prevents accidental usage before declaration TDZ is not special zone in memory, it is a state of a binding between hoisting and initialization { // TDZ starts console.log(a); //ReferenceErrror let a = 10; // TDZ ends } So, based on our above details, how can you describe Hoisting in one line ? Please follow for Part 4 updates. 👍 #javascriptfundamentals #uideveloper #corejs
To view or add a comment, sign in
-
JavaScript's Date vs Temporal: A Modern Solution for Date Handling The article discusses the limitations of JavaScript's built-in Date object, highlighting its mutable nature and inconsistencies, and advocates for the adoption of the new Temporal API as a superior alternative. Temporal offers a significant improvement over Date, providing a more reliable and less error-prone way to handle dates and times in JavaScript https://lnkd.in/g3idJnNj #javascript #frontend #datemanipulation #temporal #date
To view or add a comment, sign in
-
JavaScript in one picture 😂 🧑🏫 “It’s a single-threaded language.” 🧑🏫 “It’s an asynchronous language.” Me: So… which one is it? JavaScript: Both. Me: I hate it. 😭 Now the actual explanation 👇 👉 Single-threaded JavaScript has only one call stack. It can execute one task at a time, in order. No true parallel execution like multithreaded languages. 👉 Asynchronous JavaScript can start a task and move on without waiting for it to finish. Things like API calls, timers, file I/O are handled in the background. 👉 So how does it do both? Because of the Event Loop 🚀 • Long tasks go to Web APIs / Node APIs • Their callbacks wait in the callback / microtask queue • The event loop pushes them back to the call stack when it’s free 👉 Result: Single thread ✔ Non-blocking behavior ✔ Efficient and scalable ✔ Confusing at first. Beautiful once it clicks. 💡 If you’ve ever felt this meme — you’re learning JavaScript the right way 😄 #JavaScript #NodeJS #EventLoop #AsyncJS #WebDevelopment #LearningInPublic #DeveloperHumor
To view or add a comment, sign in
-
-
So, JavaScript has three ways to declare variables - and it's kinda weird. It's all about how var, let, and const work with JavaScript's execution model. Think of it like a big machine: when you declare a variable, JavaScript creates this thing called a Lexical Environment, which is like a container that stores variables and functions. It's got two main parts: an Environment Record and an outer reference to the parent environment. Simple. But here's where things get interesting - var, let, and const all interact with these structures in different ways. Var creates bindings in Function Environment Records, and they're initialized to undefined right away, which is pretty old-school. Let, on the other hand, creates bindings in Block Environment Records, and it's got this temporary dead zone (TDZ) thing going on, which can be a bit tricky to wrap your head around. And then there's const, which is like let, but its bindings are marked immutable - so, you can't change 'em once they're set. Understanding how all this works is key to predicting behavior and debugging issues in your code. It's like being a detective - when you see weird scoping bugs, you can trace through the environment creation and figure out exactly where a variable lives. And, honestly, it's pretty cool once you get the hang of it. So, if you want to learn more, check out this article: https://lnkd.in/g72BVQUZ #JavaScript #Variables #CodingStrategy
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