Projects Are About Humans. Deal With That!

Variables in JScript



A programming language cannot function without variables. Variables are used to store, retrieve, and also manipulate the value it contains. Based on that value, a variable can contain a string, a number, a boolean value etc. To use a variable, you must first declare it, which means that some memory is allocated to store the variable, so you can refer to it later in your script. You can use the "var" statement to define a variable, and you can choose to initialize also initialize the variable. If you don't initialize a variable in the var statement, then it will be assigned the value "undefined".

var money; //a simple declaration

var first_number, second_number; //multiple declarations in one var keyword

var name1 = "Jack", name2 = "Laura"; //multiple declarations and initializations at the same time

You can always declare a variable without using the var keyword, and then assign a value to it:

price = 1500; // The variable price is declared implicitly.

Take a little time to assign the variable a meaningful name so you know what it holds. Because Jscript is a case-sensitive language, a variable name such as "MyName" is different from "myName". There are some rules in using variable names. First, remember that the first character of the variable must be a letter or the underscore character "_". While a number cannot be used as the first character, the following characters can be numbers, letters, and underscores.

Also, you should not assign a variable the same name as a reserved word.

As you may have noticed, you don't have to also declare the variable type. In other languages, this is a very important step, but JScript is very flexible from this point of view. Its variables have a type corresponding to the type of value they contain. The first benefit of this flexible feature is that you can treat a variable as if it were of another type. This means that if you try to "add" a number to a string, then the number will be converted to a string and then both variables will be concatenated. This process is called coercing. This way, adding a number or a boolean to a string will coerce the result into a string; the result of adding a number to a boolean variable will coerce the result to a number.

No comments yet. Be the first.

Leave a reply