[JavaScript] Script & Types

This post deals with basic JavaScript features: Types, Values, and Scripting.

<script> Element

The <script> element is used to embed or link script code in HTML documents. It is recommended to use external script files, but you can place script code directly inside HTML.

The <script> element has the following attributes :

  • async: specifies that the script is executed asynchronously (only for external scripts)
  • defer: specifies that the execution of the script is deferred until the page has been parsed (only for external scripts)
  • charset: specifies the character encoding used in an external script file
  • src: specifies the URL of an external script file
  • type: specifies the MIME type of the script
  • language: deprecated
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
  $(document).ready(function () { });
<script>

The MIME type of JavaScript is “application/x-javascript” but traditionally, the “text/javascript” is used for the “type. “The “language” attribute is deprecated and should not be used.

  • In HTML5, JavaScript is the default scripting language, so you can even omit the “type” attribute.

External vs. Internal Scripts

It is recommended to use the external script files and embed them using the “src” attribute. External scripts can be cached in browsers so that it reduces the loading time when it is used for multiple pages.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.js" />

Note that the second syntax is valid in XML but should not be used in HTML documents. It cannot be handled properly in some browsers, notably IE.

Location of <script> Elements

Traditionally, the <script> elements are located in the <head> section.

<head>
  <script type="text/javascript">
  </script>
</head>

This approach nicely separates the script from the body section of a document. But sometimes, the page display can be delayed because the script is loaded before the document.

To load the document before the script, you can put the <script> elements at the end of the <body> section.

Let’s see the following script:

<head>
  <script type="text/javascript">
    alert(document.getElementById("nameInput").value);
  </script>
</head>
<body>
  <input type="text" id="nameInput" value="Homer" />
</body>

The script will fail when the script is executed because the <input> element is not available yet. Let’s move the <script> element to the bottom of the page.

<body>
  <input type="text" id="nameInput" value="Homer" />
  <script type="text/javascript">
    alert(document.getElementById("nameInput").value);
  </script>
</body>

Now the script works correctly.

Deferred Scripts

When the “defer” attribute is specified, the external script will not be executed until the document is completely parsed and displayed.

<script type="text/javascript" src="jquery.js" defer="defer">
</script>

Async Scripts

When the “async” attribute is specified, the script is executed asynchronously. The script will be executed while the page continues the parsing.

<script type="text/javascript" src="jquery.js" async="async">
</script>

<noscript> Element

The <noscript> element is used to show error messages for the browser that does not support Scripting or the browser whose scripting feature is turned off.

<noscript>
  <p>To see this page, you need a JavaScript enabled browser.</p>
</noscript>

Types and Values

Does JavaScript have types like C#? The answer is “Yes.” JavaScript DOES have types. But variables are not typed. What does it mean?

Types

JavaScript types can be divided into two categories:

  • Primitive Types
  • Object Types

JavaScript is Object-Oriented Language. Most types are objects and even inherit from the “Object” object. Primitive types include strings, numbers, and boolean values.

Text

A string is a sequence of 16-bit UNICODE characters. String literals are enclosed within a pair of single or double quotes.

You can get the length of a string using the “length” property.

var s = "Hello, World!";
alert(s.length); // 13

Numbers

  • base-10 integer values: 100, 1024 …
  • hexadecimal: 0xFF
  • floating-point values: 1.23
  • exponential values: 2.03e5 (2.03 * 10^5)

String values can be converted to numbers using the following functions:

  • parseInt(string, radix)
  • parseFloat(string)
var i = "10";
var f = "20.3";
var result = parseInt(i, 10) * 2 + parseFloat(f); // 40.3
alert("10 * 2 + 20.3 = " + result);

[Note] It is always a good practice to provide the radix value to the “parseInt()” function.

There are special values defined in a global scope.

  • Infinity : such divide by zero
  • NaN : Not a Number
var i = 10 / 0; // Infinity
var n = parseInt("NosuchNumber", 10); // NaN
alert(i + ", " + n);

Comparing values to Infinity or NaN requires attention. You cannot compare numbers directly with them. Use the following global functions:

  • isNaN(val): returns true when the value is NaN
  • isFinite(val): returns true when the value is not NaN, Infinite, or -Infinite
var i = 10 / 0; // Infinity
var n = parseInt("NosuchNumber", 10); // NaN
alert(i === Infinity); // true (possible but do not use it)
alert(n === NaN); // false!!!
alert(isFinite(i)); // false
alert(isNaN(n)); // true

In ES2015, the number-related global functions are moved to the “Number” class. The global functions should not be used anymore.

Boolean Values

A boolean value represents “true” and “false. “

Converting from other types to a boolean type is very flexible.

alert(0 ? "true" : "false"); // false
alert(1 ? "true" : "false"); // true
alert("" ? "true" : "false"); // false
alert("0" ? "true" : "false"); // true
alert("1" ? "true" : "false"); // true
alert(null ? "true" : "false"); // false
alert(NaN ? "true" : "false"); // false
alert(Infinity ? "true" : "false"); // true

