This post is part of a series comparing the language features of the C#, Javascript and Ruby programming languages.
Variables
C# requires that variables be declared with a specific type. Javascript and Ruby determine the type of variables at runtime. Here is the syntax:
C#
public string publicMessage = "Hello World";
private string privateMessage = "Hello World";
static string PRIVATE_MESSAGE = "Hello World";
Javascript
var message = "Hello World";
Javascript does not have a syntax for making variables public or private, instead it is achieved by a clever usage of closure (discussed later). Javascript does not have block scope, which means that variables defined within a block can be accessed from outside the block (a block is anything in {} such as and if statement or a loop). In Javascript variables are scoped to the function in which they are declared and are visible anywhere within that function, including within inner functions.
// this function will alert "Hello World" twice.
function showMessage() {
if (true) {
var message = "Hello World";
}
alert(message);
var innerFunction = function() {
alert(message);
};
innerFunction();
}
Ruby
A ruby variable is declared by assigning to the variable name. Ruby uses prefixes to indicate the variable scope.
# local variable
message = "Hello World"
# instance variable
@message = "Hello World"
# static variable
@@message = "Hello World"
# global variable
$message = "Hello World"