Skip to content
jshacks.dev
Fundamentals

JavaScript for C Sharp Developers a Practical Comparison

A guide for C# developers learning JavaScript: familiar async and lambdas, but no static types, eager arrays instead of LINQ, delegates that lose this.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite and Node.js logos.

A C# developer is closer to JavaScript than most. The two languages share lambda syntax, async and await, the null-conditional ?. and null-coalescing ?? operators, using for cleanup, and a heavy use of functions as values. Many snippets translate with a change of keywords. The differences hide where the syntax matches, because the behavior underneath is different: JavaScript has no static types, no checked conversions, no LINQ-style laziness by default, and a single-threaded runtime where await returns control to an event loop and not to a thread pool. This post goes through the differences that matter with the output of each snippet, ordered by how often they cost an hour, and ends with habits to build. The JavaScript runs on Node.js 24, and the C# is C# 13 on .NET 9, with outputs written from the language rules.

The vocabulary map

C#JavaScriptNotes
int, double, decimalnumber, bigintOne 64-bit float; no decimal
stringstringImmutable, UTF-16, as in C#
List<T>ArrayNo type parameter
Dictionary<K, V>Map, or ObjectMap for non-string keys
HashSet<T>Set
LINQArray methods, iterator helpersmap, filter, reduce
Task<T>Promise<T>Both start immediately
interfaceNoneDuck typing; TypeScript adds interfaces
IDisposable, usingSymbol.dispose, usingNode.js 24 and current browsers
property { get; set; }Getter and setter, or a plain field
nullnull and undefinedTwo values

Types disappear

csharp
int count = 5;
count = "five"; // compile error CS0029
JavaScript
let count = 5;
count = "five";
console.log(typeof count, count);

function add(a, b) {
  return a + b;
}

console.log(add(1, 2), add("1", 2), add(1, undefined), add([], {}));
Text
string five
3 12 NaN [object Object]

A variable holds any value, a function accepts any arguments, and the operators convert types instead of refusing. add("1", 2) gives the string "12", add(1, undefined) gives NaN, and nothing reports an error. This is the largest adjustment for a C# developer: the compiler that used to catch these mistakes is gone. TypeScript restores a static type system on top of JavaScript, with a type system similar in spirit to C# generics and nullable reference types, and it is the usual choice for large projects. Without it, tests and a linter carry the load.

Lambdas and delegates, and this

C# delegates created from a method carry their instance. JavaScript functions do not.

csharp
var counter = new Counter();
Func<int> next = counter.Next;   // delegate keeps `counter`
Console.WriteLine(next());       // 1
JavaScript
class Counter {
  count = 0;
  next() {
    this.count += 1;
    return this.count;
  }
}

const counter = new Counter();
const next = counter.next;

try {
  next();
} catch (error) {
  console.log(error.name);
}

const bound = counter.next.bind(counter);
const wrapped = () => counter.next();
console.log(bound(), wrapped());
console.log([1, 2].map(() => counter.next()));
Text
TypeError
1 2
[ 3, 4 ]

Taking counter.next as a value gives you the bare function, and calling it later has no this, so it throws. Bind the method, or wrap it in an arrow function, which is what C# does for you when you assign a method group. This is the most common cause of a "cannot read properties of undefined" error in code written by C# developers, and it is explained in the interview question on this.

LINQ versus array methods

The operations have the same names in spirit: Where is filter, Select is map, Aggregate is reduce, Any and All are some and every. The difference is when they run.

csharp
var result = numbers.Where(n => { Console.WriteLine($"where {n}"); return n % 2 == 0; })
                    .Select(n => { Console.WriteLine($"select {n}"); return n * n; })
                    .First();
Text
where 1
where 2
select 2
JavaScript
const log = [];

const eager = [1, 2, 3, 4]
  .filter((n) => {
    log.push(`filter ${n}`);
    return n % 2 === 0;
  })
  .map((n) => {
    log.push(`map ${n}`);
    return n * n;
  })[0];

console.log(eager, log.join(", "));

const lazyLog = [];

const lazy = [1, 2, 3, 4]
  .values()
  .filter((n) => {
    lazyLog.push(`filter ${n}`);
    return n % 2 === 0;
  })
  .map((n) => {
    lazyLog.push(`map ${n}`);
    return n * n;
  })
  .next().value;

console.log(lazy, lazyLog.join(", "));
Text
4 filter 1, filter 2, filter 3, filter 4, map 2, map 4
4 filter 1, filter 2, map 2

LINQ is deferred: nothing runs until you enumerate, and First() stops at the first match. JavaScript array methods are eager, so filter processes all four elements and builds a new array before map starts. The iterator helpers, available on array.values() in Node.js 22 and later, are lazy and behave like LINQ, as covered in [iterator filter()](/library/javascript-iterator-filter). For small arrays the difference does not matter, and for large or infinite sequences, use the lazy form.

Task and Promise

Both start work when created, and both are awaited with await. The model underneath differs.

csharp
Task<string> task = LoadAsync();   // starts running now, possibly on another thread
Console.WriteLine("continues");
Console.WriteLine(await task);
JavaScript
async function load() {
  console.log("load started");
  await new Promise((resolve) => setTimeout(resolve, 10));
  return "loaded";
}

const promise = load();
console.log("continues");
console.log(await promise);

const [first, second] = await Promise.all([load(), load()]);
console.log(first, second);
Text
load started
continues
loaded
load started
load started
loaded loaded

