JavaScript Primer: Using Variables and Types

You saw how to define variables in the previous example: You use the var keyword and, optionally, assign a value to the variable in a single statement. Variables that are defined within a function are local variables and are available for use only within that function. Variables that are defined directly in the script element are global variables and can be accessed anywhere, including other scripts in the same HTML document. Listing 5-8 demonstrates the use of local and global variables.

Listing 5-8. Using Local and Global Variables in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myGlobalVar = “apples”;

function myFunc(name) {

var myLocalVar = “sunny”;

return (“Hello ” + name + “. Today is ” + myLocalVar + “.”);

};

console.log(myFunc(“Adam”));

</script>

<script type=”text/javascript”>

console.log(“I like ” + myGlobalVar);

</script>

</head>

<body>

This is a simple example

</body>

</html>

JavaScript is a dynamically typed language. This doesn’t mean JavaScript doesn’t have types. It just means you don’t have to explicitly declare the type of a variable and that you can assign different types to the same variable without any difficulty. JavaScript will determine the type based on the value you assign to a variable and will freely convert between types based on the context in which they are used. The result from Listing 5-8 is as follows:

Hello Adam. Today is sunny.

I like apples

Using global variables in AngularJS development is frowned upon because it undermines the separation of concerns (which I described in Chapter 3) and makes it harder to perform unit testing (which I describe in Chapter 25). As a rule of thumb, if you have to use a global variable to get two components to talk to one another, then something has gone wrong with the application design.

1. Using the Primitive Types

JavaScript defines a set of primitive types: string, number, and boolean. This may seem like a short list, but JavaScript manages to fit a lot of flexibility into these three types.

1.1. Working with Booleans

The boolean type has two values: true and false. Listing 5-9 shows both values being used, but this type is most useful when used in conditional statements, such as an if statement. There is no console output from this listing.

Listing 5-9. Defining boolean Values in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var firstBool = true;

var secondBool = false;

</script>

</head>

<body>

This is a simple example

</body>

</html>

1.2. Working with Strings

You define string values using either the double quote or single quote characters, as shown in Listing 5-10.

Listing 5-10. Defining string Variables in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var firstString = “This is a string”;

var secondString = ‘And so is this’;

</script>

</head>

<body>

This is a simple example

</body>

</html>

The quote characters you use must match. You can’t start a string with a single quote and finish with a double quote, for example. There is no console output for this listing. AngularJS includes three utility methods that make working with string values a little easier, as described in Table 5-2.

You can see all three AngularJS string-related methods in Listing 5-11.

Listing 5-11. Using the AngularJS String-Related Methods in the jsdemo.html File

<!DOCTYPE html>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

console.log(angular.isString(“Hello”) + ” ” + angular.isArray(23));

console.log(“I am ” + angular.uppercase(“shouting”));

console.log(“I am ” + angular.lowercase(“WhiSpeRing”));

</script>

</head>

<body>

This is a simple example

</body>

</html>

The angular.isString method is useful when you are dealing with an object whose type you are unsure of. This is one of a number of related methods that AngularJS provides for typing objects, described throughout this chapter. The angular.uppercase and angular.lowercase methods do exactly as you might imagine, and the statements in the listing produce the following output in the JavaScript console:

true false

I am SHOUTING

I am whispering

1.3. Working with Numbers

The number type is used to represent both integer and floating-point numbers (also known as real numbers). Listing 5-12 provides a demonstration.

Listing 5-12. Defining number Values in the jsdemo.html File

<!DOCTYPE html>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var daysInUeek = 7;

var pi = 3.14;

var hexValue = OxFFFF;

console.log(angular.isNumber(7) + ” ” + angular.isNumber(“Hello”));

</script>

</head>

<body>

This is a simple example

</body>

</html>

You don’t have to specify which kind of number you are using. You just express the value you require, and JavaScript will act accordingly. In the listing, I have defined an integer value, defined a floating-point value, and prefixed a value with 0x to denote a hexadecimal value.

AngularJS supplements the standard JavaScript functionality with the angular.isNumber method, which is passed an object or value and returns true if it is a number and false otherwise. This example produces the following output to the console:

true false

2. Creating Objects

There are different ways to create JavaScript objects. Listing 5-13 gives a simple example.

Tip JavaScript provides support for prototype inheritance, which allows new objects to inherit functionality. This isn’t widely used in JavaScript, but I describe it briefly in Chapter 18 because it underpins one of the ways in which AngularJS services can be created.

Listing 5-13. Creating an Object in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = new Object();

myData.name = “Adam”;

myData.weather = “sunny”;

