JavaScript and Variables

Introduction

Like C#, JavaScript uses variables to store some values in the computer memory.

Declaring a Variable

To let you declare a variable in JavaScript, the language provides the same var keyword used in C#.

The Name of a Variable

A variable must have a name:

When naming your variables, you must avoid reserved words, also called keywords.

Here are examples of declaring variables:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script type="text/javascript">
    var number;
</script>
</head>
<body>

<script>
    var name;
</script>

</body>
</html>

Initialyzing a Variable

Unlike as done in C#, if you declare a variable in JavaScript using the var keyword, you don't have to immediately initialize it. Still, before using the variable in JavaScript in JavaScript, you should assign a value to it. This is done using the = operator. Here are examples:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script type="text/javascript">
    var number = 128;
</script>
</head>
<body>

<script>
    var name = "George Weah;
</script>

</body>
</html>

Declaring many Variables

As done in C#, in JavaScript, you can declare many variables on the same line or section. You can use a single var keyword. Here are examples:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script type="text/javascript">
    var firstName, middleName, lastName;
</script>
</head>
<body>

<script>
    var numerator, denominator;
</script>

</body>
</html>

Sometimes, to make your code easier to read, you can put each variable on its own line. Here are examples:

var firstName,
middleName,
lastName;

Indentation is another way to make your code easier to read. Here are examples:

var firstName,
    middleName,
    lastName;

Introduction to Values

Introduction to Strings

A string is an empty space, a character, a word, or a group of words. In JavaScript, a string can be included in double-quotes. An example of a string is "Welcome to the wonderful world of web development!". A string can also be included in single-quotes.

To initialize a variable for a string, include it in single or double-quotes. Here are examples:

var firstName = "William", middleName = "Jefferson", lastName = "Clinton";

Of course, you can also initialize each variable on its own line. Here are examples:

var firstName = "William",
    middleName = "Jefferson",
    lastName = "Clinton";

When using this technique, you don't have to initialize all variables. You can initialize only those whose values you have/know already.

Introduction to Natural Numbers

An integer is a natural number that is made of one or a combination of digits that are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 in the sequence of your choice.

This would display a dialog box. Enter the line number and click OK or press Enter.

Constants

Introduction

A constant is a value that never changes. These are constant values you can use in your program any time. You can also create your own constants. To create a constant, type the const keyword to the left of a variable. You must immediately initialize that variable with an appropriate value. Here is an example:

const ConversionFactor = 39.37;

Once a constant has been created and it has been appropriately initialized, you can use its name where the desired constant is needed.

Hoisting

In C#, you must declare a variable before using it, such as before getting its value. Here is an example:

@{
    var aphorism = "Absence of evidence is not evidence of absence";

    <p>@aphorism</p>
}

If you try accessing a variable before it has been declared, you would receive an error. That's the case for the following code:

@{
    <p>@aphorism</p>

    var aphorism = "Absence of evidence is not evidence of absence";
}

The error is because the C# compiler reads and immediately analyzes the code from top to bottom. When the compiler encounters a name, if the name represents a variable, the compiler checks whether it is a declaration, based on the fact that the variable is preceded by a valid data type or a keyword (such as var or dynamic). It that's not the case, the compiler checks whether the variable was already declared or the variable exists in another file that the compiler is already aware of. If none of these conditions can be verified, the compiler presents an error (we say that it throws an exception).

The JavaScript interpreter also reads code from top to bottom but it doesn't immediately start processing everything. It first checks everything and creates a list that resembles a tree (in fact it is called a tree list). The list starts with the variables declarations. This means that as the JavaScript interpreter is reading the code, if it encounters the declaration of a variable, it internally puts that declaration in the top of its virtual list. When the list is ready, then the interpreter starts processing the code. As a result, you can access a variable that has not yet been declared, as long as it is declared somewhere in the code. To put it another way, you can first use a variable before declaring it. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<p class="right">Affiche</p>

<script type="text/javascript">
    aphorism = "Absence of evidence is not evidence of absence";
    
    // . . .

    var aphorism;
</script>
</body>
</html>

Hoisting is the ability to access a variable before it has been declared.

Working in a Strict Mode

By default, in JavaScript, as seen above, you don't have to first declare a variable before using it. You can just write a name of a variable and immediately use it. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>

<script>
    evidence;
    
    evidence = = "Absence of evidence is not evidence of absence";
</script>

</body>
</html>