typeof operator

To determine the type of a value, you can use the “typeof” operator. It returns the type name as a string.

var i = 1;
alert(typeof i); // "number"
 
var f = 2.3;
alert(typeof f); // "number"
 
var infinity = 10 / 0;
alert(typeof infinity); // "number"
 
var nan = parseInt("ab");
alert(typeof nan); // "number"
 
var s = "Hello World!";
alert(typeof s); // "string"
 
var b = true;
alert(typeof b); // "boolean"
 
var a = new Array();
alert(typeof a); // "object"

Undefined Values

If you check the type of a variable that is not initialized, the “undefined” is returned.

var u;
alert(typeof u); // "undefined"
alert(u === undefined); // true
alert(typeof u === "undefined"); // true

Null Values

Null values are for the object types. The variable of a null value does not refer to any object. The “typeof” operator returns “object. “

var nil = null;
alert(typeof nil); // "object"

Note that “null” is not the same as “undefined.”


Type Conversions and Equality

In JavaScript, types are very flexible. JavaScript converts types as needed. But this flexibility of types makes developers confused in some cases. Therefore, it is important to understand the conversion rules.

Automatic Conversion

In JavaScript programming, you need to rely on automatic conversion most of the time. The conversion rules make sense in general.

Explicit Type Conversion

The simplest way to perform the type conversion is to use the following wrapper functions:

  • Number()
  • String()
  • Boolean()
  • Object()
alert(1 + "3"); // 13
alert(1 + Number("3")); // 4
alert(String(false) + "!"); // "false!"
alert(Boolean(Infinity) ? "T" : "F"); // "T"

Converting Numbers to Strings

All numbers in JavaScript are actually “Number” objects. The “Number” object provides methods to convert numbers to strings.

The easiest way to convert a number to a string is to use the “toString()” method. But what if you want to format the number in a specific way?

  • toFixed(x) : the number of digits after the decimal point
  • toExponential(x) : the number of digits after the decimal point
  • toPrecision(x) : the number of digits
ar n = 12.3456789;
alert(n.toFixed(2)); // 12.35
alert(n.toExponential(3)); // 1.235e+2
alert(n.toPrecision(6)); // 12.3457

Check how the values are rounded.

Converting Strings to Numbers

String values can be converted to numbers using the following functions:

  • Number.parseInt(string, radix)
  • Number.parseFloat(string)
var i = "10";
var f = "20.3";
var result = Number.parseInt(i, 10) * 2 + Number.parseFloat(f); 
alert("10 * 2 + 20.3 = " + result); // 40.3

Checking Equality

The most common way to compare two values is to use the “==” and “!=” operator.

The “==” operator compares two values somewhat loosely. Even though the types are different, it still tries to compare the values by converting the type of one of the two values. Therefore (1 == “1”) returns true.

alert(1 == "1"); // true
alert(1 == true); // true
alert(0 == false); // true

Strict Equality (Identity) Operator

Unlike other languages, JavaScript provides another type of equality operator: “===“ and “!==“.

If values are different types, they are not equal.

alert(1 === 1.0); // true
alert(1 === "1"); // false
alert(1 === true); // false
alert(0 === false); // false

Null and Undefined Values

You can also check null or undefined using the strict equality operator.

var nil = null;
var und;
alert(nil === null); // true
alert((typeof und) === "undefined"); // true
alert(und === undefined); // true

Checking undefined values is a little bit tricky.

var x;
// You declared the variable “x” but not “y”.

if (typeof x === "undefined") {
  // works
}
if (x === undefined) {
  // works
}
if (x) {
  // works
}
if (typeof y === "undefined") {
  // works
}
if (y === undefined) {
  // throws an exception
}
if (y) {
  // throws an exception
}

Check when the exception is thrown.


Initializers

For primitive types, you can use the literals (numbers or strings) to initialize variables. For objects and arrays, JavaScript provides initializers (also called “object literals” or “array literals“).

Array Initializer

You can create an array using the Array object constructor. But an array initializer is a way to do it when the value is initially known.

An array initializer is a comma-separated list of values contained within square brackets. The size will be automatically determined.

var arr1 = []; // empty
var arr2 = [1, 2, 3, 4];
alert(arr1.length); // 0
alert(arr2.length); // 4

Object Initializer

Objects consist of properties. An object initializer is also a comma-separated list within curly braces. Each item of the list is a pair of a property name and a value separated by a colon.

var point = { x: 5, y: 4 };
alert(JSON.stringify(point));
alert(point.x + ", " + point.y);

Object initializers are not restricted to properties. You can add methods to the object too.

var point = {
  x: 5,
  y: 4,
  size: function () { return this.x * this.y; }
};
alert(point.size()); // 20

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s