An async function runs synchronously until its first await, as LoadAsync does in C#, and then returns a promise. Promise.all is Task.WhenAll, and Promise.race is Task.WhenAny. The differences: JavaScript has one thread, so there is no thread pool, no Task.Run for parallel computing, no synchronization context and no ConfigureAwait. An await hands control back to the event loop, and continues later on the same thread. CPU-bound work blocks everything, and needs a worker thread. There is also no async void trap: an unhandled rejection is reported by the runtime, and in Node.js crashes the process by default.

Exceptions

csharp
try { Run(); }
catch (ArgumentException e) when (e.ParamName == "id") { /* ... */ }
catch (IOException e) { /* ... */ }
finally { /* ... */ }
JavaScript
function run(kind) {
  if (kind === "argument") throw new RangeError("bad id");
  if (kind === "io") throw new Error("disk failure", { cause: "ENOENT" });
  return "ok";
}

for (const kind of ["argument", "io", "none"]) {
  try {
    console.log(run(kind));
  } catch (error) {
    if (error instanceof RangeError) {
      console.log("range:", error.message);
    } else if (error instanceof Error) {
      console.log("error:", error.message, error.cause);
    } else {
      throw error;
    }
  } finally {
    console.log("done", kind);
  }
}
Text
range: bad id
done argument
error: disk failure ENOENT
done io
ok
done none

JavaScript has one catch block and no exception filters, so you branch with instanceof inside it and rethrow the rest. Throw Error objects, since JavaScript allows throwing any value and only an Error has a stack. The cause option plays the role of InnerException. The built-in error types are few: Error, TypeError, RangeError, SyntaxError, ReferenceError and a handful more, and custom errors are classes that extend Error.

Value types and reference types

csharp
struct Point { public int X; }
var a = new Point { X = 1 };
var b = a;
b.X = 2;
Console.WriteLine(a.X); // 1
JavaScript
const a = { x: 1 };
const b = a;
b.x = 2;
console.log(a.x);

const c = { ...a };
c.x = 3;
console.log(a.x, c.x);

let n = 1;
let m = n;
m = 2;
console.log(n, m);
Text
2
2 3
1 2

JavaScript has no value-type structs: every object is a reference, as a C# class is. Only primitives, which are numbers, strings, booleans, null, undefined, symbols and bigints, are copied by value. Copy an object with spread, which is shallow, or structuredClone(), which is deep. Strings compare by value with ===, as C# does with == on strings.

Numbers and money

JavaScript
console.log(7 / 2, Math.trunc(7 / 2), 7 % 3, -7 % 3);
console.log(0.1 + 0.2, (0.1 + 0.2).toFixed(2));
console.log(Number.MAX_SAFE_INTEGER, 2n ** 64n);

const cents = 1999;
console.log(new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(cents / 100));
Text
3.5 3 1 -1
0.30000000000000004 0.30
9007199254740991 18446744073709551616n
$19.99

Division is always floating point, so there is no integer division operator: use Math.trunc(). There is no decimal type. Keep money in integer cents, divide only for display, and use Intl.NumberFormat to format. BigInt provides exact large integers, and cannot be mixed with number without a conversion.

Null handling

JavaScript
const customer = { address: null, name: "Ada" };

console.log(customer.address?.city ?? "unknown");
console.log(customer.phone?.number ?? "none");

let cache;
cache ??= new Map();
cache.set("a", 1);
console.log(cache.size);

console.log(customer.missing, customer.address);
Text
unknown
none
1
undefined null

The operators ?., ?? and ??= work as in C#. The difference is that JavaScript has two empty values, undefined for what was never set, and null for what was set to nothing, and both are caught by ??. Reading a missing property is not an error, so a typo returns undefined. Nullable reference types in C# have a counterpart in TypeScript's strict null checks.

Dictionaries and properties

JavaScript
const ages = new Map([["ada", 36]]);

console.log(ages.get("ada") ?? 0, ages.get("grace") ?? 0, ages.has("grace"));

class Temperature {
  #celsius = 0;

  get fahrenheit() {
    return this.#celsius * 1.8 + 32;
  }

  set celsius(value) {
    if (value < -273.15) throw new RangeError("below absolute zero");
    this.#celsius = value;
  }
}

const temperature = new Temperature();
temperature.celsius = 100;
console.log(temperature.fahrenheit);
Text
36 0 false
212

Map.get() returns undefined for a missing key, which replaces TryGetValue, and ?? supplies the default. Properties with logic are getters and setters declared with get and set, and a plain public field serves as an auto-property. Private members use the # prefix.

Cleanup with using

C# developers will recognize using, which JavaScript gained in Node.js 24 and current browsers.

JavaScript
class Connection {
  constructor(name) {
    this.name = name;
    console.log("open", name);
  }
  [Symbol.dispose]() {
    console.log("close", this.name);
  }
}

{
  using first = new Connection("a");
  using second = new Connection("b");
  console.log("working");
}
Text
open a
open b
working
close b
close a

Resources are disposed in reverse order at the end of the block, as in C#. The protocol is a Symbol.dispose method in place of Dispose(), covered in JavaScript Symbol.dispose, with await using and Symbol.asyncDispose for async cleanup.

Habits to build

Use const by default. Bind methods or use arrow functions when passing them as callbacks. Use TypeScript for anything larger than a script. Use ===. Throw Error objects, and branch on instanceof. Never block the thread. Use iterator helpers when you want LINQ-style laziness. Keep money in integers. And run a linter and a formatter in your editor.

Where the C# comparison stops

The deeper differences are in the platform: no CLR or garbage-collector tuning, no reflection comparable to .NET's, no assembly loading, and a package manager and module system with different conventions. Language features such as generics, pattern matching and records have no direct counterpart, and the closest are TypeScript types and destructuring. The reference is in the MDN JavaScript guide and the C# documentation.

Taggedcsharp
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.