This type of code may create various categories of confusions such as using the same name many times (accidentally thinking that you are using different variables). One solution is to make sure that every variable must be declared before being used. To assist you with this, JavaScript supports a declaration known as use strict. To use it, include this expression in single-quotes somewhere in your code, preferably on its own line, as the first statement of your script. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>

<script>
    'use strict';
    
    . . .
    
</script>

</body>
</html>

Not all browsers support the strict mode; even those that support it don't behave the same. For example, in some browssers (such as Microsoft Edge), the variables that are used without being declared would be ignored.

The Value of a Web Control

To programmatically recognize a webpage, the JavaScript launguage provides an object named document. This object holds a list of all the items on the webpage. When you create a webpage, you may need a webform to interact with your visitors, in which case you would position some webcontrols on that form. As mentioned in the first lesson, you can give a name to each control. There are various ways you can access each control from your JavaScript code. One way is to use the following formula:

document.form-name.control-name.value

In this case, start with document. and and and with .value. Between them, enter the name you had given to the form and the name of the desired control with a period between them. An example would be document.EmploymentApplication.firstName.value. You can then assign that expression to a variable. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<form name="EmploymentApplication">
    <table>
        <tr>
            <td>First Name:</td>
            <td><input type="text" name="firstName" /></td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td><input type="text" name="lastName" /></td>
        </tr>
    </table>
</form>

<script>
    var fName = document.EmploymentApplication.firstName.value;
    var lName = document.EmploymentApplication.lastName.value;
</script>
</body>
</html>

JavaScript Compiles its Interpreted Language

Introduction

In the previous lesson, we saw that a language like C# (also languages like C++, Visual Basic, F#, Pascal, etc) uses an internal application called a compiler that analyses all the code submitted to it. If everything is alright, the compiler gathers everything and converts it in a complicated language, called the machine language, that the computer can understand.

Higher languages like JavaScript (also HTML) also use an internal application but called an interpreter. The interpreter primarilys works exactly like a compiler. It analyzes the code to check the code. The webpage interpreter reads the code from top to bottom. It reads the HTML tags and creates an ordered list to establish how the HTML appear. It adds the CSS formats to each tag to specify how the tag should appear. Then interpreter starts reading the JavaScript code. It ignores the comments and empty spaces to consider only the code sections that will influence both the HTML tags and their CSS formats. On the valid JavaScript code, the interpreter checks for errors or things it doesn't understand. If everything is alright, the interpreter submits its findings to the browser to display the results to the visitor.

Minification

We have learned that, when writing your code in JavaScript and/or one of its libraries, to make your code easier to read, you should include empty spaces and comment. Here are examples:

// Identify the employee by name.
var firstName = "James",
    lastName  = "Caulson";
// Specify the hourly salary
var hourlySalary = 22.3;
// Specify the time worked
var timeWorked = 38.5;
// Create full name
var fullName = firstName + ' ' + lastName;
// Calculate the net pay
var netPay = hourlySalary * timeWorked;

Minification is the technique used by the JavaScript interpreter to optimize your code. Among the techniques it uses, it removes the comments and empty spaces that don't matter for the functionality of your code. From the above code, it may come up with code as follows:

var firstName="James",lastName="Caulson";
var hourlySalary=22.3,timeWorked=38.5;
var fullName=firstName+' '+lastName;
var netPay=hourlySalary*timeWorked;

The interpreter performs many other operations such as renaming variables and reducing the amount of code necessary to get the job done.

Hoisting

In C#, you must declare a variable before using it, such as before getting its value. Here is an example:

@{
    var aphorism = "Absence of evidence is not evidence of absence";

    <p>@aphorism</p>
}

If you try accessing a variable before it has been declared, you would receive an error. That's the case for the following code:

@{
    <p>@aphorism</p>

    var aphorism = "Absence of evidence is not evidence of absence";
}

The error is because the C# compiler reads and immediately analyzes the code from top to bottom. When the compiler encounters a name, if the name represents a variable, the compiler checks whether it is a declaration, based on the fact that the variable is preceded by a valid data type or a keyword (such as var or dynamic). It that's not the case, the compiler checks whether the variable was already declared or the variable exists in another file that the compiler is already aware of. If none of these conditions can be verified, the compiler presents an error (we say that it throws an exception).