console.log(“Hello ” + myData.name + “. “);

console.log(“Today is ” + myData.weather + “.”);

</script>

</head>

<body>

This is a simple example

</body>

</html>

I create an object by calling new Object(), and I assign the result (the newly created object) to a variable called myData. Once the object is created, I can define properties on the object just by assigning values, like this:

myData.name = “Adam”;

Prior to this statement, my object doesn’t have a property called name. After the statement has executed, the property does exist, and it has been assigned the value Adam. You can read the value of a property by combining the variable name and the property name with a period, like this:

console.log(“Hello ” + myData.name + “. “);

The result from the listing is as follows:

Hello Adam.

Today is sunny.

2.1. Using Object Literals

You can define an object and its properties in a single step using the object literal format. Listing 5-14 shows how this is done.

Listing 5-14. Using the Object Literal Format in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = {

name: “Adam”,

weather: “sunny”

};

console.log(“Hello ” + myData.name + “. “);

console.log(“Today is ” + myData.weather + “.”);

</script>

</head>

<body>

This is a simple example

</body>

</html>

Each property that you want to define is separated from its value using a colon (:), and properties are separated using a comma (,). The effect is the same as in the previous example, and the result from the listing is as follows:

Hello Adam.

Today is sunny.

2.2. Using Functions as Methods

One of the features that I like most about JavaScript is the way you can add functions to objects. A function defined on an object is called a method. Listing 5-15 shows how you can add methods in this manner.

Listing 5-15. Adding Methods to an Object in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = {

name: “Adam”,

weather: “sunny”,

printNessages: function()

{

console.log(“Hello ” + this.name +           “);

console.log(“Today is ” + this.weather + “.”);

}

};

myData.printMessages();

</script>

</head>

<body>

This is a simple example

</body>

</html>

In this example, I have used a function to create a method called printMessages. Notice that to refer to the properties defined by the object, I have to use the this keyword. When a function is used as a method, the function is implicitly passed the object on which the method has been called as an argument through the special variable this. The output from the listing is as follows:

Hello Adam.

Today is sunny.

2.3. Extending Objects

AngularJS makes it easy to copy methods and properties from one object to another through the angular.extend method, which I have demonstrated in Listing 5-16.

Listing 5-16. Extending Objects in the jsdemo.html File

