JavaScript

JavaScript (also known as ECMAScript) is a scripting language. JavaScript is used for executing client-side scripts. That means that all JavaScript programs are executed in the browser, not on the server. This makes for much more responsive web pages.

JavaScript is an interpreted language, which means that it is not compiled, and the browser has an interpreter embedded in it that allows it to interpret and execute JavaScript scripts on the fly.

While JavaScript looks a lot like Java, it has no official relation to Java.

JavaScripthas many similarities to Java and C#, though:

  • JavaScript iscase-sensitive.
  • JavaScript is free format.
  • Single line comments begin with //. Multi-line comments are within /*…*/.
  • Statements end with a semicolon or end-of-line.
  • Identifiers begin with a letter or _ or $. Can be followed by letters, digits, $, or _. We will only use letters as the first character.
  • JavaScript has a small number of reserved words.
  • Curly brackets are used to create code blocks.
  • Many operators are the same: ==, !=, >, <, <=, >=, =

Output

Alert boxes

The simplest output from JavaScript is the alert box (similar to a Windows message box).

Example

Create a new HTML5 project called Day12.Copy the following to the body of your index document:

<script>

alert("My First JavaScript");

</script>

All inline (in the HTML file) JavaScript is enclosed inside of a <script> element. If the <script> element is in the <body> element, the JavaScript will be executed as the page is loaded by the browser!

Writing text: document.write

JavaScript can be used to write text directly into the web page, using the document.write command.Since document.write writes directly into the body of the web page, you can include HTML tags when you write.

Example

Add the following to the end of your existing script:

document.write("<h1>This is a heading</h1>");

document.write("<p>This is a paragraph</p>");

NOTE: You can only usedocument.writein the HTML output (<body>). If you use it after the document has loaded (in a function), the whole document will be overwritten.

Functions

JavaScript functions are usually placed in the <head> element or in an external file, and executed in response to some user action, like clicking on a button.

Example

Add the following code to the <head> of your document:

<script>

function myFunction()

{

document.getElementById("demo").innerHTML="My First JavaScript Function";

}

</script>

Then add the following HTML to the <body> of your document:

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>

<button type="button"onclick="myFunction()">Try it</button>

JavaScript can also be in the <body> or in an external file.

More Output

To access an HTML element from JavaScript, you can use the document.getElementById(id) method.Use the "id" attribute to identify the HTML element:

Example

Add the following to your web page:

<h1>My First Web Page</h1>

<p id="demo2">My First Paragraph</p>

<script>

document.getElementById("demo2").innerHTML="My First JavaScript";

</script>

Types, Values, Variables

Numbers

JavaScript does not make a distinction between integers and floating point values. All numbers are represented using the IEEE 754 double data type (64 bits).There is no integer data type!

Integer literals

Integers up to 17 digits can be safely represented in floating-point notation. JavaScript interprets numeric constants as hexadecimal if they are preceded by a zero and x.

Example

var x = 255; // decimal

var z=0xFF; // hex for 255

Floating-point literals

A floating-point literal is any number with a decimal point. JavaScript also lets you use scientific notation, like this: 6.02e23, which is 6.02 * 1023. Numbers can have a + or – sign in front of them.

As in all programming languages, you need to be aware of the fact that, while there is an infinite number of real numbers, there is a finite number of floating-point representations of numbers on a computer. This means that the use of floating-point numbers can cause problems with rounding errors!

Example

Add the following to the bottom of your existing script:

var x = .3 - .2;

var y = .2 - .1;

document.write("<p>x==y: " + (x==y) + "</p>");

document.write("<p>x==.1: " + (x==.1) + "</p>");

document.write("<p>y==.1: " + (y==.1) + "</p>");

You get

x==y: false

x==.1: false

y==.1: true

Add this to the bottom of your existing script:

document.write("<p> x: " + x + "</p>");

document.write("<p> y: " + y + "</p>");

y is .1, but x is 0.09999999999999998

Arithmetic: JavaScript Arithmetic Operators

Given that y=5, the table below explains the arithmetic operators:

