TypeScript : Part 2 – Loops & Functions! I'm excited to share the next chapter of my TypeScript learning journey. In this part, I dived deep into the core building blocks: Control Flow (Loops) and Type-Safe Functions. Understanding how to automate tasks and write reusable code is a game-changer! Here’s a breakdown of what I covered with examples: 1. Loops Loops help us run the same block of code multiple times. ■ For Loop: Perfect when you know exactly how many times to repeat. Example: for(let num:number=1; num<=target; num++){ console.log("For Prints: "+ num); } ■ While Loop: Best when you want to run as long as a condition is true Example: let num:number=1; while(num <= target){ console.log("While Prints: "+ num); num++; } ■ Do-While Loop: Unique because it guarantees the code runs at least once, even if the condition is false initially. Example: let num:number=1; do{ console.log("Do-While Prints: "+ num); num++; }while(num <= target); 2. Types of Functions in TypeScript ■ Named Function This is the traditional way to write a function. It has a specific name and can be called anywhere in your code Example: function sayHello(name: string): void { console.log("Hello, " + name + "!"); } sayHello("Akhila"); ■ Anonymous Function A function without a name! Usually, we assign it to a variable. It’s great for logic that doesn't need to be reused globally. Example: let square = function (num: number): number { return num * num; } console.log("square of 5: " + square(5)); ■ Arrow Function (Lambda) The modern, shorthand way to write functions using the => syntax. It’s clean, concise, and very popular in modern web development. Example: const add = (x: number, y: number): number => x + y; ■ Void Function A function that does not return a value. We use the void type to tell TypeScript that this function just performs an action (like logging to the console) and finishes. Example: let greet = function (): void { console.log("Welcome to TypeScript!"); } greet(); Ram Shankar Darivemula | Frontlines EduTech (FLM) Key Takeaway: Using types in functions helps catch bugs during development rather than at runtime. It makes the code much more predictable and easier to read! What's Next? Stay tuned for Part 3 of TypeScript, where I'll be exploring Complex types #TypeScript #WebDevelopment #SoftwareEngineering #Programming #JavaScript #WebDev #DotNet
TypeScript Loops Functions Part 2
More Relevant Posts
-
𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝟲.𝟬 𝗞𝗲𝘆 𝗙𝗲𝗮𝘁𝘂𝗿𝗲𝘀 𝗳𝗼𝗿 𝟮𝟬𝟮𝟲 TypeScript 6.0 is here. It sets up major changes for TypeScript 7.0. Here is what matters for your code. **Small fix, big help** TypeScript 6.0 now understands method syntax better. Functions that do not use `this` get better type guesses. Your code works consistently now. **Cleaner imports** You can now use `#/` as an import prefix. This matches bundler tools. Write `import utils from "#/utils.js"` instead of `../../../utils.js`. **Predictable output** A new flag `--stableTypeOrdering` makes union types appear in a fixed order. Your build files will not change randomly. Note: this can slow compilation. **Modern dates** The Temporal API is now built-in. It fixes many problems with JavaScript's Date object. Use it for time zones and durations. **Easier Map updates** Maps have two new methods: - `getOrInsert(key, default)` sets a value if missing. - `getOrInsertComputed(key, function)` runs a function only if the key is missing. **Safer regex** Use `RegExp.escape(userInput)` to safely turn user text into a pattern. You avoid injection bugs. **Breaking changes** New defaults in `tsconfig.json`: - `strict: true` - `module: esnext` - `target: es2025` (floating) - `types: []` (empty, add needed types yourself) You must now list required types explicitly. Options like `baseUrl` are deprecated. Use full paths in `paths` instead. **Your action plan** Immediate: - Update your `tsconfig.json` - Add needed types to the `types` array - Set `rootDir` if your source folder is not the project root Medium term: - Move off `target: es5` - Change module resolution to `nodenext` or `bundler` - Stop using AMD or UMD modules Long term: - Test the `--stableTypeOrdering` flag - Plan for parallel builds in CI when TypeScript 7.0 arrives These changes prepare your project for faster builds. The default settings cut startup time. Source: https://lnkd.in/gu9jP4tb Which feature will you try first? Share your migration steps below.
To view or add a comment, sign in
-
🔷 TypeScript 6.0 shipped on March 23rd. It's historic — and not for the reason you might think. This release is, by design, **the end of an era**. TypeScript 6.0 is the last major version built on the original JavaScript-based compiler codebase. TypeScript 7.0, currently in development, is being **rewritten in Go** — with native execution speeds and shared-memory multithreading. But before we get to 7.0, there are two things in the current landscape that every Node.js developer should already be using: **1. Native TypeScript execution in Node.js (no build step)** Node.js 22.18+ and 23.6+ ship with type stripping enabled by default. You can now run `.ts` files directly: ```bash node --watch server.ts # just works ``` Node strips type annotations before execution — types are treated like structured comments. No `tsc`, no `ts-node`, no `tsx`. For tooling scripts, CLIs, and internal services, this eliminates an entire build layer. **⚠️ One critical caveat**: only *erasable* TypeScript syntax is supported natively — types, interfaces, generics. `enum` and parameter properties still require `--experimental-transform-types` because they generate actual JavaScript code. **2. What TypeScript 7.0 in Go means architecturally** The current `tsc` is single-threaded and JavaScript-based — which creates real bottlenecks in large monorepos. TypeScript 7.0 will be able to parallelize type checking across modules using shared memory, making type-check times in large codebases drop from minutes to seconds. The transition plan: TypeScript 6.x for stability now, TypeScript 7.0 for performance when it ships later in 2026. If your pipeline still has a heavyweight `tsc` compile step for every dev server restart — now is a good time to rethink it. Are you already running TypeScript natively in Node.js? What's blocking you if not? 👇 Source(s): https://lnkd.in/dFQzqcfj https://lnkd.in/dcvVEg8i https://lnkd.in/dmz9iW6t https://lnkd.in/dikKt86J #TypeScript #NodeJS #JavaScript #WebDev #SoftwareEngineering #DeveloperExperience #TypeScript6
To view or add a comment, sign in
-
-
𝗧𝘆𝗽𝗲𝘀𝗰𝗿𝗶𝗽𝘁 𝗧𝘆𝗽𝗲𝘀: 𝗕𝗲𝘆𝗼𝗻𝗱 𝗕𝗮𝘀𝗶𝗰𝘀 You write TypeScript. You avoid any types. You see green squiggles. But errors happen at runtime. TypeScript missed them. Many developers face this. Basic types seem enough. But TypeScript can catch more. It makes code stronger. Use these patterns. - Branded types: Give strings unique names. UserId and Email are both strings but different types. This stops mix-ups. type UserId = string & { brand: unique symbol }; function createUserId(id: string): UserId { return id as UserId; } function sendEmail(userId: UserId, email: Email) {} sendEmail(createUserId('123'), 'test@example.com'); // Error - Template literals and infer: Parse string patterns. Extract parts from paths. type Route = `/users/${string}/posts/${string}`; type Params<T> = T extends `/users/${infer U}/posts/${infer P}` ? {userId: U; postId: P} : never; Params<'/users/alice/posts/99'> is {userId: 'alice', postId: '99'} - as const: Make objects deeply immutable. Get exact types. const config = { env: 'production', retries: 3 } as const; // config.env is 'production' not string - keyof and mapped types: Generate types from keys. Create Partial or Readonly. type PartialUser = { [K in keyof User]?: User[K]; }; type UserUpdate = { [K in keyof User as K extends 'id' ? never : K]?: User[K]; }; - Conditional types: Add logic to types. type Awaited<T> = T extends Promise<infer U> ? U : T; type Flatten<T> = T extends Array<infer U> ? Flatten<U> : T; Build a type-safe API client. const API_ROUTES = { getUser: '/users/:id' } as const; type ParamsFor<K extends keyof typeof API_ROUTES> = Record<ExtractParamNames<typeof API_ROUTES[K]>, string>; async function fetchFromApi<K extends keyof typeof API_ROUTES>(key: K, params: ParamsFor<K>) { // Fetch with correct params } This finds param errors early. Advanced TypeScript shifts your mindset. Design types before code. Start with one pattern. Apply it today. Catch bugs early. Refactor with confidence. What patterns do you use? Share your stories below. Source: https://lnkd.in/g__X8SbJ
To view or add a comment, sign in
-
🚀 NestJS – A Clean & Scalable Backend Framework (Quick Overview) Over the past few months working as a backend developer, I’ve been diving deep into NestJS. It’s honestly one of the most structured and developer-friendly frameworks in the Node.js ecosystem. 🔹 What is NestJS? NestJS is a progressive Node.js framework designed for building efficient, scalable, and maintainable server-side applications. Built with TypeScript (but supports JavaScript too) Inspired by Angular’s architecture Perfect for structured backend development 🔹 Core Concepts (The Foundation) 📦 Modules Everything starts here. Modules help organize your application into logical groups. 🎯 Controllers They handle incoming HTTP requests and return responses. 🧠 Services (Providers) This is where your business logic lives. Clean separation of concerns. 🔌 Dependency Injection (DI) Built-in DI system makes your code more testable and maintainable. ✨ Decorators Things like @Controller(), @Get(), @Injectable() make the code expressive and readable. 🔹 Built-in Features (Powerful Out of the Box) Routing (REST & GraphQL) Middleware support Pipes (validation & transformation) Guards (authentication & authorization) Interceptors (logging, response shaping) Exception Filters (centralized error handling) 🔹 Architecture & Scalability NestJS follows a modular architecture, which makes it: Easy to scale 🚀 Suitable for both monoliths and microservices Compatible with WebSockets, gRPC, and message queues 🔹 Integration & Ecosystem Works with Express (default) or Fastify Supports Prisma, TypeORM, Mongoose Easy auth integration (e.g., Passport.js) 🔹 Testing Support Built-in support for unit testing & e2e testing Uses Jest, making testing straightforward 🔹 Performance & Security High-performance ready ⚡ Supports best practices like: CORS Helmet Secure architecture patterns 🔹 CLI Tool (Huge Productivity Boost) Quickly generate boilerplate: npm i -g @nestjs/cli nest new project-name 🔹 Learning Curve Easier if you know TypeScript or Angular concepts Strong documentation + active community 💙 🔹 Use Cases REST APIs GraphQL APIs Real-time apps (chat, notifications) Microservices Enterprise-grade backends 📌 In my next posts, I’ll provide detailed overviews for each of these topics breaking them down with real-world examples and best practices. If you're working with Node.js and want structure + scalability, NestJS is definitely worth learning. #nestjs #nodejs #backenddevelopment #typescript #webdevelopment #softwareengineering
To view or add a comment, sign in
-
-
The last version of TypeScript built on JavaScript. Most people noticed the breaking changes: strict true by default, ES5 support dropped, @types no longer auto-loaded, outFile gone for good. What's easy to miss is the historical significance: this is the last version of TypeScript built on JavaScript. The compiler that's been running on Node.js since 2012 (14 years) ships its final release. Everything after this is TypeScript 7.0, rewritten in Go. The numbers are real: ✨ VS Code's 1.5 million line codebase: 78 seconds → 7.5 seconds; ✨ Sentry's codebase: 133 seconds → 16 seconds; ✨ Multi-threaded, native binary: ~57% less memory. So why not just celebrate? A few things worth keeping in mind: plugin ecosystem is broken by design. Any custom transformer, ts-patch plugin, or tool relying on the TypeScript compiler API in JS won't work with tsgo out of the box. If your build pipeline has custom tooling → check compatibility now, not when 7.0 lands. WebAssembly performance is a concern. Evan you raised it publicly: Go's Wasm output is slower than the existing JS implementation for browser-based tools. CodeSandbox, StackBlitz, web playgrounds — they run tsc in the browser. Go-compiled Wasm doesn't win there. You're migrating twice, in quick succession. 6.0 breaks enough defaults to require real work. 7.0 follows within months. For teams that don't move fast, this is two migrations with no breathing room between them. The 10x is a build-time story, not a runtime one. Your users won't feel it. Your CI pipeline will. Keep that in context when making the case for migration internally. The Go choice over Rust is worth noting too. Not because it's wrong, but because it goes against the current JS tooling trend (SWC, Deno, Turbopack are all Rust). Microsoft said that Go's GC fits TypeScript's data structures better, and porting was faster than a full redesign. Pragmatic over ideologically pure. The era of a JS-based TypeScript compiler is officially over. 14 years, 1 language, 1 runtime... and now a clean break. Curious where you stand: are you already on 6.0, or still holding off?
To view or add a comment, sign in
-
-
Ever confused about when to use 𝗽𝗿𝗼𝗽𝘀 𝘃𝘀 𝘀𝘁𝗮𝘁𝗲… and ended up mismanaging data flow? 🤯 Or passed too many props while your component secretly needed its own state? You’re not alone — this is one of the most common React confusions. 🚀 𝗣𝗿𝗼𝗽𝘀 𝘃𝘀 𝗦𝘁𝗮𝘁𝗲 — 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗗𝗮𝘁𝗮 𝗙𝗹𝗼𝘄 𝗶𝗻 𝗥𝗲𝗮𝗰𝘁 In React, UI is driven by 𝗱𝗮𝘁𝗮. 👉 That data mainly comes from two places: ◦ 𝗣𝗿𝗼𝗽𝘀 (external data) ◦ 𝗦𝘁𝗮𝘁𝗲 (internal data) Understanding the difference is key to writing clean, scalable components. 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝗣𝗿𝗼𝗽𝘀 𝘃𝘀 𝗦𝘁𝗮𝘁𝗲 (𝗮𝗻𝗱 𝘄𝗵𝘆 𝘂𝘀𝗲 𝘁𝗵𝗲𝗺)? 🔯 𝗣𝗿𝗼𝗽𝘀 (𝗣𝗿𝗼𝗽𝗲𝗿𝘁𝗶𝗲𝘀): ◦ Passed from parent → child ◦ Read-only (cannot be modified) ◦ Used to configure components 🔯 𝗦𝘁𝗮𝘁𝗲: ◦ Managed inside the component ◦ Can be updated using setters ◦ Used for dynamic, changing data 👉 Simple way to think: 𝗣𝗿𝗼𝗽𝘀 = 𝗜𝗻𝗽𝘂𝘁 𝗦𝘁𝗮𝘁𝗲 = 𝗜𝗻𝘁𝗲𝗿𝗻𝗮𝗹 𝗺𝗲𝗺𝗼𝗿𝘆 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝗣𝗿𝗼𝗽𝘀 + 𝗦𝘁𝗮𝘁𝗲 𝗧𝗼𝗴𝗲𝘁𝗵𝗲𝗿 (Example code is in attached image.) 𝗪𝗵𝗮𝘁’𝘀 𝗵𝗮𝗽𝗽𝗲𝗻𝗶𝗻𝗴 𝗵𝗲𝗿𝗲 𝗶𝗻 𝗰𝗼𝗱𝗲? ◦ initialValue → comes from 𝗽𝗿𝗼𝗽𝘀 (external input) ◦ count → stored in 𝘀𝘁𝗮𝘁𝗲 (internal data) ◦ Each component instance has its own state 👉 Props set the starting point 👉 State controls what changes over time 🏗️ 𝗥𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝘂𝘀𝗲 𝗰𝗮𝘀𝗲𝘀 You’ll use both together in almost every project: ◦ Forms → props for initial data, state for user input ◦ Modals → props for visibility, state for internal behavior ◦ E-commerce → props for product data, state for cart actions ◦ Dashboards → props from APIs, state for UI interactions 👉 Real apps = combination of props + state 📌 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 ✔ Props are 𝗿𝗲𝗮𝗱-𝗼𝗻𝗹𝘆 𝗶𝗻𝗽𝘂𝘁𝘀 from parent components ✔ State is 𝗺𝘂𝘁𝗮𝗯𝗹𝗲 𝗱𝗮𝘁𝗮 managed inside the component ✔ Use props for configuration, state for dynamic behavior Mastering this difference is what separates beginner React devs from confident ones. 💬 What confused you more when learning React — props or state? 💡 Part of my #FrontendRevisionMarathon — breaking down Frontend concepts daily 🚀 🚀 Follow Shubham Kumar Raj for more such content. #ReactJS #JavaScript #WebDevelopment #Frontend #CodingTips #100DaysOfCode #codinginterview #learnjavascript #programming #interviewprep #CareerGrowth #SowftwareEngineering #OpenToWork #FrontendDevelopment #Coding #Hiring
To view or add a comment, sign in
-
-
Golang vs JavaScript: A Systems-Level Perspective The comparison between Go and JavaScript is often oversimplified as performance vs flexibility. In practice, the differences are rooted in runtime models, concurrency, and operational behavior. JavaScript (Node.js) uses a single-threaded event loop with non-blocking I/O. This makes it highly effective for I/O-bound workloads such as APIs, real-time apps, and streaming services. However, CPU-bound tasks can become bottlenecks. While worker threads exist, they are not the default model and add complexity in communication and design. Go is built with concurrency as a first-class concept. Goroutines are lightweight and managed by the Go scheduler, allowing thousands of concurrent tasks with minimal overhead. Channels provide a structured way to communicate between them, making concurrent systems easier to design compared to callback or promise-based patterns. In terms of performance, Go generally provides better throughput and lower latency for CPU-intensive and highly concurrent workloads. Its compiled nature and efficient runtime contribute to more predictable performance. JavaScript, powered by V8, is highly optimized but still constrained by the event loop under heavy load. Memory management is another differentiator. Go offers more predictable memory usage, which is important in systems where resource control matters. JavaScript abstracts memory handling, which improves development speed but can introduce unpredictability at scale. The ecosystem is where JavaScript dominates. With npm and widespread adoption, it enables full-stack development using a single language. Go’s ecosystem is smaller but more opinionated, with a strong standard library and fewer abstractions. From an operational standpoint, Go produces self-contained binaries that simplify deployment and reduce environment-related issues. Node.js applications depend on runtime environments and package management, which can add complexity in production. The practical takeaway: JavaScript is optimized for developer productivity and rapid iteration, especially in frontend and I/O-heavy systems. Go is optimized for performance, concurrency, and operational simplicity in backend services. The decision should be driven by system requirements, not language preference.
To view or add a comment, sign in
-
Do you actually know how React + Next.js talk to the server? Most devs think it’s just “API calls”… but that’s not what’s really happening. With modern React + Next.js, the communication is built on top of the React Server Components (RSC) protocol a streaming model where the server sends serialized component trees (not just JSON). That means: → The server is literally sending UI instructions → The client reconstructs the tree → Everything depends on strict runtime contracts And here’s where things get interesting… Why pre-compilers break this? - Pre-compilers assume code is static. But RSC is not static it’s a live protocol. When you introduce a pre-compiler, you risk: - Breaking the serialization format - Changing module boundaries - Losing execution context between server ↔ client This isn’t theoretical. There are real cases where: → server actions crash builds → turbopack behaves differently from webpack → rendering fails during compilation All because the system expects a very specific execution model Even security issues have emerged from this layer, where malformed requests could affect server execution in the RSC pipeline That’s exactly why I built a fix for pre-compilers. Instead of treating prompts/code as strings, we: → respect the execution graph → preserve boundaries → align with how RSC actually works If you're building tooling around Next.js, this layer is where everything either works… or completely breaks. https://lnkd.in/dwTutPkr #nextjs #reactjs #webdev #softwareengineering #frontend #ai #programming #buildinpublic
To view or add a comment, sign in
-
🚀 Just published a new blog on full-stack development! I wrote a practical guide on connecting a Flask backend with a Next.js frontend — something I recently implemented in my own project. 💡 What you’ll learn: • How to integrate a Flask REST API with Next.js • Handling real-world issues like CORS • Structuring a clean frontend-backend architecture • Deploying using Vercel (frontend) & Render (backend) ⚙️ This is based on my environment monitoring & reporting system, where users can submit reports, vote on them, and see real-time updates using Next.js, Flask, and Firebase. If you're working on full-stack or ML-based projects, this will definitely help 👇 https://lnkd.in/dcPuJSAe #FullStackDevelopment #NextJS #Flask #WebDevelopment #APIs #SoftwareEngineering
To view or add a comment, sign in
-
𝗣𝗵𝗮𝘀𝗲 𝗜𝗜 𝗼𝗳 𝗺𝘆 𝗵𝗮𝗰𝗸𝗮𝘁𝗵𝗼𝗻: 𝗡𝗲𝘅𝘁.𝗷𝘀 𝗳𝗿𝗼𝗻𝘁𝗲𝗻𝗱 + 𝗙𝗮𝘀𝘁𝗔𝗣𝗜 𝗯𝗮𝗰𝗸𝗲𝗻𝗱. 𝗕𝗲𝘁𝘁𝗲𝗿 𝗔𝘂𝘁𝗵 𝗳𝗼𝗿 𝗮𝘂𝘁𝗵𝗲𝗻𝘁𝗶𝗰𝗮𝘁𝗶𝗼𝗻. The problem: Better Auth is a JavaScript library. It lives in Next.js. FastAPI is a completely separate Python process — it has no concept of who Better Auth just logged in. The naive fix: make FastAPI call the frontend to verify every request. Tight coupling. Added latency. Backend breaks if the frontend goes down. The correct fix: JWT bridge. Better Auth issues a signed token on login. Self-contained. Carries the user's ID. Signed with a secret key. Frontend attaches it to every API call: → Authorization: Bearer FastAPI middleware extracts the token, verifies the signature using the same secret key, decodes the user ID. No call to the frontend. No shared session. Stateless. They share exactly one thing: a secret. Security isn't enforced at the gateway. Not at the middleware. At the query. select(Task).where(Task.user_id == current_user.user_id) Every database call filtered by the authenticated user's ID. User A cannot see User B's data — even if they construct the right endpoint URL manually. The database rejects it. No exceptions. Midway through, I had a decision to make. Better Auth can own the entire auth flow — direct database access from Next.js, auth logic in API routes. Should I migrate fully? I wrote a BETTER_AUTH_DECISION.md to think it through. (An ADR — Architectural Decision Record. Documenting the tradeoff, the alternative considered, the reason for the choice.) Conclusion: no. Full migration meant giving Next.js direct database access and collapsing the clean separation I'd built. The custom JWT bridge already worked correctly. Migration had no security benefit — only costs. One tip for developers using AI on full-stack monorepos: I built three layered CLAUDE.md files: → Root — project overview, monorepo navigation, spec references → /frontend — Next.js patterns, component conventions, API client usage → /backend — FastAPI patterns, SQLModel conventions, JWT implementation Claude Code reads the hierarchy. When a feature touches both stacks — new endpoint plus the frontend component calling it — it has full context on both sides in a single session. No re-explaining the project. No re-introducing the architecture. Layered context files are the difference between AI that understands your codebase and AI that guesses. Full stack: Next.js 15 · FastAPI · SQLModel · Neon Postgres · Better Auth · custom JWT bridge. Built spec-first. User isolation enforced at the data layer. When you're bridging two different tech stacks for auth — do you prefer a stateless JWT approach, a shared auth service, or something else entirely? Governor Sindh Initiative for GenAI, Web3, and Metaverse Zia Khan | Ameen Alam #BuildInPublic #ClaudeCode #FastAPI #NextJS #FullStackDevelopment #WebDev #GIAIC #PIAIC #Panaversity
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