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)
Original content
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
External scripts can be referenced with a full URL or with a path relative to the current web page.
Original content
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().
You can use an alert box to display data.
For debugging purposes, you can call the console.log() method in the browser to display data.
console.error(" ") console.warn(" ")
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.
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 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 |
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.
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 | 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
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.
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.
Whenever you declare a variable in a function, the variable is visible only within the function. You can't access it outside the function.
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.
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 |
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.
Code after double slashes // or between /* and */ is treated as a comment.
Using Comments to Prevent Execution
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.
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.
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
A single simple data value with no additional properties and methods.
The typeof operator can return one of two complex types: function or object.
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.
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 |
There are two way to show string with variable.
1. Use + between string and variable
2. Use Template Strings in `backticks ${variable}`
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 |
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 |
Booleans can only have two 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 |
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.
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 |
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.
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.
The syntax for accessing the property of an object is:
objectName.property // person.age
objectName["property"] // person["age"]
objectName[expression] // x = "age"; person[x]
You can add new properties to an existing object by simply giving it a value.
person.nationality = "English";
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"];
In a function definition, this refers to the "owner" of the function.
objectName.methodName()
const variable = object.toUpperCase();
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.
Benetits
- Simpler syntax
- Syntax for properties and methods
- Secure better data quality
- To do things behind-the-scenes
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 |
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) |
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 |
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
}
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
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);
Functions can also be defined with a built-in JavaScript function constructor.
Function expressions can be made "self-invoking".
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
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
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.
With call(), an object can use a method belonging to another object.
The apply() method is similar to the call() method.
The apply() method takes arguments as an array.
for (iterator; condition; increment) {action}
for(let item in list) {function;}
while (condition){action;, increment;}
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
if(condition) {function}
if(condition) {function} else {function}
if(condition) {function} else if() {function} else {function}
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}
A conditional operator that assigns a value to a variable based on some condition.
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 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 ...
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 ...
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 |
Content
Content
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
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");
|
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>
|
const allP = document.querySelectorAll("p");
|
Content1 Content2 |
document.querySelectorAll("tag") |
<p>Content1</p>
|
const allP = document.querySelectorAll("p");
|
Content1 Content2 |
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;
|
id |
element.attribute.length |
<p id="p01" class="c01">content1</p>
|
const x = document.getElementById("p01").attributes.length;
|
2 |
element.style.backgroundColor = "color" |
<p id="p01">Content1</p>
|
const e = document.getElementById("p01");
|
Content1 |
Content
Content
Content
Random Number
Player1
Player2
Result
Greeing
Time
My Stock
JS Calculator