Operator / Description / Example / Result of x / Result of y
+ / Addition / x=y+2 / 7 / 5
- / Subtraction / x=y-2 / 3 / 5
* / Multiplication / x=y*2 / 10 / 5
/ / Division / x=y/2 / 2.5 / 5
% / Modulus (division remainder) / x=y%2 / 1 / 5
++ / Increment, both pre and post. / x=++y / 6 / 6
x=y++ / 5 / 6
-- / Decrement, both pre and post / x=--y / 4 / 4
x=y-- / 5 / 4

I recommend that you not use the increment and decrement operators in assignment statements, but use them as standalone statements.

Use this:

x++;

Not this:

y=x++;

The precedence rules are the usual.

  1. Anything in parentheses.
  2. Multiplication, division, remainder (%), left to right.
  3. Addition and subtraction, left to right.
Examples

This example routes output to the console log file, which can be viewed by pressing F12 in Chrome.

x=5;

console.log("x++=" + x++);

console.log("x after x++=" + x);

x=5;

console.log("++x=" + ++x);

console.log("x after ++x=" + x);

Operators

Bitwise Operators

Operator / Usage / Description
Bitwise AND / a & b / Returns a one in each bit position for which the corresponding bits of both operands are ones.
Bitwise OR / a | b / Returns a one in each bit position for which the corresponding bits of either or both operands are ones.
Bitwise XOR / a ^ b / Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.
Bitwise NOT / ~ a / Inverts the bits of its operand.
Left shift / a < b / Shiftsain binary representationb(< 32) bits to the left, shifting in zeros from the right.
Sign-propagating right shift / a > b / Shiftsain binary representationb(< 32) bits to the right, discarding bits shifted off.
Zero-fill right shift / a > b / Shiftsain binary representationb(< 32) bits to the right, discarding bits shifted off, and shifting in zeros from the left.

NOTE: Even though all numbers in JavaScript are represented as 64-bit floating-point numbers, when bitwise operators are used, the operands are converted to their equivalent 32-bit integer representations (32-bit 2s complement) before applying the operator!

Example

var x = 0xF0A0;

var y = 0xAAFF;

console.log("x&y: should be A0A0: " + (x & y).toString(16));

console.log("x|y: should be FAFF: " + (x | y).toString(16));

x=16;

console.log(x<2);

console.log((x<2).toString(2));

console.log(x>2);

console.log((x>2).toString(2));

The toString method's argument specifies the number base

Relational Operators

The relational operators are:

Operator / Example / Comments
==
(equality) / '50'==50 // true
30 ==50 // false / Returns true when both operands are equal. The operands are converted to the same type before being compared.
!=
(non-equality) / '50'!=50 // false
30 !=50 // true / Returns true when both operands are not equal. The operands are converted to the same type before being compared.
===
(equality) / '50'===50 // false
50 ===50 // true / Returns true if both operands are equaland of the same type.
!==
(non-equality) / '50'!==50 // true
50 !==50 // false
50 !==51 // true / Returns true if both operands are not (equal and of the same type).
(greater than) / '050'>40 // true
50 >50 // false / Returns true if the left operand is greater than the right one.
>=
(greater than or equal) / '50'>=50 // true
30 >=50 // false / Returns true if the left operand is greater than or equal to the right one.
(less than) / '50'<40 // false
50 <50 // false / Returns true if the left operand is greater than the right one.
<=
(less than or equal) / '50'<=50 // false
50 <=50 // true / Returns true if the left operand is greater than or equal to the right one.
Examples

You can get some results that you are not used to.

console.log('50'==50);

console.log('050'>40);

Logical Operators

The logical operators are the same as C# or Java. If x is 2 and y is 3:

Operator / Description / Example
and / (x < 10 & y > 1) is true
|| / or / (x==5 || y==5) is false
! / not / !(x==y) is true

