Skip to content

Instantly share code, notes, and snippets.

@kingluddite
Created November 14, 2023 15:48
Show Gist options
  • Select an option

  • Save kingluddite/a4ca97092a31c62908cb3fd2db494f13 to your computer and use it in GitHub Desktop.

Select an option

Save kingluddite/a4ca97092a31c62908cb3fd2db494f13 to your computer and use it in GitHub Desktop.
Loosely Typed vs Strongly Typed

Let's compare a loosely typed language like JavaScript with a strongly typed language like C#.

Loosely Typed (JavaScript):

In JavaScript, variables are not bound to a specific data type. You can assign different types of values to the same variable without explicit type declarations.

// JavaScript example (loosely typed)
let myVariable = 10;       // Integer
console.log(myVariable);

myVariable = 'Hello';      // String
console.log(myVariable);

myVariable = true;         // Boolean
console.log(myVariable);

In this example, myVariable starts as a number, then becomes a string, and finally becomes a boolean. JavaScript allows this flexibility, but it can lead to unexpected behavior if not handled carefully.

Strongly Typed (C#):

In C#, variables are strongly typed, meaning they are explicitly declared with a specific data type, and their type cannot be changed once set.

// C# example (strongly typed)
int myVariable = 10;       // Integer
Console.WriteLine(myVariable);

// This would result in a compilation error in C#
// myVariable = "Hello";   // Error: Cannot implicitly convert type 'string' to 'int'

bool isTrue = true;        // Boolean
Console.WriteLine(isTrue);

In this C# example, myVariable is explicitly declared as an integer, and attempting to assign a string value would result in a compilation error. This strict type checking helps catch potential errors at compile-time rather than during runtime.

In summary, the key difference lies in how flexible the language is regarding variable types. JavaScript is loosely typed, allowing variables to change types dynamically, while C# is strongly typed, requiring explicit declaration of variable types and enforcing type consistency.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment