ECMAScript / JavaScript
ECMAScript is the core standard of object-orientated script languages usually provided for client-side Web Application functionality such as in web browsers. JavaScript was invented by Netscape and continued by Mozilla and is built on top of ECMAScript (Edition 2) since version 1.3. JavaScript's syntax may be similar to Oracle's Java programming language but JavaScript is not a scripted version of Java – it is a completely separate entity. Microsoft's JScript implements some of JavaScript and is also based on some of ECMAScript Edition 2 since version 2.
Languages based on ECMAScript are object-orientated, encapsulating data types like objects, strings, numbers, arrays, dates, errors and functions. The language is also case sensitive: it cares whether the keywords and variable names are lowercase, UPPERCASE, camelCase or generally miXeD cAsE. In such environments that render webpages the scripts will also have access to objects that expose parts of the webpage.
Comments
Comments are provided in two types: Multiple Line Comments:
/* This is an ECMAScript, JavaScript
and JScript multi line comment. */
Single Line Comments start with two slashes and end at the current line's end or the end of the script:
// This is a scripting single line comment.
Data Types
With most programming languages that you compile to produce the application such as C, C++ and Java, you need to specifically state the type of the data (Static Typing). ECMAScript based languages, which were interpreted languages, automatically determine what the type of data is (Dynamic Typing).
Currently most ECMAScript and JavaScript implementations are shifting from script engines to script virtual machines, which compile the script at runtime to improve processing and response performance but still supports Dynamic Typing.
Strings are one or more characters such as letters, number digits and punctuation together and surrounded by either matching double quotes, "This is a string.", or single quotes, 'This is a string.'. The double quote is the preferred choice by many scripters. A backslash ( \ ) is a special character within strings. Within a double quoted string you can have a double quote as part of the string data by preceding the double quote with the backslash as "She said \"Hello!\" to the world". Otherwise the string would end before you intended. Similarly for apostrophes in single quoted strings as 'It doesn\'t shine anymore'. To break up lines within any quoted string you use the newline character ( \n ) as "The sun glows.\nRain is wet.".
Numbers or digits are either whole numbers (or integers), one or more zero to nine characters, optionally with a minus sign before it such as 32 or -68. Or decimal numbers (sometimes called float, double or real numbers) such as 32.183, -68.78802, 1.193e15, -1.03e2, -1.04e-3 or 2.22e-3.
Boolean values are something is (true) or something is not (false). A native boolean value will either be the literal word true without quotes or the literal word false without quotes. In a condition such as if something is this or something is not that, an empty string ( "" ) or ( '' ) would be equivalent to the boolean false as would the number zero ( 0 ) or ( 0.0 ), otherwise they would be equivalent to the boolean true.
Operators
Operators are one or two or the odd three character thing that performs a basic function between one or two values.
- Object Property or Method Pointer (dot
.): - Used in object syntax between object name and either property name or method name.
- Standard Assignment (single equals
=): - Assigns a string, number, array, expression, object or other to a variable.
- String Concatenation (plus sign
+): - Connects at least one string with another string or variable or number or other.
- Math Addition (plus sign
+): - Sums or adds two numbers together, adds the number from the right of the plus sign to the number on the left of the plus sign.
- Math Subtraction (minus sign or dash
-): - Subtracts or deletes one number from another number, deletes the number from the right of the minus sign from the number on the left of the minus sign.
- Math Multiplication (asterisk or star
*): - Multiply or times two numbers together, times the number on the left of the asterisk with the number on the right of the asterisk.
- Division (forward slash
/): - Divides or shares one number from another number, divides the number from the left of the divide sign with the number on the right of the divide sign. If the result is not a whole number than it provides the remainder as a decimal such as
12 / 5is 2.4. - Modulus (percentage sign
%): - Divides or shares one number from another number, divides the number from the left of the modulus sign with the number on the right of the modulus sign. If the result is not a whole number then it does not provide the remainder such as
12 % 5is 2. - Increment (two plus signs
++): - A shorthand to something equals something plus 1. Instead of
result = result + 1you doresult++which provides the currentresultand then adds 1. Or you can do++resultwhich adds 1 and then provides the updatedresult. - Decrement (two dashes or minus signs
--): - A shorthand to something equals something minus 1. Instead of
result = result - 1you doresult--which provides the currentresultand then deletes 1. Or you can do--resultwhich deletes 1 and then provides the updatedresult. - Equals (two equal signs
==): - Compares the value of a variable or literal value on the left of the 'equals' with the value of the variable or literal value on the right of the 'equals'. If they are the same then it returns
trueotherwise returnsfalse. - Not Equals (exclamation mark and single equals
!=): - Compares the value of a variable or literal value on the left of the not equals with the value of the variable or literal value on the right of the not equals. If they are not the same then it returns
trueotherwise returnsfalse. - Strictly Equals (three equal signs
===): - Strictly compares the type and value of a variable or literal value on the left of the strict equals with the type and value of the variable or literal value on the right of the strict equals. If both the type and value are the same then it returns
trueotherwise either are different then returnsfalse. - Strictly Not Equals (exclamation mark and two equal signs
!==): - Strictly compares the type and value of a variable or literal value on the left of the strict not equals with the type and value of the variable or literal value on the right of the strict not equals. If either the type or value are different then it returns
trueotherwise if both are the same then returnsfalse. - Less Than (left pointy bracket
<): - Compares if the left value is less than the value on the right. If so, returns
true, otherwise returnsfalse. - Less Than And Equal To (left pointy bracket and equals
<=): - Compares if the left value is less than or equal to the value on the right. If so, returns
true, otherwise returnsfalse. - Greater Than (right pointy bracket
>): - Compares if the left value is greater than the value on the right. If so, returns
true, otherwise returnsfalse. - Greater Than And Equal To (right pointy bracket and equals
>=): - Compares if the left value is greater than or equal to the value on the right. If so, returns
true, otherwise returnsfalse. - Logical NOT (exclamation mark
!): - Used in conditions. States the value directly to the right is considered as a negative. If the value returns (boolean)
falsethen the condition istrueand the instructions are processed. - Logical AND (two ampersands
&&): - Used in conditions. Checks both the value to the left and to the right. If both values return (boolean)
truethen the overall result istrueand the instructions are processed. - Logical OR (two vertical bars
||): - Used in conditions. Checks both the value to the left and to the right. If either value returns (boolean)
truethen the overall result istrueand the instructions are processed. - Additive Assignment (plus sign and equals
+=): - Equivalent to something = something + someOtherThing for numbers (
answer += 3;ifanswerwas 2 it would now be 5) and also appending strings to existing strings (paragraph += "An extra line.";). - Subtractive Assignment (a dash and equals
-=): - Equivalent to something = something – someOtherThing (
answer -= 3;ifanswerwas 8 it would now be 5). - Multiplication Assignment (an asterisk and equals
*=): - Equivalent to something = something * someOtherThing (
answer *= 3;ifanswerwas 3 it would now be 9). - Division Assignment (a forward slash and equals
/=): - Equivalent to something = something / someOtherThing (
answer /= 5;if answer was 12 it would now be 2.4). - Modulus Assignment (a percentage sign and equals
%=): - Equivalent to something = something % someOtherThing (
answer %= 5;ifanswerwas 12 it would now be 2).
Variables
To store information such as literal numbers, objects, dates or text strings you use variables like you would put a letter in an envelope or a product into a box.
An empty variable will have the special type undefined. You can create an empty variable and assign a value later or create the variable with the value (initialise the variable). The var keyword can be used to formally declare the variable but this keyword is optional.
// Create an empty variable
var myBox;
// Creating a group of empty variables
var myBox, startNumber;
// Assigning a value to the empty variable
myBox = "The blue box";
// Create a variable containing a string
var myBox = "This is a string.";
// Create a variable containing a whole number (an integer)
startNumber = 38;
// Create a variable containing a decimal number (a real number)
startNumber = 1.3;
Variable names must start with either a lower or upper case letter or an underscore ( _ ) or a dollar sign ( $ ), then any number of underscores, dollar signs, digits (0 to 9), lower or upper case letters. ECMAScript is case-sensitive and so lower and upper case letters are different. Such as the variable name myVar is not the same as myvar, MYVAR, Myvar, myVAR, etc. These could be five separate variables.
These simple variables are known as scalar variables. As you may have noticed, at the end of each statement or expression a semi-colon is used to indicate the end of the scripting statement.
If you want to create and initialise a variable but don't want to have an actual value yet, you can use the special null keyword as the value (no quotes around the value) as var myMessage = null;.
Simple mathematical expressions can be simply coded as assigning the answer into the variable but instead of a simple number or string, you state a math expression:
var total = 23 + 38 + 187;
var status = 5.8 – 1.3;
var per = 62 * 3;
var share = 102 / 2;
var result = ((48.3 + 24.2) * 3) / 0.5
var ultraTotal = total + share + per – status - result;
Making the variable total contain the number 248.
The variable status would contain the decimal number 4.5.
Variable per would have the number 186.
For share has 51.
Also result is 435. As in Math you can surround parts of an expression with parenthesis (normal brackets) to control which parts are calculated before others.
And you can re-use variables within the expression making ultraTotal the value of -47.5. So in order to use the variable you simply state the variable name.
Multiple strings, variables and even numbers to be in a single string can be concatenated (connected together) by using the plus sign (+).
var message = "The total of the calculation is " + result + " units.";
So if the result of the variable result is 435 then the value of message is 'The total of the calculation is 435 units.'.
Constants
Constants are like variables but instead of the optional var keyword you use the mandatory const keyword and you must define a value that is not the null keyword. A constant's name must only start with a lower or upper case letter or an underscore followed by any number of underscores, digits or lower or upper case letters. The value of a constant cannot change after its creation.
// Create a couple of constants
const coreValue = 23.33;
const companyName = "MyMetaCorp";
// Use the constants
var totalValue = coreValue + 46.8;
var myMessage = "The total value for " + companyName + " is " + totalValue + ".";
Arrays
Arrays are variables with multiple values in one. Using square brackets, [ ], and a whole number as a zero based index (first index is 0, then 1, etc.) allocates multiple values to a single array variable.
var fruit[0] = "orange";
fruit[1] = "apple";
fruit[2] = "grape";
fruit[3] = "banana";
fruit[4] = "pear";
If you just stated the variable fruit, the value would be 'Array'. In order to access a particular element of the array you would state the array name and it's index as fruit[3] to get the value of banana.
An associative array uses a name instead of an index:
var fruit["first"] = "orange";
fruit["another"] = "apple";
fruit["more"] = "grape";
fruit["thisone"] = "banana";
fruit["thelast"] = "pear";
And so to refer to banana you would state fruit["thisone"].
An array literal uses square brackets to state the comma separated list of elements and assign the whole thing to a variable. This would act like an index array.
var fruit = ["orange", "apple", "grape", "banana", "pear"];
Functions
You can encapsulate or noticeably group statements and expressions into a subroutine or function. Using the keyword function and then giving the function a name followed by parenthesis, which may contain parameters, and then braces (curly backets { } ) for the function body. The statements and expressions go within the braces.
You can feed the function with one or more pieces of information by either having a name or a comma separated list of names within the parenthesis. These names are the parameters of the function. Then you can use the parameters as variables within the function body.
function myFunc () {
var calc = (186 * 3) / 2;
var term = calc + 38;
var total = 18.46 + term;
return total;
} // (function) myFunc
The return keyword provides the output of the function.
function myDynFunc (temp, degrees) {
var calc = (186 * 3) / temp;
var term = calc + degrees;
var total = 18.46 + term;
return total;
} // (function) myDynFunc
The comments after the end brace, }, is not essential for the creation of the function but I have found them very useful especially for functions with loads of lines of statements and expressions and so you don't have to scroll and look back up and find the start of the function to see what the end brace is ending. The comment will tell you right there. After creating the function you use the function by assigning a variable with the function. The variable will then have the result of the function.
calcTotal = myFunc();
calcDynTotal = myDynFunc(2, 38);
calcDynTotal2 = myDynFunc(3, 18);
Resulting in both calcTotal and calcDynTotal would each provide 335.46.
And calcDynTotal2 would provide 222.46.
Variables that are created within functions only exist within that particular function as a local variable. Just as variables created in the general flow of the script are global variables and are available to the general script. So you can have two variables with the same name but one is created and used generally and the other is created and used only within a particular function. They have different variable scopes.
A collection of core functions that can be used include isFinite() which takes a number as its parameter. It returns false if the parameter is not a number or the positive or negative infinity value; otherwise returns true.
isNaN() with a parameter returns true if the parameter is not a number and false if is.
parseInt() tries to convert a string parameter into an integer. An optional second parameter states which base to convert into such as 8 (base 8) is octal (0-7), 10 (base 10) is decimal (0-9) and 16 (base 16) is hexadecimal (0-9 a-z/A-Z). Base 10 is the default if the second parameter is not used. If part of the string can't be converted according to the second parameter then that part till the end of the string will be ignored. If none of the string can be converted then NaN (not-a-number) will be returned.
parseFloat() tries to convert a string parameter into a floating point or decimal number. If part of the string can't be converted then that part till the end of the string will be ignored. If none of the string can be converted then NaN (not-a-number) will be returned.
The String() and Number() functions take a single parameter that can be any type of object (see next section) and convert it into a string object via String() or into a number object via Number().
Page 1, Continue to Page 2
Copyright ©2009 Legend Scrolls and Peter Davison. All rights reserved.