The JavaScript interpreter also reads code from top to bottom but it doesn't immediately start processing everything. It first checks everything and creates a list that resembles a tree (in fact it is called a tree list). The list starts with the variables declarations. This means that as the JavaScript interpreter is reading the code, if it encounters the declaration of a variable, it internally puts that declaration in the top of its virtual list. When the list is ready, then the interpreter starts processing the code. As a result, you can access a variable that has not yet been declared, as long as it is declared somewhere in the code. To put it another way, you can first use a variable before declaring it. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<p class="right">Affiche</p>

<script type="text/javascript">
    aphorism = "Absence of evidence is not evidence of absence";
    
    // . . .

    var aphorism;
</script>
</body>
</html>

Hoisting is the ability to access a variable before it has been declared.

Working in a Strict Mode

By default, in JavaScript, as seen above, you don't have to first declare a variable before using it. You can just write a name of a variable and immediately use it. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>

<script>
    evidence;
    
    evidence = = "Absence of evidence is not evidence of absence";
</script>

</body>
</html>

This type of code may create various categories of confusions such as using the same name many times (accidentally thinking that you are using different variables). One solution is to make sure that every variable must be declared before being used. To assist you with this, JavaScript supports a declaration known as use strict. To use it, include this expression in single-quotes somewhere in your code, preferably on its own line, as the first statement of your script. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>

<script>
    'use strict';
    
    . . .
    
</script>

</body>
</html>

Not all browsers support the strict mode; even those that support it don't behave the same. For example, in some browssers (such as Microsoft Edge), the variables that are used without being declared would be ignored.

The Value of a Web Control

To programmatically recognize a webpage, the JavaScript launguage provides an object named document. This object holds a list of all the items on the webpage. When you create a webpage, you may need a webform to interact with your visitors, in which case you would position some webcontrols on that form. As mentioned in the first lesson, you can give a name to each control. There are various ways you can access each control from your JavaScript code. One way is to use the following formula:

document.form-name.control-name.value

In this case, start with document. and and and with .value. Between them, enter the name you had given to the form and the name of the desired control with a period between them. An example would be document.EmploymentApplication.firstName.value. You can then assign that expression to a variable. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<form name="EmploymentApplication">
    <table>
        <tr>
            <td>First Name:</td>
            <td><input type="text" name="firstName" /></td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td><input type="text" name="lastName" /></td>
        </tr>
    </table>
</form>

<script>
    var fName = document.EmploymentApplication.firstName.value;
    var lName = document.EmploymentApplication.lastName.value;
</script>
</body>
</html>

JavaScript Compiles its Interpreted Language

Introduction

In the previous lesson, we saw that a language like C# (also languages like C++, Visual Basic, F#, Pascal, etc) uses an internal application called a compiler that analyses all the code submitted to it. If everything is alright, the compiler gathers everything and converts it in a complicated language, called the machine language, that the computer can understand.

Higher languages like JavaScript (also HTML) also use an internal application but called an interpreter. The interpreter primarilys works exactly like a compiler. It analyzes the code to check the code. The webpage interpreter reads the code from top to bottom. It reads the HTML tags and creates an ordered list to establish how the HTML appear. It adds the CSS formats to each tag to specify how the tag should appear. Then interpreter starts reading the JavaScript code. It ignores the comments and empty spaces to consider only the code sections that will influence both the HTML tags and their CSS formats. On the valid JavaScript code, the interpreter checks for errors or things it doesn't understand. If everything is alright, the interpreter submits its findings to the browser to display the results to the visitor.

Minification

We have learned that, when writing your code in JavaScript and/or one of its libraries, to make your code easier to read, you should include empty spaces and comment. Here are examples:

// Identify the employee by name.
var firstName = "James",
    lastName  = "Caulson";
// Specify the hourly salary
var hourlySalary = 22.3;
// Specify the time worked
var timeWorked = 38.5;
// Create full name
var fullName = firstName + ' ' + lastName;
// Calculate the net pay
var netPay = hourlySalary * timeWorked;

Minification is the technique used by the JavaScript interpreter to optimize your code. Among the techniques it uses, it removes the comments and empty spaces that don't matter for the functionality of your code. From the above code, it may come up with code as follows:

var firstName="James",lastName="Caulson";
var hourlySalary=22.3,timeWorked=38.5;
var fullName=firstName+' '+lastName;
var netPay=hourlySalary*timeWorked;

The interpreter performs many other operations such as renaming variables and reducing the amount of code necessary to get the job done.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next