Comparing C# and JavaScript Syntax
Simple statements
The syntax of simple statements are identical.
for ([initializer]; [test]; [increment]) {
...
}
[initializer]
while ([test]) {
...
[increment]
}
if ([test]) {
...
} else if ([test]) {
...
} else {
...
}
Variables
JavaScript is dynamic typed, meaning that any given variable can hold any type of value. C# is static typed, so variables get a type at creation time and can only accept values of the correct type.
Variables in JavaScript are declared with one of three keywords: var
, let
, const
. C# also uses var
to declare variables, but they have different meanings.
var
in C# tells the compiler to infer the type of the variable from context, e.g. in the statement var x = "string";
, x can only be a string
type.
var
in JavaScript creates a variable that can be used anywhere in a function (the variable definition is hoisted
to the start of the enclosing function).
Comparison
Comparison of values is one of the places where JavaScript and C# diverge due to the static/dynamic natures of the languages.
Because JavaScript can only know the type of a value at runtime it relies on type coercion to force values to be the same type. It is therefore safe in JavaScript to compare e.g. a string and a number, because the runtime will coerce the number to a string. However, this leads to unexpected results, so modern JavaScript provides an ===
operator that does not coerce the values, and so different typed values will not match (e.g., "1" == 1
is true, but "1" === 1
is false).
Functions
Calling a function is mostly the same in both languages: result = function(arg1, arg2)
. Of course, in C# result must be the correct type (or the code won't compile).
C# won't let you call a function with the wrong number of arguments, or arguments of the wrong type. JavaScript will pass along to the functions any arguments you provide, filling in missing arguments with 'undefined' and adding any extra arguments onto the end of the formal parameters. (You can access extra arguments through the arguments
array).