JS Essentials



JavaScript and Java are completely different languages, both in concept and design.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.

Hight level, interpreted programming Language.
Conforms to the ECMAScript Specification
Mutli-paradigm - can write in many ways (object oriented, Funtion,...)
Runs on the clinent/browser as well as on the server (Node.js)
Build very interactive user interfaces with frameworks like React

What is JavaScript Used For?
- Adding interactivity to websites
- Developing mobile applications (React Native, NativeScript, Ionic)
- Creating web browser based games
- Back end web development
- Desktop application development (electron JS)


1. Introduction

1.1 The <script> Tag

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.


1.2 Javascript Function

A JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called).

Original content


1.3 External Javascript

Scripts can also be placed in external files:
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

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

Original content


1.4 External References

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

Original content


2. JavaScript Output

JavaScript can "display" data in different ways:

Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().


2.1 Using innerHTML



2.2 Using document.write()





2.3 Using window.alert()

You can use an alert box to display data.





2.4 Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display data.
console.error(" ") console.warn(" ")


2.5 JavaScript Print

JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser to print the content of the current window.






3. JavaScript Statements

3.1 JavaScript Programs

A JavaScript program is a list of programming statements.
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
The statements are executed, one by one, in the same order as they are written.

Breaking Long Code Lines

If a JavaScript statement does not fit on one line, the best place to break it is after an operator.
Breakup text string with a single baskslash.
A safer way to break up a string, is to use string addition.

Guidelines:

- Semicolons separate JavaScript statements.
- Ending statements with semicolon is not required, but highly recommended.
- When separated by semicolons, multiple statements on one line are allowed.
- JavaScript ignores multiple spaces.
- A good practice is to put spaces around operators ( = + - * / )
- For best readability, programmers often like to avoid code lines longer than 80 characters.


3.2 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.


3.3 JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

Keywords Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
for Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
var Declares a variable

4.JavaScript Syntax

var x, y, z; // How to declare variables
x = 5; y = 6; // How to assign values
z = x + y; // How to compute values

The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
Strings are written inside double or single quotes. Numbers are written without quotes.

4.1 Variables

An equal sign is used to assign values to variables.
You can declare many variables in one statement.
Strings are written inside double or single quotes. Numbers are written without quotes.
It's 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 re-declare a JavaScript variable, it will not lose its value.


var let con

var const let
Global Scope Yes No No
Function Scope Yes Yes Yes
Block Scope No Yes Yes
Reassign Yes No Yes
Redeclared Yes No No
Need initializer No Yes No
Refer before declaration Yes No No

var let score = 30;
score = 31;

const name; ERROR const name = 'Tom';
const = 'Jim'; ERROR

Global Scope, Local Scope, Function Scope, Block Scope

Global Scope

The area outside all the functions is consider the global scope and the variables defined inside the global scope can be accessed and altered in any other scopes.

Local Scope

Variables declared inside the functions become Local to the function and are considered in the corresponding local scope.
Local scope can be divided into function scope and block scope.

Function Scope

Whenever you declare a variable in a function, the variable is visible only within the function. You can't access it outside the function.

Block Scope

A block scope is the area within if, switch conditions or for and while loops. {curly brackets}
const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block.

4.2 Operators

Arithmetic operators ( + - * / ) to compute values.
The "equal to" operator is written like == in JavaScript.
Operator Precedence: Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).


4.2.1 JavaScript Arithmetic Operators

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
= x = y

4.2.2 JavaScript Assignment Operators

Operator Example
+= x += y, x = x + y
-= x -= y, x = x - y
*= x *= y, x = x * y
/= x /= y, x = x / y
%= x %= y, x = x % y
**= x **= y, x = x ** y

4.2.3 JavaScript Comparison Operators

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
? ternary operator
? : Condition ? "Yes" : "No"

4.2.4 JavaScript Logical Operators

Operator Description
&& logical and
|| logical or
! logical not

4.2.5 JavaScript Type Operators

Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type

4.2.6 JavaScript Operator Precedence Values

Operator Description Example
( ) Expression grouping (3 + 4)
. Member person.name
[] Member person["name"]
() Function call myFunction()
new Create new Date()
<< Shift left x << 2
>> Shift right x >> 2
in Property in Object "PI" in Math
instanceof Instance of Object instanceof Array

4.3 Expression

An expression is a combination of values, variables, and operators, which computes to a value.
The computation is called an evaluation.
Expressions can also contain variable values
The values can be of various types, such as numbers and strings.


4.4 Comments

Code after double slashes // or between /* and */ is treated as a comment.
Using Comments to Prevent Execution


4.5 Indentifiers

In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
JavaScript is Case Sensitive.
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
All JavaScript variables must be identified with unique names. Reserved words (like JavaScript keywords) cannot be used as names
JavaScript treats underscore as a letter.
Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library.


4.6 Variable name

JavaScript programmers tend to use camel case that starts with a lowercase letter.
Underscore: first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case): FirstName, LastName, MasterCard, InterCity.
Lower Camel Case: firstName, lastName, masterCard, interCity.

4.7 Character Set

JavaScript uses the Unicode character set.


5 Date Types

JavaScript variables can hold many data types: numbers, strings, objects and more.
JavaScript has dynamic types. This means that the same variable can be used to hold different data types.
Undefined and null are equal in value but different in type.
- var length = 16; // Number
- var lastName = "Johnson"; // String
- var x = {firstName:"John", lastName:"Doe"}; // Object

Primitive Data

A single simple data value with no additional properties and methods.

Complex Data

The typeof operator can return one of two complex types: function or object.

typeof


5.1 Numbers

Numbers are written with or without decimals.
Extra large or extra small numbers can be written with scientific (exponential) notation.
JavaScript Numbers are Always 64-bit Floating Point.
Integers (numbers without a period or exponent notation) are accurate up to 15 digits.
The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate.
JavaScript will try to convert strings to numbers in all numeric operations.
NaN is a JavaScript reserved word indicating that a number is not a legal number.
NaN is a number: typeof NaN returns number.
Infinity (or -Infinity) is the value JavaScript will return if a number is outside the largest possible number.
But numbers can also be defined as objects with the keyword new.


5.1.1 Number Methods

Code Description Sample Result
Number.isNaN() To find out if a value is a number var input = 100
input.isNaN()
True
Number.toString() To convert to number to string var input = 123;
input.toString();
"123"
Number.toString(base) To convert to specified base var input = 32;
input.toString(32);
10
Number.toExponential() Return a string with a number rounded and written using exponential notation. var input = 9.656;
input.toExponential(2);
9.66e+0
Number.toFixed() Return a string with the number written with a specified number of decimals. var input = 9.1543;
input.toFixed(2);
9.15
Number.toPrecision() Return a string with a number written with a specified length. var input = 9.1543;
input.toPrecision(2);
9.2
Number.valueOf() Return a number as a number. var input = 123;
input.valueOf();
123
Number.Number() Convert variables to numbers. Number(true);
Number("10");
Number("10.33");
Number("John");
1
10
10.33
NaN
Number.Number() Convert date to numbers.(number of milliseconds since 1.1.1970) Number(new Date("2017-09-30")); 1506729600000
Number.parseInt() Returns a whole number parseInt("10.33");
parseInt("10 20 30");
parseInt("years 10");
10
10
NaN
Number.parseFloat() Returns a number parseFloat("10.33");
parseFloat("10 20 30");
parseFloat("years 10");
10
10
NaN
Number.MIN_VALUE Returns the smallest possible number in JavaScript. var x = Number.MIN_VALUE; 5e-324
Number.MAX_VALUE Returns the smallest possible number in JavaScript. var x = Number.MIN_VALUE; 5e-324

5.2 Strings

Strings are text, written within double or single quotes.
You can also add strings, but strings will be concatenated:.
Strings are written inside double or single quotes. Numbers are written without quotes.


String with varibale

There are two way to show string with variable.
1. Use + between string and variable
2. Use Template Strings in `backticks ${variable}`

5.2.1 String Length

To find the length of a string, use the built-in length property:

5.2.2 Escape Character

The backslash (\) escape character turns special characters into string characters:

Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator

5.2.3 Finding a String in a String

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string.
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string.
Both indexOf(), and lastIndexOf() return -1 if the text is not found.
The search() method searches a string for a specified value and returns the position of the match.
The search() method cannot take a second start position argument.
The indexOf() method cannot take powerful search values (regular expressions).

5.2.4 Extracting String Parts

There are 3 methods for extracting a part of a string:
slice(start, end)
slice() extracts a part of a string and returns the extracted part in a new string.
If a parameter is negative, the position is counted from the end of the string.
If you omit the second parameter, the method will slice out the rest of the string.

substring(start, end)
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
If you omit the second parameter, the method will slice out the rest of the string

substr(start, length)
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
If you omit the second parameter, substr() will slice out the rest of the string.


5.2.5 String Methods

Code Description Sample Result
String.concat(string) Join String var input1 = "Hello"
var input2 = "World!"
input1.concat(" ", input2)
Hello World!
String.toLowerCase() Converting to Lower Case var input = "one Two THREE"
input.toLowerCase()
one two three
String.toUpperCase() Converting to Upper Case var input = "one Two THREE"
input.toUpperCase()
ONE TWO THREE
String.trim() Removed whitespace var input = " Hello World! "
input.trim()
Hello World!
String.charAt() Return the character at a specified index in a string var input = "Hello World!"
input.charAt(0)
H
String.charCodeAt(index) Return the unicode of the character at a specified index in a string var input = "Hello World!"
input.charAt(0)
72
String[index] Property Access
If no character is found, [ ] returns undefined
It is read only. str[0] = "A" (do not assign)
var input = "Hello World!"
input[0]
H
String.split(charactor) Converting a String to an Array var input = "a, b, c, d"
var output = input.split(",")
output[1]
b

5.3 Booleans

Booleans can only have two values: true or false.


Boolean Values

JavaScript has a Boolean data type. It can only take the values true or false.
Code Description Sample Result
Boolean() to find out if an expression (or a variable) is true Boolean(10 > 9);
(10 > 9);
10 > 9;
true
true
true
comparison operators to take the values true or false Boolean(100);
Boolean(3.14);
Boolean(-15);
Boolean("Hello");
Boolean('false');
true
true
true
true
true

5.4 Arrays

JavaScript arrays are written with square brackets and items are separated by commas.
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
An array is a special variable, which can hold more than one value at a time.
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.


5.4.1 for Loop Array Elements

for (iterator; condition; increment) {action}


5.4.1 for of Array Elements

for (object of object) {action}

5.4.2 forEach Loop Array Elements

Array.forEach (function)


5.4.3 Array Random order

Fisher Yates shuffle


5.4.4 Array Iteration

5.4.4.1 Array.forEach(function)

Perform a function on each array element.



5.4.4.2 Array.map(function)

Create a new array by performing a function on each array element.



5.4.4.3 Array.filter(function)

Create a new array with array elements that passes a test.



5.4.4.4 Array.reduce(function)

Run a function on each array element to produce a single value. (left-to-right)



5.4.4.5 Array.reduceRight(function)

Run a function on each array element to produce a single value. (right-to-left)



5.4.4.6 Array.every(function)

Check if all array values pass a test.



5.4.4.7 Array.some(function)

Check if some array values pass a test.



5.4.4.8 Array.indexOf()

Search an array for an element value and returns its position.
Array.indexOf() returns -1 if the item is not found.



5.4.4.9 Array.lastIndexOf()

Search an array for an element value and returns last position.
Array.lastIndexOf() returns -1 if the item is not found.



5.4.4.10 Array.find(function)

Return the value of the first array element that passes a test function.



5.4.4.11 Array.findIndex(function)

Return the index of the first array element that passes a test function.



5.4.5 Array Methods

Code Description Sample Result
Array.push() Add a new element to an array at last const input = ["item1", "item2"];
input.push("item3");
item1, item2, item3
Array[Array.length] = "item" Add a new element to an array const input = ["item1", "item2"];
input[input.length] = "item3";
["item1", "item2", "item3"]
Array.unshift() Add a new element to an array at the beginning const input = ["item1", "item2"];
input.unshift("item3");
item3, item1, item2
Array.pop() Remove the last element from an array const input = ["item1", "item2"];
input.pop();
item1, item2
Array.shift() Remove the first element from an array const input = ["item1", "item2"];
input.shift();
item2, item3
Array[index] = item Change element in an array const input = ["item1", "item2"];
input[1] = "newItem";
item1, newItem
Array.splice() Add new items to an array
parameter1: position to add
parameter2: no. of elements to removed.
The rest parameters: new elements
const input = ["item1", "item2"];
input.splice(2, 0, "newItem1", "newItem2");
item1, newItem1, newItem2
Array.isArray() Return true if the argument is an array. const input = ["item1", "item2"];
Array.isArray(input);
true
Array instanceof Array Return true if the argument is an array. const input = ["item1", "item2"];
input instanceof Array;
true
Array.toString() Convert an array to a string of (comma separated) array values const input = ["item1", "item2"];
input.toString();
item1,item2
Array.join() Join all array elements into a string const input = ["item1", "item2"];
input.join(" - ");
item1 - item2
Array.concat() Create a new array by merging existing arrays const input1 = ["item1", "item2"];
const input2 = ["item3", "item4"];
output = input1.concat(input2);
item1,item2,item3,item4
Array.slice() Slice out a piece of an array into a new array
parameter1: start element
parameter2: end element
const input1 = ["item1", "item2", "item3", "item4"];
output = input1.slice(1, 3);
item2,item3
Array.sort() Sort an array alphabetically.
const input1 = ["b", "a", "c"];
const input2 = [3, 1, 2];
input1.sort();
input2.sort();
a,b,c
1,2,3
Array.reverse() Reverse the elements in an array.
conts input = ["a", "b", "c"];
output = input.reverse();
c,b,a
Math.max() Find the highest number in an array.
conts input = [3, 5, 4];
myArrayMax(input);
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}
5

5.5 Objects

JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by commas.
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.

Objects, Properties, and Methods

You define (and create) a JavaScript object with an object literal.
The name:values pairs in JavaScript objects are called properties.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.


Accessing JavaScript Properties

The syntax for accessing the property of an object is:

objectName.property // person.age
objectName["property"] // person["age"]
objectName[expression] // x = "age"; person[x]

Adding New Properties

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

person.nationality = "English";

Deleting Properties

The delete keyword deletes a property from an object.
The delete operator should not be used on predefined JavaScript object properties. It can crash your application.

delete person.age; // or delete person["age"];

Object Methods

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

Accessing Object Methods

objectName.methodName()

Using Built-In Methods

const variable = object.toUpperCase();

Adding a Method to an Object

Display JavaScript Objects

Displaying the Object Properties by name

Displaying the Object Properties in a Loop

Displaying the Object using Object.values()

Displaying the Object using JSON.stringify()

JSON.stringify will not stringify functions.

Using get, set, defineProperty

Benetits - Simpler syntax
- Syntax for properties and methods
- Secure better data quality
- To do things behind-the-scenes

get

set

defineProperty

5.6 Date Obeject

By default, JavaScript will use the browser's time zone and display a date as a full text string.
Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date()
One and two digit years will be interpreted as 19xx
Date(milliseconds)
01 January 1970 plus x milliseconds

5.6.1 Date Formats

