JavaScript Tutorial

JavaScript Where To

Script can be placed in the , or in the section of an HTML page , or in both. But placing scripts at the bottom of the element improves the display speed , because script complation slow down the display.

Scripts can also be placed in external files and it is a practical method to solve the problem the same code is used in many different web pages . It’s important to note that you can’t contain tags in external scripts . Placing scripts in external files has some advantages as below :

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads

External scripts can be referenced with a full URL or with a path relative to the current web page .

JavaScript Output

JavaScript can display data use innerHTML/document.write()/window.alert()/console.log() .

  • Using innerHTML

    1
    document.getElementById().innHTML = 'content';

    Changing the innerHTML property of an HTML element is a common way to display data in HTML.

  • Using document.write()

    For testing purposes , it is convenient to use document.write() .

    1
    document.write('content');

    Noted: Using document.write() after an HTML document is fully loaded , will delete all existing HTML .

  • Using window.alert()

    1
    window.alert('content');
  • Using console.log()

    For debugging purpose, you can use the console.log() method to display data.

    1
    console.log('content');

JavaScript Statements

A JavaScript program is a list of programming statements. In HTML, JavaScript programs are executed by the web browser. A JavaScript statement consists of values, operators, expressions, keywords and comments. The statements are executed one by one, in the same order as they are written.

Semicolons

JavaScript statements separated by semicolons.

1
2
3
4
var a, b, c;
a = 1;
b = 2;
c = 3;

When separated by semicolons, you are allowed write multiple statements on one line.

Ending statements with semicolons is not required, but highly recommended.

JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make ite more readable and put spaces around operators is a good practice.

JavaScript Line Length and Line Breaks

You should avoid code lines longer than 80 characters for best readability.

JavaScript Code Blocks

JavaScript statements can be grouped together in code blocks, inside curly brackets {}. The purpose of code blocks is to define statements to be executed together.

JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be performed and they are all reserved words. Reserved words cannot be used as names of variables.

JavaScript Syntax

JavaScript syntax is the set of rules, how JavaScript programs are constructed.

JavaScript Values

The JavaScript syntax defines two types of values: Fixed values and variable values. Fixed values are called literals. Variable values are called variables.

JavaScript Operators

JavaScript uses arithmetic operators (+ - * /) to compute values and use an assignment operator (=) to assign values to variables.

JavaScript Expressions

An expressions is a combination of values, variables, and operators, which computes to a value.

JavaScript is Case Sensitive

All JavaScript identifiers are case sensitive.

JavaScript and Camel Case

Historically, programmers have used different ways of joining multiple words into one variable name .

  • Hyphens are not allowed in JavaScript. They are reserved for subtractions
  • Underscore
  • Upper Camel case (Pascal Case)
  • Lower Camel Case

JavaScript tend to use camel case that start with a lowercase letter, such as :

1
firstName, lastName, masterCard, interCity

JavaScript Character Set

JavaScript uses the Unicode character set

JavaScript Comments

JavaScript comments can be used to explain JavaScript code, and to make it more readable.

  • Single line comments start with //. Any text between // and the end of line will be ignored by JavaScript
  • Multi-line Comments start with /* and end with /. Any text between /\ and */ will be ignored by JavaScript

JavaScript Variables

JavaScript variables are containers for storing data values. In programming, just like in algebra, we use variables to hold values. All JavaScript variables must be identified with unique names. These unique names are called identifiers.

The general rules for constructing names for varialbes ard :

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter
  • Names can also begin with $ and __
  • Names are case sensitive
  • Reserved words cannot be used as names

It is a good programming practice to declare all variables at the beginning of a script.

A variable declared without a value will have the value undefined .

If you put a number in quotes, the rest of numbers will be treated as strings and concatenated.

JavaScript Data Types

JavaScript variables can hold many data types: numbers, string, objects and mored. In programming, data types is an import concept. To be able to operate on variables, it is important to konw something about the type.

When adding a number and a string, JavaScript will treat the number as a string.

JavaScript evaluates expression from left to right. Different sequences can produce different results.

JavaScript has dynammic types. This means that the same variable can be used to hold different data types.

You can use the JavaScript typeof operator to find the type of a JavaScript variable. The typeof operator returns the type of a variable or an expression.

In JavaScript, a variable without a value, has the value undefined . The typeof is also undefined .

In JavaScript null is “nothing”. It is supposed to be something that doesn’t exist. Unfortunately, in JavaScript, the data of null is an object. You can consider it a bug in JavaScript that typeof null is an object. It should be null.

Difference Between Undefined and Null

Undefined and null are equal in value but different in type

1
2
3
4
5
typeof undefined	// undefined
typeof null // object

null === undefined // false
null == undefined // true

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when “something” invokes it.

Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscored, and dollar signs. The parentheses may include parameter names separated by commas: (parameter, parameter, …).

Invocation

The code inside the function will execute when “something” invokes the function :

  • when an event occurs
  • When it is invoked from JavaScript code
  • Automatically

Return

When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will return to execute the code after the invoking statement. Function often compute a return value. The return value is “returned” back to the caller.

1
2
3
4
5
6
7
// define a function
function convertStringToLowerCase (text) {
return text.toLocaleLowerCase();
}

// invoke a function
var lowerCaseStr = convertStringToLowerCase("Hello JavaScript !");

Accessing a function without () will return the function definition instead of the function result.

Why Functions?

You can reuse code by using function. As it is : Define the code once, and use it many times.

Functions used as variable values

Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

1
console.log("text".toLocalLowerCase());

JavaScript Object

JavaScript objects are containers for named values called properties or methods.

Object Definition

You define a JavaScript object with an object literal

1
var object = {key: value, key: value, ...};

Object Properties

The name:values pairs in JavaScript objects are called properties. You can access object properties in two ways :

  • objectName.propertyName
  • objectName["propertyName"]

Object Methods

Objects can also have methods - actions that can be performed on objects. Methods are stored in properties as function definitions. A method is a function stored as a property.

1
2
3
4
5
6
var objct = {
key: value,
key: value,
...
methodName: function () {}
};

The this keyword

In a function definition, this refers to the “owner” of the function.

Accessing Object Mehtods

You access an object method with the following syntax :

1
objctName.methodName();

Do Not Declare Strings, Numbers, and Booleans as Objects!

When a JavaScript variable is declared with the keyword “new”, the variable is created as an object. Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.

JavaScript Scope

Scope determines the accessibility of variables.

Function Scope

In JavaScript there are two types of scope:

  • Local scope
  • Global scope

JavaScript has function scope: Each function creates a news scope. Scope determines the accessibility of these variables.

Variables defined inside a function are not accessible from outside the function.

Local Variables