<!DOCTYPE html>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = {

name: “Adam”,

weather: “sunny”,

printMessages: function () {

console.log(“Hello ” + this.name + “. “);

console.log(“Today is ” + this.weather + “.”);

}

var myExtendedObject = {

city: “London”

};

angular.extend(myExtendedObject, myData);

console.log(myExtendedObject.name);

console.log(myExtendedObject.city);

</script>

</head>

<body>

This is a simple example

</body>

</html>

In this example I create an object with a city property and assign it to the variable called myExtendedObject.

I then use the angular.extend method to copy all of the properties and functions from the myData object to myExtendedObject. Finally, to demonstrate the mix of original and copied properties, I use the console.log method to write out the values of the name and city properties, producing the following console output:

Adam

London

Tip The extend method preserves any properties and methods on the target object. If you want to create a copy of an object without this preservation, then you can use the angular.copy method instead.

3. Working with Objects

Once you have created objects, you can do a number of things with them. In the following sections, I’ll describe the activities that will be useful later in this book.

3.1. Detecting Objects

AngularJS provides the angular.isObject method, which returns true if the argument it is called with is an object and false otherwise, as demonstrated in Listing 5-17.

Listing 5-17. Detecting Objects in the jsdemo.html File

<!DOCTYPE html>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myObject = {

name: “Adam”,

weather: “sunny”,

};

var myName = “Adam”; var myNumber = 23;

console.log(“myObject: ” + angular.isObject(myObject));

console.log(“myName: ” + angular.isObject(myName));

console.log(“myNumber: ” + angular.isObject(myNumber));

</script>

</head>

<body>

This is a simple example

</body>

</html>

I have defined an object, a string, and a number, and I assess them all using the angular.isObject method, producing the following output to the console:

myObject: true

myName: false

myNumber: false

3.2. Reading and Modifying the Property Values

The most obvious thing to do with an object is to read or modify the values assigned to the properties that the object defines. There are two different syntax styles you can use, both of which are shown in Listing 5-18.

Listing 5-18. Reading and Modifying Object Properties in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = {

name: “Adam”,

weather: “sunny”,

};

myData.name = “Joe”;

myData[“weather”] = “raining”;

console.log(”Hello ” + myData.name + “.”);

console.log(“It is ” + myData[“weather“]);

</script>

</head>

<body>

This is a simple example

</body>

</html>

The first style is the one that most programmers with be familiar with and that I used in earlier examples. You concatenate the object name and the property name together with a period, like this:

myData.name = “Joe”;

You can assign a new value to the property by using the equal sign (=) or read the current value by omitting it. The second style is an array-style index, like this:

myData[“weather”] = “raining”;

In this style, you specify the name of the property you want between square braces ([ and ]). This can be a convenient way to access a property because you can pass the name of the property you are interested as a variable, like this:

var myData = {

name: “Adam”,

weather: “sunny”,

};

var propName = “weather”;

myData[propName] = “raining”;

This is the basis for how you enumerate the properties of an object, which I describe next. Here is the console output from the listing:

Hello Joe.

It is raining

3.3. Enumerating an Object’s Properties

You enumerate the properties that an object has using the for…in statement. Listing 5-19 shows how you can use this statement.

Listing 5-19. Enumerating an Object’s Properties in the jsdemo.html File

<!DOCTYPE html>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = {

name: “Adam”,

weather: “sunny”,

printMessages: function () {

console.log(“Hello ” + this.name + “. “);

console.log(“Today is ” + this.weather + “.”);

}

};

for (var prop in myData) {

console.log(“Name: ” + prop + ” Value: ” + myData[prop]);

}

console.log(“—“);

angular.forEach(myData, function (value, key) {

console.log(“Name: ” + key + ” Value: ” + value);

});

</script>

</head>

<body>

This is a simple example

</body>

</html>

The for…in loop is a standard JavaScript feature and performs the statement in the code block for each property in the myData object. The prop variable is assigned the name of the property being processed in each iteration. I use an array-index style to retrieve the value of the property from the object.

AngularJS provides an alternative through the angular.forEach method, which takes the object and a function that will be executed for each property. The function is passed the value of the current property and its name through the value and key parameters. The result is the same as when using the for…in loop, as the following console output shows:

Name: name Value: Adam

Name: weather Value: sunny

Name: printMessages Value: function () {

console.log(“Hello ” + this.name + “. “);

console.log(“Today is ” + this.weather + “.”);

}

Name: name Value: Adam

Name: weather Value: sunny

Name: printMessages Value: function () {

console.log(“Hello ” + this.name + “. “);

console.log(“Today is ” + this.weather + “.”);

}

From the result, you can see that the function I defined as a method on the myData object is also enumerated in both cases. This is as a result of the flexible way that JavaScript handles functions, but it is something to be aware of when you are new to JavaScript.

3.4. Adding and Deleting Properties and Methods

You can still define new properties on an object even if it has been defined using the object literal style. Listing 5-20 gives a demonstration. (The listings in this section do not produce any console output.)

Listing 5-20. Adding a New Property to an Object in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = {

name: “Adam”,

weather: “sunny”,

};

myData.dayOfUeek = “Nonday”;

</script>

</head>

<body>

This is a simple example

</body>

</html>

In this listing, I have added a new property to the object called dayOfWeek. I have used dot notation (concatenating the object and property names with a period), but I could as readily have used the index-style notation. As you might expect by now, you can also add new methods to an object by setting the value of a property to be a function, as shown in Listing 5-21.

Listing 5-21. Adding a New Method to an Object in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = {

name: “Adam”,

weather: “sunny”,

};

myData.SayHello = function() {

console.write(“Hello”);

};

</script>

</head>

<body>

This is a simple example

</body>

</html>

You can delete a property or method from an object using the delete keyword, as shown in Listing 5-22.

Listing 5-22. Deleting a Property from an Object in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = {

name: “Adam”,

weather: “sunny”,

};

delete myData.name;

delete myData[“weather”];

delete myData.SayHello;

</script>

</head>

<body>

This is a simple example

</body>

</html>

3.5. Determining Whether an Object Has a Property

You can check to see whether an object has a property using the in expression, as shown in Listing 5-23.

Listing 5-23. Checking to See Whether an Object Has a Property in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = {

name: “Adam”,

weather: “sunny”,

};

var hasName = “name” in myData;

var hasDate = “date” in myData;

console.log(”HasName: ” + hasName);

console.log(“HasDate: ” + hasDate);

</script>

</head>

<body>

This is a simple example </body>

</html>

In this example, I test for a property that exists and one that doesn’t. The value of the hasName variable will be true, and the value of the hasDate property will be false, as follows:

HasName: true

HasDate: false

Source: Freeman Adam (2014), Pro AngularJS (Expert’s Voice in Web Development), Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *