In TypeScript, 'as const' might look like a tiny keyword, but it’s incredibly powerful once you understand what it does. By default, TypeScript tries to be flexible - - Strings, numbers, and booleans are widened to their general type ("apple" -> string, 42 ->number). - Arrays are treated as general arrays (number[]). - Objects have properties typed generally (role: "admin" -> string). This flexibility is called type 'widening.' TypeScript assumes you might want to reassign these values later. But what if you want the most specific, literal type, and you also want your object or array to be 'readonly' at the type level? That’s where 'as const' comes in. When we use 'as const', the values are narrowed to their literal types, arrays become 'readonly,' and Objects have all the properties marked as 'readonly'. But why is this useful? It is useful for things like - - Configuration objects: values can’t be reassigned accidentally. - Readonly tuples - avoids unintended array mutation. - Enums alternative - teams often use 'as const' objects instead of enums. Now, you need to still keep in mind that 'as const' is a compile-time only TypeScript feature. It doesn’t make the object immutable at runtime. If you also need runtime immutability, you can use something like 'Object.freeze.' The bottom-line is that this small keyword can prevent subtle bugs, make your types safer, and improve code reliability. #TypeScript #JavaScript #Coding #Programming #WebDevelopment #Development
How 'as const' improves TypeScript code safety and reliability
More Relevant Posts
-
Let's talk about something quite interesting in TypeScript - 'Indexed Access Types.' In TypeScript, 'Indexed Access Types' let us look up a type by indexing another type. This is similar to how we access a property on an object or an array at runtime. Let’s say we have an 'as const' object, and we want our types to stay perfectly in sync with the values inside it. That’s where 'Indexed Access Types' shine. This means if the original object changes, your derived types update automatically. You can even use 'keyof' with it to extract all possible value types or combine specific keys to build flexible unions. And yes, this is why 'as const' is so useful because it ensures those values are literal types, not widened ones like 'string.' If you try to access a key that doesn’t exist, TypeScript immediately warns you, giving you both type safety and consistency. So far, I talked about ' as const' objects in TypeScript. What if instead of an object, we have an ‘as const’ array? Using 'as const', this array becomes a 'readonly tuple,' and we can use 'Indexed Access Types' to extract types from it the same way we do with objects. We can get the type of a specific element by its index or even create a union type of all the values in the array. Here’s where it gets interesting. If we use 'number' as the index type, TypeScript interprets that as 'all numeric indices', effectively giving us a union of all the element types in the array. That means if our array changes or if elements are added or removed, the derived type automatically reflects those changes. This pattern is incredibly powerful for defining value-driven types that evolve with your code. In short, Indexed Access Types help you create types that truly evolve with your data. #TypeScript #JavaScript #Programming #Development #Coding #WebDevelopment
To view or add a comment, sign in
-
-
Most of us use JavaScript every day — but have you ever wondered what actually happens when your JS file runs? 🤔 I’ve been exploring the entire flow of JavaScript execution, and it’s absolutely fascinating to see how your simple index.js file travels through multiple stages before becoming machine-executable code 💻 Here’s the journey of your JS code 👇 1️⃣ Source Code (.js) → The code you write (e.g., fibonacci.js). 2️⃣ Parsing Phase → JS engine reads and validates syntax. 3️⃣ AST (Abstract Syntax Tree) → The code is broken into a structured tree that represents program logic. Here we know why Node as a Data Structure is Important😅 4️⃣ Interpreter (Ignition) → Quickly starts executing your code line by line. 5️⃣ Optimizer (TurboFan) → Observes patterns, identifies “hot” code paths. 6️⃣ Compiler (JIT – Just In Time) → Compiles optimized sections into efficient machine code. 7️⃣ Machine Code Execution → The CPU finally runs it ⚙️
To view or add a comment, sign in
-
-
𝟵𝟬% 𝗼𝗳 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝗱𝗼𝗻’𝘁 𝗸𝗻𝗼𝘄 𝗵𝗼𝘄 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗿𝘂𝗻𝘀 𝘂𝗻𝗱𝗲𝗿 𝘁𝗵𝗲 𝗵𝗼𝗼𝗱. 𝗬𝗼𝘂𝗿 𝗯𝗿𝗼𝘄𝘀𝗲𝗿 𝗿𝗲𝗮𝗱𝘀, 𝗰𝗼𝗺𝗽𝗶𝗹𝗲𝘀, 𝗮𝗻𝗱 𝗰𝗹𝗲𝗮𝗻𝘀 𝗶𝘁 - 𝗶𝗻 𝗿𝗲𝗮𝗹 𝘁𝗶𝗺𝗲. 👇 🔹 𝗦𝘁𝗲𝗽 𝟭: 𝗣𝗮𝗿𝘀𝗶𝗻𝗴 (𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝘁𝗵𝗲 𝗖𝗼𝗱𝗲) • You write JavaScript code. • Your browser has a JavaScript engine - the program that runs your code. • The Parser reads it and breaks it into tokens (small code pieces). • These tokens form an AST (Abstract Syntax Tree) - a diagram that shows how your code is arranged • If something’s wrong, the parser stops and shows a syntax error. 🔹 𝗦𝘁𝗲𝗽 𝟮: 𝗜𝗻𝘁𝗲𝗿𝗽𝗿𝗲𝘁𝗮𝘁𝗶𝗼𝗻 (𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗕𝗲𝗴𝗶𝗻𝘀) • The Interpreter turns the AST into Bytecode (instructions the engine can run). • The Bytecode runs inside the engine, not directly on the CPU. • The program starts running after this step. • The engine tracks which parts run often and what data types are used. 🔹 𝗦𝘁𝗲𝗽 𝟯: 𝗝𝗜𝗧 𝗖𝗼𝗺𝗽𝗶𝗹𝗮𝘁𝗶𝗼𝗻 (𝗢𝗽𝘁𝗶𝗺𝗶𝘇𝗮𝘁𝗶𝗼𝗻) • The engine finds hot code (functions or loops that run many times). • It sends them to the JIT (Just-In-Time) Compiler, which turns hot code into faster Machine Code during execution. • This Machine Code runs directly on the CPU. • The result - same code, now runs much faster. 🔹 𝗦𝘁𝗲𝗽 𝟰: 𝗔𝗱𝗮𝗽𝘁𝗶𝘃𝗲 𝗢𝗽𝘁𝗶𝗺𝗶𝘇𝗮𝘁𝗶𝗼𝗻 (𝗦𝘁𝗮𝘆 𝗙𝗹𝗲𝘅𝗶𝗯𝗹𝗲) • The engine constantly checks how code behaves. • If types or logic change, it re-optimizes the code for the new pattern. • This adaptive process keeps JavaScript dynamic and efficient. 🔹 𝗦𝘁𝗲𝗽 𝟱: 𝗚𝗮𝗿𝗯𝗮𝗴𝗲 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗶𝗼𝗻 (𝗖𝗹𝗲𝗮𝗻 𝘁𝗵𝗲 𝗠𝗲𝗺𝗼𝗿𝘆) • When code or data is no longer needed, it’s removed automatically. • The Garbage Collector (GC) finds and clears unused memory. • This keeps memory light and your app smooth. 🔄 𝗙𝘂𝗹𝗹 𝗙𝗹𝗼𝘄: Parsing → Interpretation → JIT Compilation → Adaptive Optimization → Garbage Collection Follow Saurav Kumar for more easy-to-understand Frontend insight. ✨ Would love to know your thoughts 👇 #JavaScript #FrontendDevelopment #WebDevelopment #JSEngine #ReactJS #Coding #Programming
To view or add a comment, sign in
-
-
You must've used or at least heard of 'Enums' in TypeScript. Enums let you define a set of named constants that represent a fixed set of values. They can make code more readable and self-documenting. For example, instead of passing around raw strings like 'admin' or 'user', you can define an enum and use those named members instead. Enums are a TypeScript-specific feature that compiles into JavaScript objects. This means they exist at runtime, unlike most type-only constructs. TypeScript is supposed to be a type system, and it should not introduce any runtime features. But, Enums go against that goal. There are also 'Const Enums' that are completely removed during compilation, but even the TypeScript documentation does not recommend using them unless extremely necessary. You will actually find a lot of articles and YouTube videos where developers talk about the cons of Enums and why you should probably not use them. So, what should be used instead? Well, there is another way to define a set of named constants in TypeScript, and it is using 'as const,' which I discussed in one of my previous posts. Unlike Enums, objects using 'as const' compile to just a plain object. So, there is no extra runtime overhead. Now, this 'Enum' vs 'as const' debate is pretty popular in the TypeScript community, and while some developers prefer 'Enums,' some are against using them. The bottom-line is that Enums are not 'bad,' but many teams default to 'as const' because it’s lighter, safer, and closer to plain JavaScript. #TypeScript #JavaScript #Programming #WebDevelopment #Coding
To view or add a comment, sign in
-
-
🚀 𝗗𝗮𝘆 𝟮 𝗼𝗳 𝗥𝗲𝘃𝗶𝘀𝗶𝘁𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Today I revised some 𝗰𝗼𝗿𝗲 𝗝𝗦 𝗳𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀 👇 🔹 𝘃𝗮𝗿, 𝗹𝗲𝘁 & 𝗰𝗼𝗻𝘀𝘁 – var is old and has problems (function scope, hoisting issues). Modern JS prefers let & const. 🔹 𝗗𝗮𝘁𝗮 𝗧𝘆𝗽𝗲𝘀 𝗣𝗿𝗶𝗺𝗶𝘁𝗶𝘃𝗲: Number, String, Boolean, Undefined, Null, BigInt, Symbol. 𝗡𝗼𝗻-𝗣𝗿𝗶𝗺𝗶𝘁𝗶𝘃𝗲: Object, Array, Function. 🔹 𝗜𝗻𝘁𝗲𝗿𝗲𝘀𝘁𝗶𝗻𝗴 𝗙𝗮𝗰𝘁𝘀 typeof null 👉 returns "object" (a well-known bug in JS 🐞). typeof array 👉 also returns "object". 🔹 𝗠𝘂𝘁𝗮𝗯𝗶𝗹𝗶𝘁𝘆 𝗣𝗿𝗶𝗺𝗶𝘁𝗶𝘃𝗲 𝘃𝗮𝗹𝘂𝗲𝘀 𝗮𝗿𝗲 𝗶𝗺𝗺𝘂𝘁𝗮𝗯𝗹𝗲 → If you assign a new value, a fresh copy is created. 𝗡𝗼𝗻-𝗽𝗿𝗶𝗺𝗶𝘁𝗶𝘃𝗲 𝘃𝗮𝗹𝘂𝗲𝘀 (𝗼𝗯𝗷𝗲𝗰𝘁𝘀, 𝗮𝗿𝗿𝗮𝘆𝘀, 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀) are stored by reference → If two variables point to the same object, changing one affects the other. ✨ These fundamentals are the foundation of mastering advanced JS concepts. #JavaScript #WebDevelopment #100DaysOfCode #JSFundamentals #LearningInPublic
To view or add a comment, sign in
-
-
⚡ Day 25 of #30DaysOfJavaScript Today’s topic: Mastering JSON in JavaScript 🧠 Have you ever wondered how data travels between your frontend and backend like magic? ✨ That magic format is called JSON (JavaScript Object Notation) — the universal language of the web! 🌍 --- 🔹 What is JSON? JSON stands for JavaScript Object Notation. It’s used to store and exchange data in a structured, human-readable format. Example 👇 const user = { "name": "Tanmoy", "age": 25, "skills": ["JavaScript", "Python", "React"] }; --- 🔹 Convert JS Object → JSON String const jsonData = JSON.stringify(user); console.log(jsonData); Output: {"name":"Tanmoy","age":25,"skills":["JavaScript","Python","React"]} --- 🔹 Convert JSON String → JS Object const parsedData = JSON.parse(jsonData); console.log(parsedData.name); // Tanmoy --- 🔥 Pro Tip: Use JSON.stringify() and JSON.parse() to easily handle API data and store structured info in local or session storage. JSON is the bridge between your frontend and backend — master it, and you master communication! 💪 --- 💭 Question for You: What’s the coolest project where you used JSON? Comment below 👇 #30DaysOfJavaScript #CodingGuruji #JavaScript #LearnToCode #WebDevelopment #Frontend #Programming #TechLearning #SoftwareEngineering #WebDev #DeveloperCommunity #JSDeveloper #CodeWithMe #CodingMotivation #100DaysOfCode #TechEducation #DeveloperJourney
To view or add a comment, sign in
-
-
JS Domination | Day 2 — Call Stack & Heap Memory Simplified! Ever wondered how JavaScript handles memory and runs your code so smartly?* 🤔 Let’s break it down in simple words . Call Stack — This is where your code actually runs! Every time you call a function, it gets added (pushed) on top of the stack — once finished, it’s removed (popped). it stores primitive values like numbers, strings, and booleans — basically everything that’s small and directly used. JS runs one thing at a time here — that’s why it’s single-threaded. Heap Memory — Think of it as a storage warehouse This is where reference types (objects, arrays, functions) live. Instead of storing the actual data in the stack, JS stores a reference (address) pointing to the heap — that’s how memory is managed efficiently. Together, the Call Stack handles execution, and the Heap handles storage and referencing. Understand this, and debugging, optimizing, and truly mastering JS becomes way easier What’s one JS concept that always confuses you? Drop it below — I might cover it next! #JavaScript #WebDevelopment #JSConcepts #Frontend #FullStack #LearnWithMe #TechLearning #CodingJourney #SoftwareEngineering #JSCommunity #DeveloperLife
To view or add a comment, sign in
-
Day 10 ✅ of JS Series - by Rohit Negi What I learned: Today, I learned about how Javascript runs behind the scene. Let's discuss that briefly. ✅ Step 1: Coverts JS code to Abstract Syntax Tree(AST) ✅ Step 2: Coverts AST to machine readable bytecode ✅ Step 3: It is ready for execution. JS engine creates Global Execution Context(GEC) and push it onto call stack. ✅ Step 4: In GEC , the code runs into two phases. 1. Memory Creation Phase 2. Execution Phase ✅ Step 5: In Memory creation phase: 🔹 variables are created in memory and initialized to undefined (But for "let" and "const" variables are uninitialized due to Temporal Dead Zone dead zone) 🔹 For the function , its entire definition stored in heap memory and the identifier(function name) is initialized with a reference (a pointer) to that memory location. ✅ In Execution Phase: 🔹 Variables are assigned to value defined by developer. 🔹 When the function is called , a new execution context is created and push it on call stack. It also runs in two phases paused current execution - Creation and Execution phase. ✅ Step 6: After the function finishes executing, its Execution Context is popped off the call stack, and control returns to the GEC where it was called . ✅ Step 7: Once the entire code has been executed, the Global Execution Context is also popped from the call stack #JavaScript #WebDevelopment #learnInPublic
To view or add a comment, sign in
-
-
𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐍𝐚𝐦𝐢𝐧𝐠 𝐂𝐨𝐧𝐯𝐞𝐧𝐭𝐢𝐨𝐧𝐬 𝐍𝐨 𝐎𝐧𝐞 𝐅𝐨𝐥𝐥𝐨𝐰𝐬 (𝐁𝐮𝐭 𝐒𝐡𝐨𝐮𝐥𝐝) Messy variable names make JS code hard to read, even if it works. In my latest blog, I cover: - 💡 Start and end variable names with letters — not _ or $ - 💡 Snake_case isn’t dead — sometimes it’s the cleanest choice - 💡 Reserved words are more than a restriction; they’re a legacy from 1950s memory limits Tips inspired by 𝐃𝐨𝐮𝐠𝐥𝐚𝐬 𝐂𝐫𝐨𝐜𝐤𝐟𝐨𝐫𝐝 Read it here 👉 https://lnkd.in/d_j6X-8J
To view or add a comment, sign in