Variables declared within a JavaScript function, become Local to the function. Local variables have local scope: They can only be accessed within the function.

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a function starts, and deleted when the function is completed.

Global Variables

A variable declared outside a function, become Global. A global variable has global scope: All scripts and functions on a web page can access it.

JavaScript Variables

In JavaScript, objects and functions are also variables.

Scope determines the accessibility of variables, objects, and functions from different parts of the code.

Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a global variable, even if the variable inside a function.

Strict Mode

All modern browsers support running JavaScript in “Strict Mode”. In Strict mode, global variables are not created automatically.

Global Variables in HTML

With JavaScript, the global variable scope is the complete JavaScript environment.

In HTML, the global scope is the window object. All global variables belong to the window object.

The Lifetime of JavaScript Variables

The lifetime of a JavaScript variable starts when it is declared.

Local variables are deleted when the function is completed.

In a web browser, global variables are deleted when you close the browser window, but remain available to new pages loaded into the same window.

JavaScript Events

HTML events are “things” that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can “react” on these events.

HTML Events

An HTML event can be something the browser dose, or somthing a user does.

JavaScript lets you execute code whtn events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

1
<element event="some JavaScript">

JavaScript code is often several lines long. It is more common to see event attributes calling functions.

1
<element event="functoinName">

What can JavaScript Do ?

Event handlers can be used to handle, and verify, user input, user actions, and browser actions.

JavaScript Strings

JavaScript strings are used for storing and manipulating text.

String Length

The length of a string is found in the built in property length.

1
2
var txt = "AaBbCcDdEeFfGg";
var length = txt.length;

Special Characters

Because strings must be written within quotes, JavaScript will misunderstand this string and the solution to avoid this problem, is to use the backslash escape character.

Breaking Long Code Lines

For best readability, programmers often like to avoid code lines longer than 80 characters. If a JavaScript statements does not fit on one line, the best place to break it is after an operator.

1
2
document.getElementById("element-id").innerHTML =
"content";

You can also break up a code line within a text string with a single backslash.

1
2
3
var text = "Line - 1 \
Line - 2
";

Strings Can be Objects

Normally, JavaScript strings are primitive values, created from literals, but strings can also be defined as objects with the keyword new.

1
2
var literalStr = "literal string";
var objectStr = new String("object string");

JavaScript String Methods

Primitive values cannot have propertiess or methods, because they are not objects.

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
var orignalStr = "AaBbCcDdAaBbCcDd";
var subStr = "aB";

// the length property returns the length of a string
// strLength is 8
var strLength = orignalStr.length;

// the indexOf() method returns the index of the first occurrence of a specified text in a string
// subStrIndex is 1

// the lastIndexOf() method returns the index of the last occurrence of a specified text in a string
// lastIndexOfSubStr is 9

// Both indexOf() and lastIndexOf() return -1 if the text is not found
// Both indexOf() and lastIndexOf() accept a second parameter as the starting position for search.
var subStrIndex = orignalStr.indexOf(subStr);
var lastIndexOfSubStr = orignalStr.lastIndexOf(subStr);

// the search() method search a string for a specified value and return the position of the match
// search() method cannot accept second parameter and can take regular expressions as search values
// subStrIndex is 1
var subStrIndex = orignalStr.search(subStr);

// slice(start, end),substring(start, end), and substr(start, length) for extracting a part of a string.
// slice() extracts a part of a string and returns the extracted part in a new string
// substring() is similar to slice(), the difference is that substring() cannot accept negative indexes
// substr() is similar to slice(), the difference is that the second parameter specifies the length of the extracted part.

// now resultStr1, resultStr2, resultStr3 is AaBb
var resultStr1 = orignalStr.slice(0, 3);
var resultStr2 = orignalStr.substring(0, 3);
var resultStr3 = orignalStr.substr(0, 4);

// the replace() method replaces a specified value with anthor value in a string
// resultStr now is Hello JavaScript
// the replace() method does not change the string it is called on, it returns a new string.
// By default, the replace() function replaces only the first match
// To replace all matches, use a regular expression with a /g flag
orignalStr = "Hello Lee Code";
resultStr = orignalStr.replace("Lee Code", "JavaScript");

// A string is converted to upper case with toUpperCase()
// now resultStr is ABCDEFG
orignalStr = "abcdefg";
resultStr = orignalStr.toUpperCase();
// A string is converted to lower case with toLowerCase()
resultStr = resultStr.toLowerCase();

// contact() joins two or more strings
var contactStr = "A".contact("B","C","D");

// trim() method remove whitespace from both sides of a string
// now resultStr is ABC
orignalStr = "A B C";
resultStr = orignalStr.trim();

// the charAt() method returns the character at a specified index in a string
// now resultStr is A
resultStr = orignalStr.charAt(0);

// Accessing a string as an array is unsafe
// You can accessing a string as an array but it is upsafe and unpredictable
// If you want read a string as an array, convert it to an array first
// split() method can convert a string to an array
// now charArr is [a, b, c, d, e, f, g]
orignalStr = "a,b,c,d,e,f,g";
var charArr = orignalStr.split(",");

All string methods return a new string. They don’t modify the orignal string.

Formally said: Strings are immutable: Strings cannot be changed, only replaced.

JavaScript Numbers

JavaScript has only one type of number. Numbers can be writtenn with or without decimals.

Extra large or extra small numbers can be written with scientific notation.

1
2
let x = 123e5;
let y = 123e-5;

JavaScript Numbers are always 64-bit Floating Point

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

This format stores numbers in 64 bits, where the number is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63.

Precision

Integers are accurate up to 15 digits.

The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate.

1
2
// x will be 0.3000000000000004
let x = 0.2 + 0.1;

To solve the problem above, it helps to multiply and divide

1
let x = (0.2*10 + 0.1*10) / 10;

Adding Numbers and Strings

JavaScript uses the + operator for both addition and concatenation. Numbers are added. Strings are concatenated.

1
2
3
4
5
6
7
8
9
// strResult will be 12
let strX = "1";
let strY = "2";
let strResult = strX + strY;

// numberResult will be 3
let numberX = 1;
let numberY = 2;
let numberResult = numberX + numberY;

The JavaScript compiler works from left to right.

Numeric Strings

JavaScript strings can have numeric content and JavaScript will try to convert strings to numbers in all numeric operations.

1
2
3
4
// result will be 0.5
let x = "1";
let y = "2";
let result = x / y;

NaN - Not a Number

NaN is a JavaScript reserved word indicating that a number is not a legal number.

Try to do arithmetic with a non-numberic string will result in NaN.

1
2
// x will be NaN
let x = 100 / "a";

You can use the global JavaScript function isNaN() to find out if a value is a number.

NaN is a number : typeof NaN returns number:

1
2
// returns "number"
typeof NaN;

Infinity

Infinity is the value JavaScript will return if you calculate a number outside the largest possible number.

Division by 0 also generates Infinity. Infinity is a number: typeof Infinity returns number.

Hexadecimal

JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.

Never write a number with a leading zero. Some JavaScript versions interpret numbers as octal if they are written with a leading zero.

By default, JavaScript displays numbers as base 10 decimals. But you can use the toString() method to output numbers from base 2 to base 36.

1
2
3
4
5
6
let number = 32;
number.toString(10); // 32
number.toString(32); // 10
number.toString(16); // 20
number.toString(8); // 40
number.toString(2); // 100000

Numbers Can be Objects

Normally JavaScript numbers are primitive values created from literals, but numbers can also be defined as objects with the keyword new.

1
2
let x = 123;				// typeof x return number
let y = new Number(123); // typeof y return object

Do not create Number objects. It slows down execution speed.

Or even worse, Objects cannot be compared.

JavaScipt Number Methods

Number methods help you work with numbers.

All number methods can be used on any type of numbers.

  • toString()

    toString() returns a number as a string

  • toExponential()

    toExponential() returns a string, with a number rounded and written using exponential notation.

    A parameter defines the number of characters behind the decimal point. The parameter is optional, if you don’t specify it, JavaScript will not round the number.

    1
    2
    3
    4
    let x = 1.23456;
    x.toExponential(2); // 1.23e+0
    x.toExponentail(4); // 1.2345e+0;
    x.toExponentail(6); // 1.234560e+0
  • toFixed()

    toFixed() returns a string, with the number written with a specified number of decimals.

    1
    2
    3
    4
    5
    let x = 1.2345;
    x.toFixed(0); // 1
    x.toFixed(2); // 1.23
    x.toFixed(4); // 1.2345
    x.toFixed(6); // 1.234500
  • toPrecision()

    toPrecision() returns a string, with a number written with a specified length

    1
    2
    3
    4
    5
    let x = 1.2345;
    x.toPrecision(); // 1.2345
    x.toPrecision(2); // 1.2
    x.toPrecision(4); // 1.235
    x.toPrecision(6); // 1.234500
  • valueOf()

    valueOf() returns a number as a numer. This method is used internally in JavaScript to convert Number objects to primitive values.

    All JavaScript data types have a valueOf() and a toString() method.

Converting Variables to Numbers

There are 3 JavaScript methods that can be used to convert variables to numbers : Number() , parseInt() , parseFloat() . These methods are not number methods, but global JavaScript methods.

