While Loop in TypeScript
Loop statements make it possible to run a statement or set of statements repeatedly. There are two main types of loops: definite loops, like the for
loop, have a specified number of iterations, while indefinite loops, like the while
and do…while
loops, have an unknown number of iterations.
Instructions are carried out by the while
loop as long as the given condition is true
. The code block doesn’t run until the condition has been assessed.
Syntax:
while(condition)
{
// statements if the condition is true
}
Example: This code calculates the factorial of 5.
var num:number=5;
var factorial:number=1;
while(num >=1)
{
factorial=factorial * num;
num--;
}
console.log("The factorial is "+factorial);
Output:
The factorial is 120
As long as num
is higher than or equal to 1, the loop keeps going, computing the factorial and decreasing num
each time.
Do…while Loop
A significant distinction separates the do…while
loop from the while
loop: the do…while
loop runs the code block at least once before assessing the condition. Only the next iteration is examined for the condition.
Syntax:
do
{
//statements
}while(condition)
Example: This prints numbers in reverse order, starting at 10.
var n:number=10;
do
{
console.log(n);
n--;
}while(n>=0);
If the condition is initially false (e.g., if n
was set to 5 and the condition was n > 5
), the do
block would still execute once, whereas a standard while
loop would be skipped entirely,.
For Loop
The for
loop iterates across a fixed collection of variables by running a code block a predetermined number of times.
Syntax:
for (initial_count_value; termination-condition; step)
{
//statements
}
The loop does the step (e.g., increment or decrement) after each iteration, initialises the count, verifies the termination condition, and executes the statements.
Example: Calculating the factorial of 5 using a for
loop.
var num:number= 5;
var i:number;
var factorial=1;
for(i=num;i>=1;i--)
{
factorial*=i;
}
console.log(factorial)
Output:
120
Advanced Loops in TypeScript
JavaScript’s array iteration was previously confusing, therefore TypeScript introduced the for…of
loop to clear it up.
For…in Loop
Iterating over an object’s keys (or indices) is what the for...in
loop does. It returns the indices of arrays as strings rather than the actual array elements. Usually, a string
or any
other type is used as the variable val
in the syntax for (var val in list)
.
For…of Loop
The for…of
loop reduces the amount of boilerplate code needed and clarifies the idea by iterating over the elements of an array or iterable object directly. Character by character iteration over a string is another usage for it.
Example using for…of:
var someArray = ;
for (var item of someArray) {
console.log(item);
}
Output:
9
2
5
This iterates across the array’s members rather than its indexes.
Break Statement
The break
statement is a flow control method that is used to compel a switch
construct or a loop (like while
, do…while
, or for
) to end immediately. When run inside a loop, control is transferred to the statement that comes right after the loop.
Syntax:
break
An example of a break
in a while loop
is as follows: This code immediately ends the loop after determining the first multiple of five between 1 and 10.
var i:number=1
while(i<=10)
{
if (i % 5 == 0)
{
console.log ("The first multiple of 5 between 1 and 10 is : "+i)
break //exit the loop if the first multiple is found
}
i++
}
Output:
The first multiple of 5 between 1 and 10 is : 5
The program would skip the remainder of the current iteration if the break
statement were changed to continue
(assuming that i % 5 == 0
was true), but the loop would not end.
Switch Statement
After evaluating a variable expression and comparing its value to a list of constant case
clauses, the switch
statement runs the related statements.
Syntax:
switch(variable_expression)
{
case constant_expr1:
{
//statements;
break;
}
// ... other cases ...
default:
{
//statements;
break;
}
}
Rules and Flow
- Only constants may be included in the
case
statements; variables or expressions are not permitted. - All of the switch’s cases are used to test the expression’s value.
- The matching code block runs if there is a match. The optional
default
block’s code runs if no case matches. - Flow Control: If a
break
statement isn’t used after each block, execution moves on to the following one. If there is nobreak
in a case and an unexpected execution flow is possible, a compiler flag callednoFallthroughCasesInSwitch
can be activated to notify issues.
Example: The following checks the value of the variable grade
.
var grade:string="A";
switch(grade)
{
case "A":
{
console.log("Excellent");
break;
}
case "B":
{
console.log("Good");
break;
}
default:
{
console.log("Invalid choice");
break;
}
}
Output:
Excellent
Since the grade
is “A,” the break
statement leaves the switch
block and the first case runs, printing “Excellent.”
Scoping
Curly braces {}
can be used to enclose the body of your case
statements, allowing you to reuse variable names specified using let
in other case
statements. Each case now has its own block scope thanks to this:
switch (name) {
case 'x': {
let x = 5; // This 'x' is scoped to this block
// ...
break;
}
case 'y': {
let x = 10; // This 'x' is a new, separate variable
// ...
break;
}
}
Exhaustive Checks
TypeScript commonly uses the switch
statement to execute exhaustive checks on discriminated unions, which are types made up of several object types that may be identified by a literal property (e.g., kind:'square'
).
The variable’s type is intelligently narrowed by TypeScript when the switch
iterates across situations. It narrows the variable’s type within the default
block to never
, after covering all potential literal types in the union. Because a value (the unhandled type) can never
be assigned to the bottom type, this creates a safeguard that will alert developers if they forget to handle a case.
This thorough check pattern usually appears as follows:
function area(s: Shape) { // Assume Shape is a union of 'square', 'rectangle', 'circle'
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.width * s.height;
case "circle": return Math.PI * s.radius * s.radius;
default:
const _exhaustiveCheck: never = s; // Compile error if a case is missing
return _exhaustiveCheck; // Used if strictNullChecks is enabled
}
}
Decision Making in TypeScript
With decision-making structures, programmers can specify one or more criteria that the program will assess and the code blocks that will be run in response to the evaluation’s results. In addition to being essential for managing a program’s execution path, these structures are also essential for TypeScript’s Type Narrowing and Control Flow Analysis.
You can use TypeScript’s if
statement, if…else
statement, else…if
ladder, and switch statement to make decisions.
The Statement and Its Variations
A block of code is not run until a condition (a Boolean expression) has been evaluated using the if
construct.
If…else Statement
Statements inside the if
block are executed if the Boolean expression evaluates to true
.
Syntax:
if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
Example:
var num:number=5
if (num > 0)
{
console.log("number is positive")
}
Output:
number is positive
Since (num > 0
) is true, the statement is executed.
If Statement
An else
block can optionally come after an if
statement. The if
statement tests a Boolean expression, and if it evaluates to false
, the statements inside the else
block run.
Syntax:
if(boolean_expression)
{
// statement(s) will execute if the Boolean expression is true
}
else
{
// statement(s) will execute if the Boolean expression is false
}
Example: The example below checks for even or odd numbers.
var num:number = 12;
if (num % 2==0)
{
console.log("Even");
}
else
{
console.log("Odd");
}
Output:
Even
The divisibility is checked by two using the if
block. The if
block is executed because 12 is even.
Else…if Ladder
Multiple conditions can be tested consecutively with the help of the else…if
ladder.
Guidelines for use the ladder:
- One
else
block or zero can be included in anif
statement; it must follow anyelse…if
statements. - The optional
else
block must occur after zero to manyelse…if
blocks in anif
statement. - Importantly, after an
else…if
is successful, none of the otherelse…if
orelse
will be put to the test.
Example:
var num:number=2
if(num > 0)
{
console.log(num+" is positive")
}
else if(num < 0)
{
console.log(num+" is negative")
}
else
{
console.log(num+" is neither positive nor negative")
}
Output:
2 is positive
The first if
block runs because num > 0
is true, and the remaining steps in the ladder are skipped.
TypeScript’s Use of for Type Guards
Type guards, which enable the compiler to restrict the potential type of a variable within a block of code, depend on conditional checks in TypeScript.
For instance, type safety can be guaranteed when working with a union type (Foo | Bar
) by utilising instanceof
in an if
statement:
class Foo { foo = 123; }
class Bar { bar = 123; }
function doStuff(arg: Foo | Bar) {
if (arg instanceof Foo) {
console.log(arg.foo); // OK: TypeScript knows 'arg' is Foo here
// console.log(arg.bar); // Error: Property 'bar' does not exist on Foo
} else { // MUST BE Bar! [17]
// console.log(arg.foo); // Error: Property 'foo' does not exist on Bar
console.log(arg.bar); // OK: TypeScript knows 'arg' is Bar here
}
}
TypeScript is intelligent enough to understand that if the if
condition narrows the type to Foo
, the corresponding else
block must contain the remaining possible type, Bar
,.