TypeScript Loops Functions Part 2

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

To view or add a comment, sign in

Explore content categories