JavaScript global methods can be used on all JavaScript data types.

  • Number()

    This method returns a number, converted from its argument.

    1
    2
    3
    4
    5
    6
    Number(true);	// 1
    Number(false); // 0
    Number("10"); // 10
    Number(" 10"); // 10
    Number("10 20"); // NaN
    Number("John"); // NaN

    If the number cannot be converted, NaN is returned.

    Number() can also convert a date to a number

    1
    Number(new Date("2016-06-10");	// returns the number of milliseconds since 1.1.1970
  • parseFloat()

    This method parses its argument and returns a floating point number. Space are allowed.

    1
    2
    3
    4
    5
    parseFloat("10");			// 10
    parseFloat("10.33"); // 10.33
    parseFloat("10 20"); // 10
    parseFloat("10 years"); // 10
    parseFloat("years 10"); // NaN
  • parseInt()

    This method parsed its argument and returns an integer. Space are allowed.

    1
    2
    3
    4
    5
    parseInt("10");			// 10
    parseInt("10.33"); // 10
    parseInt("10 20 30"); // 10
    parseInt("10 years"); // 10
    parseInt("years 10"); // NaN

Number Properties

Number properties belongs to the JavaScript’s number object wrapper called Number. These properties can only be accessed as Number.propertyName . And these properties cannot be used on variables.

  • MAX_VALUE

    Returns the largest number possible in JavaScript

  • MIN_VALUE

    Returns the smallest number possible in JavaScript

  • NEGATIVE_INFINITY

    Represents negative infinity (returned on overflow)

  • NaN

    Represents a “Not-a-Number” value

  • POSITIVE_INFINITY

    Return infinity (return on overflow)

JavaScript Arrays

JavaScript arrays are used to store multiple values in a single variable. An array can hold many values under a single name, and you can access the values by referring to an index number.

Creating an Array

Using an array litral is the easiest way to create a JavaScript Array.

1
var array_name = [item, item, item, ...];

Using the keyword new create an array.

1
var array_name = new Array(item, item, ...);

Accessing the Elements of an Array

You refer to an array element by referring to the index number.

1
2
3
4
let arrayNum = [1, 2, 3, 4];
let element = arrayNum[0]; // element is 1
arrayNum[1] = 0;
element = arrayNum[1]; // element is 0

Accessing the Full Array

With JavaScript, the full array can be accessed by referring to the array name.

Arrays are a special type of objects, with numberd indexes. The typeof operator in JavaScript returns “object” for arrays.

How to Recognize an Array?

  • Array.isArray()

  • Create your own isArray() function

    1
    2
    3
    function isArray(arr) {
    return arr.constructor.toString().indexOf("Array") > -1;
    }
  • instanceof operator

    1
    2
    let arrayNum = [1, 2, 3, 4];
    arrayNum instanceof Array // true

JavaScript Array Methods

  • toString()

    The method toString() converts an array to a string of array values.

    1
    2
    let arrayStr = ["Hello ", " World", " !"];
    let resultStr = arrayStr.toString(); // result is Hello World !

    JavaScript automatically converts an array to a comma separated string when a primitive value is expected. This is always the case when you try to output an array.

    1
    2
    let strArr = ["Apple", "Google", "Facebook", "Twitter"];
    let result = strArr.toString(); // result is "Apple","Google","Facebook","Twitter"
  • join()

    The method join() alos joins all array elements into a string. It behaves just like toString(), but in addition you can specify the separator.

    1
    2
    let arrayNum = [1, 2, 3, 4];
    let rusultStr = arrayNum.join("*"); // resultStr is 1*2*3*4
  • pop()

    The method pop() removes the last element from an array

    1
    2
    let arrayNum = [1, 2, 3, 4];
    let result = arrayNum.pop(); // arrayNum now is [1, 2, 3] and result is 4
  • push()

    The method push() adds a new element to an array at the end and return the new array length.

    1
    2
    let arrayNum = [1, 2, 3];
    let result = arrayNum.push(4); // now arrayNum is [1, 2, 3, 4] and result is t
  • shift()

    The method shift() removes the first array element and shifts all other elements to a lower index.

    1
    2
    let arrayNum = [1, 2, 3, 4];
    let result = arrayNum.shift(); // arrayNum is [2, 3, 4] and result is 1
  • unshift()

    The method unshift() method adds a new element to an array at the beginning and return the new array length

    1
    2
    let arrayNum = [1, 2, 3, 4];
    let result = arrayNum.unshift(0); // now arrayNum is [0, 1, 2, 3, 4] and result is 5
  • splice()

    The method splice() method can be used to add new items to an array.

    1
    2
    let arrayNum = [1, 2, 3];
    arrayNum.splice(2, 0, 0.1, 0.2); // now arrayNum is [1, 2, 0.1, 0.2, 3]

    Also can be used to remove elements

    1
    2
    let arrayNum = [1, 2, 3];
    arrayNum.splice(0, 1); // now arrayNum is [2, 3]
  • concat()

    The method concat() creates a new arry by merging existing arrays and it can take any number fo array arguments.

    1
    2
    3
    let arrX = [1, 2, 3];
    let arrY = [4, 5];
    let result = arrX.concat(arrY); // result is [1, 2, 3, 4, 5]

    The concat() method can also take values as arguments.

  • slice()

    The slice() method slices out a piece of an array into a new array and creates a new array. It does not remove any elements from the source array.

    1
    2
    3
    let strArr = ["A", "B", "C", "D"];
    let result = strArr.slice(1); // result is ["B", "C", "D"]
    result = strArr.slice(1, 3); // now result is ["B", "C"]

Sorting an Array

  • sort()

    The sort() method sorts an array alphabetically

    1
    2
    let strArr = ["b", "d", "a", "c"];
    strArr.sort(); // now strArr is ["a", "b", "c", "d"]

    By default, the sort() function sorts values as strings. Because of this, the sort() method will produce incorrect result when sorting numbers. You can fix this by providing a compare function.

    1
    2
    3
    4
    5
    6
    7
    let numArr = [100, 20, 50 10, 40];
    numArr.sort( function (numX, numY) {
    return numX - numY;
    }); // now numArr is [10, 20, 40, 50, 100]
    numArr.sort( function (numX, numY) {
    return numY - numX;
    }); // now numArr is [100, 50, 40, 20, 10]

    The purpose of the compare function is to define an alternative sort order. The compare function should return a negative, zero, or positive value, depending on the arguments.

    You can even sorting an array in random order.

    1
    2
    3
    4
    let numArr = [1, 2, 4, 3, -1];
    numArr.sort( function (numX, numY) {
    return 0.5 - Math.random();
    });
  • reverse()

    The reverse() method reverses the elements in an array.

    1
    2
    3
    let strArr = ["b", "d", "a", "c"];
    strArr.sort(); // now strArr is ["a", "b", "c", "d"]
    strArr.reverse(); // now strArr is ["d", "c", "b", "a"]
  • Find the highest (or lowest) array value

    There are no built-in functions for finding the max or min value in an array.

    However, after you have sorted an array, you can use the index to obtain the highest and lowest values

    1
    2
    3
    4
    5
    6
    7
    8
    9
    let numArr = [100, 20, 50, 10, 40];
    numArr.sort( function (numX, numY) {
    return numX - numY;
    }); // now numArr is [10, 20, 40, 50, 100]
    const minValue = number[0]
    numArr.sort( function (numX, numY) {
    return numY - numX;
    }); // now numArr is [100, 50, 40, 20, 10]
    const maxValue = numArr[0];

    You can also use Math.max.apply to find the highest number in an array

    1
    2
    3
    4
    5
    let numArr = [100, 20, 50, 10, 40];
    function maxValueInArr (arr) {
    return Math.max.apply(null, arr);
    };
    const maxValue = maxValueInArr(numArr); // maxValue is 100

    Or ues Math.min.apply() to find th lowest number in an array

    1
    2
    3
    4
    5
    let numArr = [100, 20, 50, 10, 40];
    function minValueInArr (arr) {
    return Math.min.apply(null, arr);
    };
    const minValue = minValueInArr(numArr); // minValue is 100

    The fastest solution is to use a “home made” method.

    The function loops through an array comparing each value with the highest value found.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    function maxValueInArr (arr) {
    let arrLen = arr.length;
    let maxValue = - Infinity;
    while (arrLen --) {
    if (arr[arrLen] > max) {
    maxValue = arr[arrLen];
    }
    }
    return maxValue;
    }

    The function loops through an array comparing each value with lowest value found.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    function minValueInArr (arr) {
    let arrLen = arr.length;
    let minValue = Infinity;
    while (arrLen--) {
    if (arr[arrLen] < minValue) {
    minValue = arr[arrLen];
    }
    }
    retrun minValue;
    }

    JavaScript arrays often contain objects. Even if objects have properties of different data types, ther short() method can be used to sort the array. The solution is to write a compare function to compare the property values.

    1
    2
    3
    4
    5
    6
    7
    8
    let objArr = [{name:"a", age: 19}, {name:"b", age: 9}, {name:"ac", age: 80}];
    objArr.sort(function sortObjByAge (objX, objY) {
    let ageX = objX.age;
    let ageY = objY.age;
    if (ageX < ageY) { return -1;}
    if (ageX > ageY) {return 1;}
    return 0;
    });

JavaScript Array Iteration

Array iteration methods operate on every array item.

  • Array.forEach()

    The forEach() method calls a function once fro each array element.

    1
    2
    3
    4
    5
    let strArr = ["a", "b", "c", "d"];
    let result = "";
    strArr.forEach( function (value, index, arr) {
    result = result + value + "\n";
    });
  • Array.map()

    The map() method creates a new array by performing a function on each arry element.

    1
    2
    3
    4
    let numArr = [12, 2, 33, 21, 4];
    let newNumArr = numArr.map( function (value, index, array) {
    return value*2;
    });
  • Array.filter()

    The filter() method creates a new array with array elements that passes a test.

    1
    2
    3
    4
    let numArr = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0];
    let evenNumArr = numArr.filter( function (value, index, arr) {
    if (value % 2 == 0) { return value;}
    });
  • Array.reduce()

    The reduce() method reduces an array to single variable.

    1
    2
    3
    4
    let numArr = [1, 3, 5, 7, 9];
    let result = numArr.reduce( (sum, value) => {
    return sum + value;
    });
  • Array.every()

    The every() method check if all array values pass a test.

    1
    2
    3
    4
    let numArr = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0];
    let evenNumArr = numArr.every( function (value) {
    if (value % 2 == 0) { return value;}
    });
  • Array.indexOf()

    Search an array for an element value and returns its position.

    1
    2
    let numArr = [1, 3, 5, 7, 9];
    let result = numArr.idnexOf(5);
  • Array.lastIndexOf()

    Array.lastIndexOf() is the same as Array.indexOf() , but searches from the end of the array.