There are generally 3 types of JavaScript date input formats.
  • ISO Date "2015-03-25" (The International Standard)
  • Short Date "03/25/2015"
  • Long Date "Mar 25 2015" or "25 Mar 2015"

  • Parsing Dates
    Date.parse() method to convert it to milliseconds.

    5.6.2 Get Date Methods

    Code Description Sample Result
    getFullYear() Get the year as a four digit number (yyyy) var input = new Date();
    input.getFullYear();
    2020
    getMonth() Get the month as a number (0-11) var input = new Date();
    input.getMonth();
    4
    getMonth() Get the month as a number (0-11) var input = new Date();
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    months[input.getMonth]();
    May
    getDate() Get the day as a number (1-31) var input = new Date();
    input.getDate();
    16
    getHours() Get the hour (0-23) var input = new Date();
    input.getHours();
    15
    getMinutes() Get the minute (0-59) var input = new Date();
    input.getMinutes();
    54
    getSeconds() Get the second (0-59) var input = new Date();
    input.getSeconds();
    17
    getMilliseconds() Get the millisecond (0-999) var input = new Date();
    input.getMilliseconds();
    278
    getTime() Get the time (milliseconds since January 1, 1970) var input = new Date();
    input.getTime();
    1589611666674
    getDay() Get the weekday as a number (0-6) var input = new Date();
    input.getDay();
    6
    getDay() Get the weekday as a number (0-6) var input = new Date();
    var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    days[input.getDay()];
    Sat

    UTC Date Methods
    UTC date methods are used for working with UTC dates (Universal Time Zone dates).
    getUTCDate() getUTCDay() getUTCFullYear() getUTCHours() getUTCMilliseconds() getUTCMinutes() getUTCMonth() getUTCSeconds()

    5.6.4 Set Date Methods

    Set Date methods let you set date values (years, months, days, hours, minutes, seconds, milliseconds) for a Date Object.

    Code Description Sample Result
    setFullYear() Set the year (optionally month and day)
    The setFullYear() method can optionally set month and day.
    var input = new Date();
    input.setFullYear(2030);
    input.setFullYear(2030, 11, 3);
    Thu May 16 2030 17:00:27 GMT+0900 (Japan Standard Time)
    Tue Dec 03 2030 17:03:11 GMT+0900 (Japan Standard Time)
    setMonth() Set the month (0-11) var input = new Date();
    input.setMonth(11);
    Wed Dec 16 2020 17:09:54 GMT+0900 (Japan Standard Time)
    setDate() Set the day as a number (1-31) var input = new Date();
    input.setDate(15);
    Fri May 15 2020 17:14:45 GMT+0900 (Japan Standard Time)
    setHours() Set the hour (0-23) var input = new Date();
    input.setHours(22);
    Sat May 16 2020 22:17:16 GMT+0900 (Japan Standard Time)
    setMinutes() Set the minutes (0-59) var input = new Date();
    input.setMinutes(30);
    Sat May 16 2020 17:30:23 GMT+0900 (Japan Standard Time)
    setSeconds() Set the seconds (0-59) var input = new Date();
    input.setSeconds(30);
    Sat May 16 2020 17:19:30 GMT+0900 (Japan Standard Time)

    5.7.1 Math Properties (Constants)

    Mathematical constants that can be accessed with the Math object
    Code Description Sample Result
    Math.E returns Euler's number Math.E; 2.718281828459045
    Math.PI returns PI Math.PI; 3.141592653589793
    Math.SQRT2 returns the square root of 2 Math.SQRT2; 1.4142135623730951
    Math.SQRT1_2 returns the square root of 1/2 Math.SQRT1_2; 0.7071067811865476
    Math.LN2 returns the natural logarithm of 2 Math.LN2; 0.6931471805599453
    Math.LN10 returns the natural logarithm of 10 Math.LN2; 2.302585092994046
    Math.LOG2E returns base 2 logarithm of E Math.LOG2E; 1.4426950408889634
    Math.LOG10E returns base 10 logarithm of E Math.LOG10E; 0.4342944819032518

    5.7.2 Math Constructor

    Unlike other global objects, the Math object has no constructor. Methods and properties are static.
    All methods and properties (constants) can be used without creating a Math object first.

  • abs(x) Returns the absolute value of x
  • acos(x) Returns the arccosine of x, in radians
  • acosh(x) Returns the hyperbolic arccosine of x
  • asin(x) Returns the arcsine of x, in radians
  • asinh(x) Returns the hyperbolic arcsine of x
  • atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
  • atan2(y, x) Returns the arctangent of the quotient of its arguments
  • atanh(x) Returns the hyperbolic arctangent of x
  • cbrt(x) Returns the cubic root of x
  • ceil(x) Returns x, rounded upwards to the nearest integer
  • cos(x) Returns the cosine of x (x is in radians)
  • cosh(x) Returns the hyperbolic cosine of x
  • exp(x) Returns the value of Ex
  • floor(x) Returns x, rounded downwards to the nearest integer
  • log(x) Returns the natural logarithm (base E) of x
  • max(x, y, z, ..., n) Returns the number with the highest value
  • min(x, y, z, ..., n) Returns the number with the lowest value
  • pow(x, y) Returns the value of x to the power of y
  • random() Returns a random number between 0 and 1
  • round(x) Rounds x to the nearest integer
  • sin(x) Returns the sine of x (x is in radians)
  • sinh(x) Returns the hyperbolic sine of x
  • sqrt(x) Returns the square root of x
  • tan(x) Returns the tangent of an angle
  • tanh(x) Returns the hyperbolic tangent of a number
  • trunc(x) Returns the integer part of a number (x)
  • 6 Functions

    A JavaScript function is a block of code designed to perform a particular task.
    A JavaScript function is executed when "something" invokes it (calls it).
    A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
    Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
    The parentheses may include parameter names separated by commas:(parameter1, parameter2, ...)
    The code to be executed, by the function, is placed inside curly brackets: {}
    Inside the function, the arguments (the parameters) behave as local variables.
    You can reuse code: Define the code once, and use it many times.
    JavaScript functions can be called before they are declared.

    function functionName(parameter1, parameter2, parameter3) {
    // code to be executed
    }

    Function Invocation

    When an event occurs (when a user clicks a button)
    When it is invoked (called) from JavaScript code
    Automatically (self invoked)

    Anonymouse Function

    Function without a name

    anonymous function

    (function () { console.log('Hallo') });

    self invoked anonymous function

    (function () { console.log('Hallo') })();

    self invoked anonymous function with a parameter called "$"

    var jQuery = 'I\'m not jQuery.';
    (function ($) { console.log($) })(jQuery);

    Function Constructor

    Functions can also be defined with a built-in JavaScript function constructor.

    Self-Invoking Functions

    Function expressions can be made "self-invoking".

    Arrow Function

    Arrow functions allow us to write shorter function syntax:
    Arrow functions were introduced in ES6.

    Arrow function with one statement dont need return.

    Arrow function with forEach

    Constructor function

    Objects of the same type are created by calling the constructor function with the new keyword.
    Good practice to name constructor functions with an upper-case first letter.
    It is return function when run individual varibale. (Need to use prototypes)
    You can not add a new property to an existing object constructor

    Prototypes

    All JavaScript objects inherit properties and methods from a prototype.
    Array objects inherit from Array.prototype.
    The Object.prototype is on the top of the prototype inheritance chain.
    Prototype property allows you to add new properties to object constructors.

    Class Function

    Call()

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

    Apply()

    The apply() method is similar to the call() method.

    The apply() method takes arguments as an array.

    7. LOOP

    For Loop

    for (iterator; condition; increment) {action}


    For in

    for(let item in list) {function;}

    While Loop

    while (condition){action;, increment;}

    Conditions

    Conditional statements are used to perform different actions based on different conditions.
    Use if to specify a block of code to be executed, if a specified condition is true
    Use else to specify a block of code to be executed, if the same condition is false
    Use else if to specify a new condition to test, if the first condition is false
    Use switch to specify many alternative blocks of code to be executed

    The if Statement

    if(condition) {function}


    The if else Statement

    if(condition) {function} else {function}

    The if else if else Statement

    if(condition) {function} else if() {function} else {function}

    Switch statement

    Use the switch statement to select one of many code blocks to be executed.
    Switch(expression) { case a: code_block break; case b: code_block break; default: code_block}

    Ternary Operator

    A conditional operator that assigns a value to a variable based on some condition.

    8 Events

    HTML events are "things" that happen to HTML elements.
    When JavaScript is used in HTML pages, JavaScript can "react" on these events.
    Here are some examples of HTML events:
    - An HTML web page has finished loading
    - An HTML input field was changed
    - An HTML button was clicked

    Event

    Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
    page loads
    page is closed
    clicks a button
    inputs data And more ...

    Even Methods

    HTML event attributes can execute JavaScript code directly
    HTML event attributes can call JavaScript functions
    You can assign your own event handler functions to HTML elements
    You can prevent events from being sent or being handled
    And more ...

    Common HTML Events

    Event Description
    onchange An HTML element has been changed
    onclick The user clicks an HTML element
    onmouseover The user moves the mouse over an HTML element
    onmouseout The user moves the mouse away from an HTML element
    onkeydown The user pushes a keyboard key
    onload The browser has finished loading the page

    8.1 onclick event

    Content


    8.2 onclick this




    8.3 onmouseover | onmouseout event

    Content


    8.4 onkeydown event

    Press a key inside the text field to set a lightgray background color.



    In HTML:



    In JavaScript:

    9 DOM

    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.
    To change, remove, add, all HTML elements, attributes, sytles, events in the page.
    Core DOM - standard model for all document types
    XML DOM - standard model for XML documents
    HTML DOM - standard model for HTML documents
    A property is a value that you can get or set
    A method is an action you can do

    getElement

    Methods HTML JS Result
    document.getElementById(id) <p id="p01"> </p> document.getElementById("p01").innerHTML = "Hello!"; Hello!
    document.getElementsByClassName(name) <p class="book"> </p>
    bookElement = document.getElementsByClassName("book");
    console.log(bookElement);
    HTMLCollection [p.book]
    document.getElementsByTagName(name) <h1> Title </h1>
    document.getElementsByTagName("H1")[0].innerHTML = "New title"; New title
    document.querySelector(#id) <p id="p01"> Title </p>
    document.querySelector("#p01").innerHTML = "New title"; New title
    document.querySelector(.class) <p class="book"> Title </p> document.querySelector(".book").innerHTML = "New title"; New title
    document.querySelector("a[attribute]") <a href="http://www.disney.com" target="_blank">disney.com</a> document.querySelector("a[target]").style.backgroundColor = "lightyellow"; disney.com
    document.querySelectorAll("tag") <p>Content1</p>
    <p>Content2</p>
    const allP = document.querySelectorAll("p");
    allP[1].style.backgroundColor = "lightyellow";

    Content1

    Content2

    document.querySelectorAll("tag") <p>Content1</p>
    <p>Content2</p>
    const allP = document.querySelectorAll("p");
    for(i = 0; i < allP.length; i++) {
    allP[i].style.backgroundColor = "lightyellow"; }

    Content1

    Content2

    Change property

    Property HTML JS Result
    element.innerHTML = new html content <p id="p01"> </p> document.getElementById("p01").innerHTML = "Hello!"; Hello!
    element.attribute.name <p id="p01">content1</p> const x = document.getElementById("p01").attributes[0].name;
    console.log(x)
    id
    element.attribute.length <p id="p01" class="c01">content1</p> const x = document.getElementById("p01").attributes.length;
    console.log(x)
    2
    element.style.backgroundColor = "color" <p id="p01">Content1</p> const e = document.getElementById("p01");
    e.style.backgroundColor = "lightyellow";

    Content1

    11. Examples

    11.1 Change HTML Content

    Content


    11.2 Change HTML Attribute Value





    11.3 Change HTML Styles

    Content


    11.4 Hide HTML Elements

    Content


    11.5 Random Number in range

    Min Value: Max Value:

    Random Number


    11.6 Random Condition Result

    Player1

    Player2

    Result

    11.7 Greeting

    Greeing

    Time

    11.8 Get Rewards based on Rank (Stacked)

    My Stock

    11.9 Calculator

    JS Calculator

    11.10 Sorting Object Arrays