A Boolean expression is created by using the logical operators. Because JavaScript does not require all of the values in a Boolean expression to be Boolean values (like C# and Java do), be very careful if you apply these operators to non-Boolean values!

The priority rules are the same as in C# and Java:

  1. ()
  2. !
  3. ||

The Assignment Operator

The assignment operator in JavaScript is the equals sign: =. Since JavaScript does not do strict type checking, the type of the value on the right side does not have to match the type of the variable on the left side.

The assignment operator is also right-associative, which means you can write statements like this:

a = b = c = 0;

This assigns 0 to c. Then it assigns the value of c (0) to b. Then it assigns the value of b (0) to a.

Shortcuts are also allowed:

+=, -=, *=, /=, %=

Similar shortcuts are allowed with the bitwise operators, but be sure you know what you are doing before using these shortcuts with bitwise operators.

JavaScript also has a Math object that supplies many built-in math functions.

Example

//Simulate rolling of a die

console.log("Roll of a die: " + Math.floor(Math.random()*6+1));
document.write("<p> Roll of a die: " + Math.floor(Math.random()*6+1) + "</p>");

Dates and Times

JavaScript has a Date class.

Example

// Today

console.log(Date());

document.write("<p>" + Date() + "</p>");

var today = new Date();

var then = new Date(2000, 7, 4);//Months are 0-based! NOT the 4th of July, but Aug 4!

console.log (today );

document.write("<p>" + today + "</p>");

console.log (then);

document.write("<p>" + then + "</p>");

Text

A String object holds a string of text. You can use the String constructor, or just skip the constructor and use a string constant on the right-hand side of the assignment operator.

Example

var first = new String("George");

var last = "Washington";

String literals

Strings can be enclosed in quotation marks or apostrophes.

String escape sequences

Escape sequences begin with a backslash (\). Escape sequences are used to insert special characters in the middle of a string literal. Some examples:

  • \nnewline
  • \ttab
  • \rreturn
  • \"quotation marks
  • \'apostrophe
  • \\backslash
  • \xXXLatin-1 (ASCII) hex value
  • \uXXXXUnicode value. For example \u03c0 is the character π.

console.log ("\u03c0");

document.write("<h1> \u03c0 </h1>");

String methods

JavaScript has a number of string methods. Strings are immutable; you cannot change them. This is not a problem because you can always create a new one. Strings are treated as read-only arrays of Unicode characters.

Example

s = "Hello, world!"

console.log("s=" + s);// "Hello, world!"

document.write("<p>s=" + s + "</p>");// "Hello, world!"

console.log("First character of s is:" + s[0]);// "H"

document.write ("<p>First character of s is:" + s[0] + "</p>");// "H"

console.log("Last character of s is:" + s[s.length-1]);// "!"

document.write ("<p>Last character of s is:" + s[s.length-1] + "</p>");// "!"

Because strings are immutable, you cannot do this, though:

s[0] = "h"; // illegal! Strings are immutable!

console.log("Is 'H' lower case? " + s);

document.write("<p>Is 'H' lower case? " + s + "</p>");

So how can you change the first letter to lower-case?

s = s[0].toLowerCase() + s.substr(1);

console.log("'H' is now 'h': " + s);

document.write("'H' is now 'h': " + s);

A String Object Property

Method / Description
length / Returns the length of a string

Some String Object Methods

Method / Description
charAt() / Returns the character at the specified index
charCodeAt() / Returns the Unicode of the character at the specified index
concat() / Joins two or more strings, and returns a copy of the joined strings
fromCharCode() / Converts Unicode values (integers) to characters
indexOf("x") / Returns the position of the first found occurrence of a specified value in a string
lastIndexOf() / Returns the position of the last found occurrence of a specified value in a string
match() / Searches for a match between a regular expression and a string, and returns the matches
replace() / Searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring
search() / Searches for a match between a regular expression and a string, and returns the position of the match
split() / Splits a string into an array of substrings
substr() / Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
substring() / Extracts the characters from a string, between two specified indices
toLowerCase() / Converts a string to lowercase letters
toUpperCase() / Converts a string to uppercase letters

A String operator

The plus sign is the concatenation operator in JavaScript.

Example

var first = "George"

var last = "Washington"

console.log(first + last);

document.write("<p>" + first + last + "</p>");

Since the plus sign is overloaded (has two distinct meanings, depending on context), the interpreter needs to know what to do when you use the plus sign with both strings and numbers. When this happens, it always interprets the plus sign as the concatenation operator.

var first = "George";

console.log(first + 7); // gives 'George7'

console.log(7 + first); // gives '7George'

console.log(7 + "7"); // gives '77'

console.log("7" + 7); // gives '77'

console.log(Number("7") + 7); // gives 14

The order of the operands makes no difference (as it does in some other languages).

Strings in Java are sequences of 16-bit Unicode values.

Pattern matching

JavaScript has a RegExp class for creating and manipulating regular expressions. JavaScript uses the Perl syntax for regular expressions. More later.

Day12-JavaScript.docx110/27/2018