JavaScript Date Objects

By default, JavaScript will use the browser’s time zone and display a date as a full text string :

Fri Jun 13 2016 14:24:54 GMT+0800 (China Standard Time)

Creating Date Objects

Date objects are created with the new Date() constructor.

1
2
3
4
5
6
7
8
9
// new Date() create a new date object with current date and time
new Date();
// new Date(year, month, ...) create a new date object with a specified date and time
new Date(year, month, day, hours, minutes, seconds, milliseconds);
// JavaScript store dates as number of milliseconds since January 01, 1970, 00:00:00 UTC
// new Date(milliseconds) creates a new date object as zero time plus milliseconds
new Date(milliseconds);
// new Date(date string) creates a new date object from a date string
new Date(date string);

Date Methods

When a Date object is created, a number of methods allow you to operate on it.

  • toString()

    JavaScript will output dates in full text string format in HTML with the toString() method.

  • toUTCString()

    The toUTCString() method convert a date to a UTC string

  • toDateString()

    The toDateString() method converts a date to a ore readable format.

Date Formats

There are generally 3 types of JavaScript date input formats

  • ISO Date - “2016-06-10”

    The ISO format follows a strict standard in JavaScript. ISO 8601 is the international standard for the representation of date and times. The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format.

    The computed date will be relative to your time zone.

  • Short Date - “06/10/2016”

    In some browsers, months or days with no leading zeroes may produce an error.

  • Long Date - “Jun 10 2016”

    Long dates are most often written with a “MMM DD YYYY” syntax like this.

Time Zone

When setting a date, without specifying the time zone, JavaScript will use the browser’s time zone.

Date Input - Parsing Dates

If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds. Date.parse() returns the number of milliseconds between the date and January 1, 1970.

1
let milliSeconds = Date.parse("Jun 10, 2016");

You can the use the number of milliseconds to convert it to a date object.

Get Date Methods

These methods can be used for getting information from a date object

Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number(1-31)
getHours() Get the hour(0-23)
getMinutes() Get the minute(0-59)
getSeconds() Get the second(0-59)
getMilliseconds() Get the millisecond(0-999)
getTime() Get the time(milliseconds since January 1, 1970)
getDay() Get the weekday as a number(0-6)

Set Date Methods

Set date methods let you set date values for a date object

Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)

Compare Dates

Dates can easily be compared. JavaScript counts months from 0 to 11. January is 0. December is 11.

JavaScript Math Object

The JavaScript Math object allows you to perform mathematical tasks on numbers.

  • Math.round()

    Math.round(x) returns the value of x rounded to its nearest integer

    1
    const result = Math.round(4.1); // result is 4
  • Math.pow()

    Math.pow(x, y) returns the value of x to the power of y.

    1
    const result = Math.pow(2, 10);	// result is 1024
  • Math.sqrt()

    Math.sqrt(x) returns the square root of x

    1
    const result = Math.sqrt(64); // result is 8
  • Math.abs()

    Math.abs(x) returns the absolute values of x

    1
    const result = Math.abs(-1); // result is 1
  • Math.ceil()

    Math.ceil(x) returns the value of x rounded up to its nearest integer

    1
    const result = Math.ceil(4.4); // result is 5
  • Math.floor()

    Math.floor(x) returns the value of x rounded down to its nearest integer.

    1
    const result = Math.floor(4.7); // result is 4
  • Math.sin()

  • Math.cos()

  • Math.min() and Math.max()

    Math.min() and Math.max() can be used to find lowest or highest value in a list of arguments

  • Math.random()

    Math.random() returns a random number between 0 and 1

Math Properties

JavaScript provides 8 mathematical constants that can be accessed with the Math object.

1
2
3
4
5
6
7
8
Math.E 			// returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQET1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns the base 2 logarithm of E
Math.LOG10E // returns the base 10 logarithm of E

All methods and properties can be used without creating a Math object first.

Random

Math.random() returns a random number between 0(inclusive), and 1(exclusive)

1
2
3
4
5
Math.floor(Math.random() * 10);	// returns a random integer from 0 to 9

function getRandomInteger (min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}; // This function returns a random number min(include) to max(excluded)

Booleans

JavaScript has a Boolean data types. It can only take the values true or false.

The Boolean() Function

You ca use the Boolean() function to find out if an expression is true

1
const result = Boolean(-1 > 0);	// result is false

Everything with a “Value” is true. Everything without a “Value” is false.

1
2
3
4
5
6
7
8
9
10
11
12
13
// result is true
Boolean(100);
Boolean(-100);
Boolean("100");
Boolean("false");

// result is false
Boolean(0);
Boolean(-0);
Boolean("");
Boolean(null);
Boolean(false);
Boolean(NaN);

Object can’t be compared.

JavaScript Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false. Comparison operators are used in logical statements to determine equality or difference between variables or values.

Operator Description
== Equal to
=== Equal value and equal type
!= Not equal
!== Not equal value or not equal type
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Logical operators are used to determine the logic between variables or values.

Operator Description
&& and
`
! not

JavaScript also contains a conditionnal operator that assigns a value to a variable based on some condition.

1
variableName = (condition) ? valueX:valueY;

Comparing data of different types may give unexpected results. To secure a proper result, variables should be converted to the proper type before comparison.

JavaScript Bitwise Operators

Operator Name Description
& AND Sets each bit to 1 if both bits are 1
` ` OR
^ XOR Sets each bit to 1 only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shifts left by pushing zeros in from the right and let the leftmost bits fall of
>> Signed right shift Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
>>> Zero fill right shift Shifts right by pushing zeros in from the left, and let the rightmost bits fall off

JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers. After the bitwise operation is performed, the result is converted back to 64 bits JavaScript numbers.

JavaScript Regular Expressions

A regular expression is a sequence of characters that forms a search pattern. The serarch pattern can be used for text search and tet replace operations.

A regular expression ban be a single character, or more complicated pattern. Regular expression can be used to perform all types of text search and text replace operations.

1
/pattern/modifiers;

Using string methods

In JavaScript, regular expressions are often used with the two string methods: search() and replace(). The search() method uses an expression to search for match, and returns the position of the match. The replace() method returns a modified string where the pattern is replaced.

1
2
3
4
let originStr = "Hello JavaScript!";
let searchResult = originStr.search("Hello"); // reulst is 0
let replaceResult = originStr.replace("Hi", "Hello"); // result is Hi JavaScript!
repalceResult = originStr.replace(/hi/i, "Visit"); // result is Visit JavaScript!

Regular Expression Modifiers

Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multiline matching

Regular Expression Patterns

Brackets are used to find a range of characters

Expression Description
[a-zA-Z] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
[x|y] Find any of the alternatives separated with `

Metacharacters are characters with a special meaning

Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning or at the end of a word
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers define quantities

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zeor or one occurrences of n

Using test()

The test() method is a RegExp expression method. It searches a string for a pattern, and returns true or false, depending on the result.

1
2
let pattern = /e/;
pattern.test("The best things in life are free!"); // return true

Using exec()

The exec() method is a RegExp expression method. It searches a string for a specified pattern, and returns the found text. If no match is found, it returns null.

1
/e/.exec("The best things in life are free!");	// return e

JavaScript Errors

The try statments lets you test a block of code for errors. The catch statments lets you handle the error. The throw statments lets you create custom errors. The finally statment lets you execute code, after try and catch, regardless of the result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try {
// Block of code to try
} catch (err) {
// Block of code to handle errors
}

try {
throw 'error'; // you can throw a exception
} catch (err) {
// Block of code to handle errors
}

try {
// Block of code to try
} catch () {
// Block of code to handle errors
} finally {
// Block of code to be executed regardless of the try/catch result
}

Ther Error Object

JavaScript has built in error object that provides error information when an error occurs. The error object provides two useful properties: name and message.

Property Description
name Sets or returns an error name
message Sets or returns an error message

Error Name Values

Error Name Description
EvalError An error has occurred in the eval() function.(Newer versions of JavaScript does not throw an EvalError. Use SyntaxError instead.)
RangeError A number “out of range” has occurred
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
URIError An error in encodeURI() has occurred

JavaScript Debugging

Debuggin is not easy. But fortunately, all modern browsers have a built-in JavaScript devugger. Built-in debugger can be turned on and off, forcing errors to be reported to the user.

The console.log() Method

If your browsers supports debugging, you can use console.log() to display JavaScript values in the debugger window.

1
2
3
<script>
console.log(value);
</script>

Setting Breakpoints

In the debugger window, you can set breakpoints in the JavaScript code. At each breakpoint, JavaScript will stop execution, and let you examine JavaScript values. After examining values, you can resume the execution of code.

The debugger Keyword

The debugger keyword stops the execution of JavaScript, and calls (if available) the debugging function.

1
2
3
let x = 0;
debugger;
document.getElementById("ele_id").innerHTML = x;

JavaScript Hoisting

Hoisting is JavaScript’s default behavior of moving declarations to the top. In JavaScript, a variable can be declared after it has been used. In others words, a variable can be used before it has been declared.

1
2
3
numberX = 5;
numberX += 10;
let numberX;

To understand this, you have to understand the term ‘hoisting’. Hoisting is JavaScript’s default behavior of moving all declarations to the top of current scope.

Beware, JavaScript only hoists declarations, not initializations.

Declare your variables at the top

Hoisting is an unknown or overlooked behavior of JavaScript. If a developer doesn’t understand hoisting, programs may contain bugs or errors. To avoid bugs, always declare all variables at the beginning of every scope. Since this is how JavaScript interprets the code, it is always a good rule.

JavaScript in strict mode does not allow variables to be used if they are not decalred.

JavaScript Use Strict

use strict; Defines that JavaScript code should be executed in ‘strict mode’.

The use strict directive was new in ECMAScript version 5. It is not a statment, but a literal expression, ignored by eraily version of JavaScript. The purpose of use strict is to indicate that the code should be executed in ‘strict mode’. With strict mode, you can not, for example, use undeclared variables.

You can use strict mdoe in all your programs. It helps you to write cleaner code, like preventing you from using undeclared variables.

Declaring Strict Mode

Strict mode is decalred by adding "use strict"; to the beginning of a script or a function.

Declared at beginning of a script, it has global scope.

1
2
3
4
<script>
"use strict";
// your JavaScript code
</script>

Declared inside a function, it has local scope

1
2
3
4
5
6
7
numberX = 3.14;	// this will not cause an error
testFunction();

function testFunction () {
"use strict";
numberY = 3.14; // this will cause an error
}

Why Strict Mode

Strict mdoe makes it easier to write “secure” JavaScript. Strict mode changes previously accepted “bad syntax” into real errors.

Not allowed in strict mode

  • Usging a variable/object, without declaring it, is not allowed.
  • Deleting a variable/object/function is not allowed.
  • Duplicating a parameter name is not allowed.
  • Octal numberic literals and octal escape characters are not allowed.
  • Writing to read-only/get-only propery is not allowed.
  • Deleting an undeletable property is not allowed.
  • The string “eval”/“arguments” cannot be used as a variable
  • The with statment is not allowed
  • For security reasons, eval() is not allowed to create variables in the scope from which it was called

The JavaScript this Keyword

In a function definition, this refers to the “owner” of the function.

Default Binding

When used along, this refers to the Global object. In a browser the global object is [object Window].

But in strict mode, this will be undefined, because strict mode does not allow default binding.

JavaScript Style Guide and Coding Conventions

Always use the same coding conventions for all your JavaScript projects.

JavaScript Coding Conventions

Coding conventions are style guidelines for programming. They typically over:

  • Naming and declaration rules for variables and functions.
  • Rules for the use of white space, indentation, and comments.
  • Programming practices and principles.

Coding conventions secure quality:

  • Improve code readability
  • Make code maintenance easier

Coding conventions can be documented rules for teams to follow, or just be your individual coding practice.

JavaScript Best Practices

Avoid global variables, avoid new, avoid ==, avoid eval()

Avoid Global Variables

Minimize the use of global variables. This inclueds all data types, objects, and functions. Global variables and functions can be overwritten by other scripts. Use local variables instead, and learn how to use closures.

Always Declare Local Variables

All variables used in a function should be declared as local variables.

Local variables must be declared with the var/let keyword, otherwise they will become global variables.

Declarations on Top

It is good coding practice to put all declarations at the top of each script or function.

This will:

  • Give cleaner code
  • Provide a single place to look for local variables.
  • Make it easier to avoid unwanted global variables
  • Reduce the possibility of unwanted re-declarations

Initialize Variables

It is good coding practice to initialize variables when you declare them.

Never Declare Number, String, or Boolean Objects

Always treat numbers, strings, or boolean as primitive values. Not as objects.

Declare these types as objects, slow down execution speed, and produces nasty side effects.

Beware of Automatic Type Conversions

Beware that numbers can accidentally be converted to string or NaN. JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type.

Use === Comparison

The == comparison operator always convert before comparison. The === operator forces comparison of values and type.

Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to undefined.

Undefined values can break your code. It is a good habit to assign default values to arguments.

End Your Switches with Defaults

Always end your switch statments with a default. Even if you think there is no need fot it.

Avoid Using eval()

The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it. Because it allows arbitaray code to be run, it also represents a security problem.

JavaScript JSON

JSON is a format for storing and transporting data. JSON is often used when data is sent from a server to a web page.

  • JSON stands for JavaScript Object Notation
  • JSON is lightweight data interchange format
  • JSON is language independent *
  • JSON is “self-describing” and easy to understand

The JSON syntax is derived from JavaScript object notation syntax, but JSON format is text only. Code for reading and generating JSON data can be written in any programming language.

The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.

JSON data is written as name/value pairs, just like JavaScript object properties. A name/value pair consists of a field name, followed by a colon, followed by a value.

JSON names require double quotes, JavaScript names do not.

Converting a JSON Text to a JavaScript Object

A common use of JSON is to read data from a web server, and display the data in web page.

For simplicity, this can be demonstrated using a string as input.

JavaScript Objects

In JavaScript, alomost “everything” is an Object.

JavaScript Primitives

A primitive value is a value that has no properties or methods. A primitive data type is data that has a primitive value.

JavaScript defines 5 types of primitive data types:

  • string
  • number
  • boolean
  • null
  • undefined

Primitive values are immutable (they are hardcoded and therefore cannot be changed)

Objects are Variables containing Variables

JavaScript variables can contain single values. Objects are variables too. But objects can contain many values. The values are written as name : pairs.

1
2
3
4
5
let objectVar = {
key: value,
key: value,
...
}

A JavaScript object is a collection of named values.

Object Properties

The named values, in JavaScript objects, are called properties.

Object properties can be both primitive values, other objects, and functions.

Object Methods

Methods are actions that can be performed on objects.

An Object method is an object property containing a function definition.

JavaScript objects are containers for named values, called properties and mthods.

Creating a JavaScript Object

1
2
3
4
5
6
7
// Create an object using literal
let objectByLiteral = {keyX: "valueX", keyY: "valueY"};

// Create an object using keyword new
let objectByNew = new Object();
objectByNew.keyX = "valueX";
objectByNew.keyY = "valueY";

JavaScript Objects are Mutable

Objects are mutable: They are addressed by reference, not by value.

JavaScript variables are not mutable. Only JavaScript objects.

JavaScript Object Properties

Properties are the most important part of any JavaScript object. Properties are the values associated with a JavaScript object. A JavaScript object is a collection of unorderd properties. Properties can usually be changed, added, and deleted, but some are read only.

Accessing JavaScript Properties

The syntax for accessing the property of an object is :

1
2
3
4
5
objectName.propertyName
// or
objectName["property"]
// or
objectName[expression] // The expression must be evaluate to a property name

JavaScript for…in Loop

The JavaScript for…in statment loops through the properties of an object.

1
2
3
for (variable in object) {
code to be executed
}

The block of code inside of the for…in loop will be executed once for each property.

Add New Properties

You can add new properties to an existing object by simply giving it a value.

You cannot use reserved words for property names. JavaScript naming rules apply.

Deleting Properties

The delete keyword deletes a property from an object.

1
2
let objByLiteral = {keyX: "valueX"};
delete objByLiteral.keyX;

The delete keyword deletes both value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions. The delete operator should not be used on predefined JavaScript object propertis. It can crash your application.

Property Attribute

All properties hava a name. In addition they also have a value. The value is one of the property’s attributes.

Other attributes are: enumerable, configurable, and writable. These attributes define how the property can be accessed.

JavaScript Object Methods

JavaScript methods are actions that can be performed on objects. A JavaScript method is a property containing a function definition.

Methods are functions stored as object properties.

Accessing Object Methods

You access an object method with the following syntax:

1
objectName.methodName();

If you access the method property, without () , it will return the function definition.

Adding a method to an Object

1
2
3
obj.methodName = function () {
code to be executed
}

JavaScript Object Constructors

It is considered good practice to name constructor functions with an upper-case first letter.

In a constructor function this does not have a value. It is a substitute for the new object. The value of this will become the new object whent a new object is created.

Note taht this is not a variable. It is a keyword. You cannot change the value of this.

JavaScript Prototypes

All JavaScript objects inherit properties and methods from a prototype.

Prototype Inheritance

Date objects inherit from Date.prototype. Array objects inherit from Array.prototype. The Object.prototype is on the top of the prototype inheritance chain.

Using the prototype Property

The JavaScript prototype allows you to add new properties to object constructors

1
2
3
4
function Person (value) {
this.key = value;
}
Person.prototype.keyNew = "valueNes";

The JavaScript prototype proterty also allows you to add new methods to objects constructors:

1
2
3
4
5
6
function Person (value) {
this.key = value;
}
Person.prototype.methodNew = function () {
code to be executed
}

Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.

JavaScript Function Definitions

JavaScript functions are defined with the function keyword. You can use a functin declaration or a function expression.

1
2
3
function functionName (parameters) {
code to be executed
}

Declared functions are not executed immediately. They are “saved for later use”, and will be executed later, when they are invoked.

Semicolons are used to separate executable JavaScript statments. Since a function declaration is not an executable statment, it is not common to end it with a semicolon.

Function Expressions

A JavaScript function can also be defined using an expression. A function expression can be stored in a variable.

1
let expressionFun = function (parameters) { execuate code };

After a function expression has been stored in a variable, the variable can be used as a function.

Function stored in variables do not nedd function names. They are always invoked using the variable name.

The Function() Constructor

JavaScript functions are defined with the function keyword.

Functions can also be defined with a built-in JavaScript function consturctor called Function() .

1
let newFunction = new Function("parameterX", "parameterY", ... " execuated code");

You actually don’t have to use the function constructor. Most of time, you can avoid using the new keyword in JavaScript.

Function Hoisting

Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scopt.

Hoisting applies to variable declarations and to function declarations.

Because of this, JavaScript functions can be called before the declared.

Self-Invoking Functions

Function expression can be made “self-invoking”. A “self-invoking” expression is invoked automatically, without being called. Function expression will execute automatically if the expression is followed by ().

You cannot self-invoke a function declaration.

You have to add parentheses around the function to indicate that it is a function expression.

1
2
3
( function () {
executed code
}) ();

Functions Can Be Used as Values

JavaScript functions can be used as values.

1
2
3
4
5
function parameterFun (parameters) {
executed code
}

let result = parameterFun(parameters);

Functions are Objects

The typeof operator in JavaScirpt returns “function” for functions. But, JavaScript functions can best be descripted as objects. JavaScript functions have both properties and methods.

JavaScript Function Parameters

A JavaScript function does not perform any checking on parameter values. Function parameters are the names listed in the function definition. Function arguments are the real values passed to the function.

JavaScript function do not check the number of arguments received.

Parameter Defaults

If a function is called with missing arguments, the missing value are set to undefined . But sometimes it is better to assign a default value to the parameter.

1
2
3
4
5
function arguementsMissingFun (x, y) {
if ( x === undefined ) {
x = 0;
}
}

If a function is called with too many arguments, these arguments can be reached using the arguments object.

The Arguments Object

JavaScirpt functions have a built-in object called the arguments object. The argument object contains an array of the arguments used when the function was called. This way you can simply use a function to find the highest value in a list of numbers.

Arguments are Passed by Value

The parameters, in a function call, are the function’s arguments. JavaScript arguments are passed by value: The function only gets to know the values, not arguments’s locations. If a function changes an argument’s value, it does not change the parameter’s original value. That is, changes to arguments are not visible outside the function.

Objects are Passed by Reference

In JavaScript, object references are values. Because of this, objects will behave like they are passed by reference: If a function changes an object property, it changes the original value. That is, changes to object properties are visible outside the function.

JavaScript Function Invocation

The code inside a function is not executed when the function is defined. The code inside a function is executed when the function is invoked. It is common to use the term “call a function” instead of “invoke a function”. It is also common to say “call upon a function”, “start a function”, or “execute a function”.

1
2
3
4
5
6
function invokeFunction (numX, numY) {
return numX * numY;
}

// Invoking a Function as a Function
invokeFunction(1, 3);

The function above does not belong to any object. But in JavaScript there is always a default global object. In HTML the default object is the HTML page itself, so the function above “belongs” to the HTML page. In a browser the page object is the browser window. The function above automatically becomes a window function.

This is a common way to invoke a JavaScript function, but not a very good practice. Global variables, methods, or function can easily create name conflicts and bugs in the global object.

The this Keyword

In JavaScript, the thing called this, is the object that “owns” the current code. The value of this, when used in a function, is the object that “owns” the function.

Note that this is not a variable. It is a keyword. You cannot change the value of this.

The Global Object

When a function is called without an owner object, the value of this becomes the global object.

In a web browser the global object is the browser window.

Invoking a function as a global function, causes the value of this to be the global object. Using the window object as a variable can easily crash your program.

Invoking a Function as a Method

In JavaScript you can define functions as object methods.

1
2
3
4
5
6
7
8
let aObject = {
propertyX: "valueX",
methodY: function () {
// some execute code
}
}

aObject.methodY();

Invoking a Function with a Function Constructor

If a function invocation is preceded with the new keyword, it is constructor invocation.

1
2
3
4
5
6
7
8
// This is a function constructor
function aFun (argX, argY) {
this.propertyX = argX;
this.propertyY = argY;
}

// This create a new object
let result = new aFun("valueX", "valueY");

A counstructor invocation creates a new object. The new object inherits the properties and methods from its constructor.

The this keyword in the constructor does not have a value. The value of this will be the new object created when the function is invoked.

JavaScript Function Call

With the call() method, you can write a method that can be used on different objects.

In JavaScript all functions are object methods. If a function is not a method of a JavaScript object, it is a function of the global object.

The JavaScript call() Method

The call() method is a predefined JavaScript method. It can be used to invoke a method with an owner object as argument.

With call(), an object can use a method belonging to another object.

JavaScript Function Apply

With the apply() method, you can write a method that can be used on different objects. The apply() method is similar to the call() method.

The difference Between call() and apply() :

  • The call() method takes arguments separately.
  • The apply() method takes arguments as an array.

The apply() method is very handy if you want to use an array instead of an argument list.

The apply() method accepts arguments in an array.

JavaScript Function Closures

Global variables live as long as your application lives. Local variables have shourt lives. They are created when the function is invoked, and deleted when the function is finished.

All functions have access to the global scope. In fact, in JavaScript, all functions have access to the scope “above” them. JavaScript supports nested functions. Nested functions have access to the scope “above” them.

JavaScript closures make it possible for a function to have “private” variables.

A closures is a function having access to the parent scope, even after the parent function has closed.

JavaScript HTML DOM

With the HTML DOM, JavaScript can access and change all the elements of an HTML document.

When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects.

With the object model, JavaScript gets all the power it needs to create dynamic HTML :

  • JavaScript can change all the HTML elements in the page
  • JavaScript can change all the HTML attributes in the page
  • JavaScript can change all the CSS styles in the page
  • JavaScript can remove existing HTML elements and attributes
  • JavaScript can add new HTML elements and attributes
  • JavaScript can react to all existing HTML events in the page
  • JavaScript can create new HTML events in the page

The DOM is W3C standard and it defines a standard for accessing documents:

The W3C Document Object Model is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.

The W3C DOM standard is separated into 3 different parts:

  • Core DOM - standard model for all document types
  • XML DOM - standard model for XML documents
  • HTML DOM - standard model for HTML documents

The HTML DOM is a standard object model and programming interface for HTML. It defines :

  • The HTML elements as objects
  • The properties of all HTML elements
  • The mehtods to access all HTML elements
  • The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

JavaScript HTML DOM Methods

HTML DOM methods are you can perform on HTML elements. HTML DOM properties are values of HTML elements that you can set or change.

The HTML DOM can be accessed with JavaScript. In the DOM, all HTML elements are defined as objects.

The getElementById() method

The most common way to access an HTML element is to use the id of the element.

1
document.getElementById("demo").innerHTML = "Hello DOM!";

The innerHTML Property

The easiest way to get the content of an element is by using the innerHTML property.

The innerHTML property can be used to get or change any HTML element, including and .

JavaScript HTML DOM Document

The HTML DOM document object is the owner of all other objects in your web page.

Finding HTML Elements

Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements

Method Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.setAttribute(attribute, value) Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element

Adding and Deleting Elements

Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
document.write(text) Write into the HTML output stream

Adding Events Handlers

Method Description
document.getElementById(id).onclick() = function () {code} Add event handler code to an onclick event

Finding HTML Objects

Property Description
document.anchors Return all elements that have a name attribute
document.applets Return all elements (Deprecated in HTML 5)
document.baseURI Return the absolute base URI of the document
document.body Return the element
document.cookie Return the document’s cookie
document.doctype Return the document’s doctype
document.documnetElement Return the element
document.documentMode Return the mode used by the browser
document.documentURL Return the URI of the document
document.domain Return the domain name of the document server
document.domConfig Obsolete. Return the DOM configuration
document.embeds Return all elements
document.forms Return all
elements
document.head Return the element
document.images Return all elements
document.implementation Return the DOM implementation
document.inputEncoding Return the document’s encoding
document.lastModified Return the data and time the document was updated
document.links Return all and elements that have a href attribute
document.readyState Return the status of the document
document.referrer Return the URI of the referrer (the linking document)
document.scripts Return all

© 2022 Y2hlbmdsZWk=  Powered by Hexo & Icarus