Javascript
-JavaScript defines the behaviour of your website
-JavaScript is known as a client side language because it runs in the client's web browser.
-A JavaScript file is a text file with a .js file extension

JavaScript can be included/used in an html file in 3 ways:

JavaScript Example:

Example html doc with JavaScript

Copy and paste the following in a .html file


JavaScript can "display" data in different ways:

JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":

Example

document.getElementById("demo").innerHTML = "Hello Dolly.";

Semicolons ;

Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

var a, b, c;     // Declare 3 variables
a = 5;           // Assign the value 5 to a
b = 6;           // Assign the value 6 to b
c = a + b;       // Assign the sum of a and b to c

Try it Yourself »

When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;
Try it Yourself »

On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.


variables are used to store data values.

A variable name can begin with a letter, underscore (_), or a dollar sign ($). Subsequent characters may be letters, digits, underscores, or dollar signs. A variable name cannot start with a number and must not contain minus signs (hyphens/dashes) (-)

JavaScript is case-sensitive.

JavaScript uses the var keyword to declare variables.

An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

var x;
x = 6;

Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed.


Arithmetic

Arithmetic operators perform arithmetic on numbers (literals or variables).

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

Data Types

Main (basic) primitive Data types:

string
-text enclosed in single or double qoutes, e.g. "hello"

number
-A number, e.g. 4 , 4.5, -5.5

boolean
-True or false value. In logic statements
False values are: True values are: Boolean() - use this builtin function to check boolean values and expressions e.g. Boolean(5 > 2) returns true

undefined
-A variable without a value is undefined. A variable can also be set to undefined x = undefined

null
-null is used to set an object (a complex data type) to empty. undefined may also be used.

You can use the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator can be used with or without brackets ().

Example:
typeof "John"              // Returns "string"
typeof 3.14                // Returns "number"
typeof(true)               // Returns "boolean"
typeof false               // Returns "boolean"
typeof x                   // Returns "undefined" (if x has no value)

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

Example

var x;           // Now x is undefined
x = 5;           // Now x is a Number
x = "John";      // Now x is a String

JavaScript Strings and useful String methods

A JavaScript string is zero or more characters written inside single (' ') or double (" ") quotes.

var carName1 = "Volvo XC60"; // Double quotes
var carName2 = 'Volvo XC60'; // Single quotes


You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';


To use the same quotes in a string use a backslash (\)

Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash
\n newline character starts text on a new line
\t tab character tabs or indents the text

  var x = "We are \"Vikings\" from the north";


Strings can be concatenated with the addition "+" operator:

alert("hello" + "Bob");

OR

var txt1 = "hello";
var txt2 = "Bob";
alert(txt1 + txt2);

Note that trying to do invalid arithmetic on strings will just produce the value Not a Number - NaN


String methods:

To find how many letters are in a string use the length property:

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
console.log(txt.length); //26


JavaScript Numbers and useful Number methods


Number Method Description Example
Global JavaScript Methods JavaScript - global methods can be used on all JavaScript data types.
Number() Returns a number, converted from its argument.
If the number cannot be converted, NaN (Not a Number) is returned.
Number(true);          // returns 1
Number(false);         // returns 0
Number("10");          // returns 10
Number("  10");        // returns 10
Number("10  ");        // returns 10
Number(" 10  ");       // returns 10
Number("10.33");       // returns 10.33
Number("10,33");       // returns NaN
Number("10 33");       // returns NaN
Number("John");        // returns NaN
parseFloat() Parses its argument and returns a floating point number. parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned. If the number cannot be converted, NaN (Not a Number) is returned.
parseFloat("10");        // returns 10
parseFloat("10.33");     // returns 10.33
parseFloat("10 20 30");  // returns 10
parseFloat("10 years");  // returns 10
parseFloat("years 10");  // returns NaN
parseInt() Parses its argument and returns an integer
parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned. If the number cannot be converted, NaN (Not a Number) is returned.
parseInt("10");         // returns 10
parseInt("10.33");      // returns 10
parseInt("10 20 30");   // returns 10
parseInt("10 years");   // returns 10
parseInt("years 10");   // returns NaN 
Other number methods that you may find useful
isNaN() You can use the global JavaScript function isNaN() to find out if a value is a number
var x = 100 / "Apple";
isNaN(x);  // returns true because x is Not a Number
x can also be assigned NaN
var x = NaN;
isNaN(x);  // returns true because x is Not a Number
Note that typeof(NaN) is a number
toString() The toString() method returns a number as a string.
var x = 123;
x.toString();            // returns 123 from variable x
(123).toString();        // returns 123 from literal 123
(100 + 23).toString();   // returns 123 from expression 100 + 23
Base 10 is default but other bases can be specified:
var myNumber = 32;
myNumber.toString(10);  // returns 32
myNumber.toString(32);  // returns 10
myNumber.toString(16);  // returns 20
myNumber.toString(8);   // returns 40
myNumber.toString(2);   // returns 100000
toExponential() toExponential() returns a string, with a number rounded and written using exponential notation.
An optional parameter defines the number of characters behind the decimal point.
If you don't specify a parameter, JavaScript will not round the number.
var x = 9.656;
x.toExponential(2);     // returns 9.66e+0
x.toExponential(4);     // returns 9.6560e+0
x.toExponential(6);     // returns 9.656000e+0
toFixed() toFixed() returns a string, with the number written with a specified number of decimals
var x = 9.656;
x.toFixed(0);           // returns 10
x.toFixed(2);           // returns 9.66
x.toFixed(4);           // returns 9.6560
x.toFixed(6);           // returns 9.656000
toPrecision() toPrecision() returns a string, with a number written with a specified length
var x = 9.656;
x.toPrecision();        // returns 9.656
x.toPrecision(2);       // returns 9.7
x.toPrecision(4);       // returns 9.656
x.toPrecision(6);       // returns 9.65600

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 (calls it).

To declare a function:

function name(parameter1 = 5, parameter2 = "hello", parameter3) { //optional parameter variables, some with optional initializations
  // code to be executed
  
  arguments.length; //this useful builtin arguments object can be used to find out how many arguments are passed to the function
  arguments[i];    // you can even access each argument in an array
  
  //parameters, and variables declared with the var keyword, are local to the function e.g   var x = "local";
 //variables used without the var keyword are global and are accesible outside the function e.g. x = "global";
  
  return someValue; //optional value can be returned, return can also be used to exit the function.
}

To invoke or call a function:

name(argument1, argument2, argument3); //arguments are optional if the parameter has been initialized in the function definition

The () Operator Invokes the Function

Functions called without the brackets () will return the function object

This is useful for assigning functions to variables.

var x = mult;

x(5,5); //returns 25
mult(5,5); //also returns 25

function mult(a, b) {
  return a * b
};

Anonymous Functions

var x = function (a, b) {return a * b};
var z = x(4, 3); //z is assigned 12

Note the function above is anonymous because it was not declared with a name, only x() can call the function

Self-Invoking Functions

Function expressions can be made "self-invoking".

A self-invoking expression is invoked (started) automatically, without being called.

Function expressions 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:

Example

(function () {
  var x = "Hello!!";  // I will invoke myself
})();

The function above is actually an anonymous self-invoking function (function without name).

Arrow Function

hello = function() {
  return "Hello World!";
}
Same as:
hello = () => {
  return "Hello World!";
}

It gets shorter! If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword:

hello = () => "Hello World!";

Note: This works only if the function has only one statement.

Arrow Function With Parameters:

hello = (val) => "Hello " + val;

In fact, if you have only one parameter, you can skip the parentheses as well:

hello = val => "Hello " + val;

JavaScript Objects

Objects mimic/represent real world objects

Objects are a set of key-value pairs of data that form a kind of description of an object

To declare an object:

var myobject = {key1: "value1", key2: value2,…};

To access value of object:

var x = myobject.key1; //OR 
var x = myobject["key1"];

Objects are Mutable

Note that Objects are Passed by Reference in functions.
This means that if you change the value of the object, you change the object everywhere in the program, unlike local variables

Also if you assign an object to another variable, the variable stores a reference to the object, not a copy.

Note that Arrays are (special) objects, this also applies to arrays

var car = {type:"Fiat", model:"500", color:"white"};
var x = car;
x.color= "blue";
document.write(car.color); //writes blue;

The "this" keyword

The 'this' keyword has different values depending on where it is used.

In a method (a function in an object), this refers to the owner object. E.g:

var person = { 
  firstName: "John",
  fullName : function() { return this.firstName }
};

this refers to the person (owner) object, it can be replaced with person.firstName

Alone, this refers to the global object.

In a function, this refers to the global object.


JavaScript Arrays

Arrays store multiple variables/data values

To use array you declare it:

var myarray = [];   	//OR
var myarray = [item1, item2, ...];

To add more values to array:

myarray[0] = 1;
myarray[1] = 'value 2';
myarray.push(item); //- Adds item to end of array
var x = myarray.pop(); //-Removes item from end of array and returns value
var y = myarray.length; //-Returns array size (number of elements in the array)

Note that array indexes start at zero - (0) and NOT one (1).


JavaScript Events

Common HTML Events

Here is a list of some common HTML events:

Event Description
Events useful for forms
onchange An HTML element has been changed
onblur The event occurs when an element loses focus
onfocus The event occurs when an element gets focus
onfocusin The event occurs when an element is about to get focus
onfocusout The event occurs when an element is about to lose focus
oninput The event occurs when an element gets user input
oninvalid The event occurs when an element is invalid
onsubmit The event occurs when a form is submitted
Mouse Events
onclick The user clicks an HTML element
ondblclick The event occurs when the user double-clicks on an element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onmouseenter The event occurs when the pointer is moved onto an element
onmouseleave The event occurs when the pointer is moved out of an element Difference between mouse enter/leave and mouse over/out events
onmousedown The event occurs when the user presses a mouse button over an element
onmouseup The event occurs when a user releases a mouse button over an element
onmousemove The event occurs when the pointer is moving while it is over an element
onwheel The event occurs when the mouse wheel rolls up or down over an element
Keyboard Events
onkeydown The user pushes a keyboard key
onkeypress The event occurs when the user presses a key
onkeyup The event occurs when the user releases a key
Useful page Events
onload The browser has finished loading the page
onpageshow The event occurs when the user navigates to a webpage
onpagehide The event occurs when the user navigates away from a webpage, this may not work as expected based on browser settings

The list is much longer: W3Schools JavaScript Reference HTML DOM Events.

Event objects:

There are useful event objects that provide useful information (attributes/properties) and operations (methods) about the event that was triggered.

For example when a key on the keyboard is pressed, it will be useful to know which key was pressed as well.

Here is a list of some common useful event properties:

Event Property Description
Keyboard Event object
key Returns the key value of the key represented by the event
Mouse Event object
button Returns which mouse button was pressed when the mouse event was triggered
buttons Returns which mouse buttons were pressed when the mouse event was triggered
which Returns which mouse button was pressed when the mouse event was triggered.
The values returned by this property are the same as those returned by the button property plus one
clientX Returns the horizontal coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered
clientY Returns the vertical coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered
Mouse Wheel Event object
deltaY Returns the vertical scroll amount of a mouse wheel (y-axis)


Making Decisions (logical true/false)- if statements-if,else, else-if

var i = 10;

if (i < 5) { 
  greeting = "Good day";
}
else if (i < 6) {
  greeting = "Good evening";
}
else {
  greeting = "Good night";
}

The variable greeting will be assigned "Good night" because i = 10 which causes the first two conditions to evaluate to false

Conditional (Ternary) Operator

variablename = (condition) ? value1:value2 

Example
var age= 16;
var voteable = (age < 18) ? "Too young":"Old enough";

The variable voteable is assigned "Too young" because the condition evaluates to true.

The Switch statement

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

Example
var i = 10;

switch (i) {
  case 1:
    greeting = "Hello";
    break;
  case 5:
    greeting = "Good day";
    break;
  case 8:
    greeting = "Good afternoon";
    break;
  case 10:
    greeting = "Good night";
    break;
  default:
    greeting = "bye bye"
}

A neat way of selecting one of many blocks of code to execute. In this case, the variable greeting is assign "Good night".

The default case is optional and is similar to the else statement- if all comparisons are false, the default will execute

Note that Switch cases use strict comparison (===). The values must be of the same type to match.


The Comparison and Logical Operators

Comparison operators are used in logical statements to determine equality or difference between variables or values.

Given that x = 5, the table below explains the comparison operators:

Operator Description Comparing Returns Try it
== equal to x == 8 false Try it »
x == 5 true Try it »
x == "5" true Try it »
=== equal value and equal type x === 5 true Try it »
x === "5" false Try it »
!= not equal x != 8 true Try it »
!== not equal value or not equal type x !== 5 false Try it »
x !== "5" true Try it »
x !== 8 true Try it »
> greater than x > 8 false Try it »
< less than x < 8 true Try it »
>= greater than or equal to x >= 8 false Try it »
<= less than or equal to x <= 8 true Try it »

Logical Operators

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

Given that x = 6 and y = 3, the table below explains the logical operators:

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


Comparing data of different types may give unexpected results.

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison.
An empty string converts to 0. A non-numeric string converts to NaN which is always false.


Case Value Try
2 < 12 true Try it »
2 < "12" true Try it »
2 < "John" false Try it »
2 > "John" false Try it »
2 == "John" false Try it »
"2" < "12" false Try it »
"2" > "12" true Try it »
"2" == "12" false Try it »

When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.

To secure a proper result, variables should be converted to the proper type before comparison:


JavaScript Loops

Loops can execute a block of code a number of times.

The For Loop - repeat statements or commands a known number of times

The for loop has the following syntax:

for (initializations; condition; incrementations) {
  // code block to be executed
}
Example:
for (var i = 0; i < 5; i++) {
  // code block to be executed
}

//The loop will repeat (from i = 0 to i = 4) five (5) times

The While Loop - repeat statements or commands an unknown number of times

The while loop loops through a block of code as long as a specified condition is true.

Syntax:

while (condition) {
  // code block to be executed
}
Example:
var i = 0;
while (i < 5) {
  //code block to be executed 
  i++;  //equivalent to i = i + 1;
}

//The loop will repeat (from i = 0 to i = 4) five (5) times based on the condition (i < 5).

The Do/While Loop - repeat statements or commands at least once, and an unknown number of times.

do {
  // code block to be executed
}
while (condition);
Example:
var i = 0;
do {
	//code block to be executed
	i++;
} 
while (i < 5); 

//The loop will repeat (from i = 0 to i = 4) five (5) times based on the condition (i < 5).

Keywords break; and continue;

You can use the keyword continue, to skip an iteration of the loop.
You can use the keyword break, to jump out of (end) a loop.
These keywords are often used with if-statements.

Be careful with infinite loops!! they can crash your browser!


Getting form data with javascript and JavaScript Form validation

Method 1:

Using the Document method getElementById() to access the value attribute of the input form element.

<input id ="fname" type="text" name="firstname" value="" placeholder="Enter first name" oninput="getName()" >
<p id = "display"></p>
<script>
  var name = "";
  function getName(){
    name = document.getElementById("fname").value //store entered name
    document.getElementById("display").innerHTML = name; //display the name
  }
</script>

Method 2:

Using name attributes of a form to access the input element's value docment.forms["myForm"]["fname"].value

See link https://www.w3schools.com/js/tryit.asp?filename=tryjs_validation_js

There are other ways but these are very effective for now

Form Validation

For the javascript form validation Api see https://www.w3schools.com/js/js_validation_api.asp

Constraint Validation HTML Input Attributes

Attribute Description
disabled Specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires an element
type  Specifies the type of an input element

For a full list, go to HTML Input Attributes.

Constraint Validation CSS Pseudo Selectors

Selector Description
:disabled Selects input elements with the "disabled" attribute specified
:invalid Selects input elements with invalid values
:optional Selects input elements with no "required" attribute specified
:required Selects input elements with the "required" attribute specified
:valid Selects input elements with valid values

For a full list, go to CSS Pseudo Classes.


Web Storage

Javascript variables are temporary and their values are all lost when you reload the webpage.

Web storage allows you to store data in the browser.

HTML web storage provides two objects for storing data on the client:

window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

The first syntax is useful for using variable to store the key used to access the value
// Store
localStorage.setItem("lastname", "Smith");

// Retrieve
var lastname = localStorage.getItem("lastname");

OR

// Store
localStorage.lastname = "Smith";
// Retrieve
var lastname = localStorage.lastname;

To remove an item:

localStorage.removeItem("lastname");

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.

Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!


Handling Form Data

Following is an example of saving form data to a text file with php on a webserver.
This is a very basic example of how a messaging website can work.

Example: SaveMessage.php

<?php
$myfile = fopen("message.txt", "w") or die("Unable to open file!");

$txt = $_GET["message"];
fwrite($myfile, $txt);

fclose($myfile);

echo "Message Sent";
?>

Html Form: index.html

<html>
<head>
<title>My Form</title>
</head>
<body>
<form action="SaveMessage.php">
  Message: <input type="text" name="message" placeholder='Enter message'>
  <input type="submit" value='Send Message'>
</form>
</body>
</html>

PHP - just a little on using php to store text files

To test PHP code, you will have to use a webserver/webhost that supports php or download a php server such as WAMP or XAMPP

Reading/displaying a text (.txt) file stored on your web server

Opening a file with php

Create/Write to a file with php

Also Note that you can use AJAX to read from text files stored on a webserver/webhost




For your reference:


A note on variable Scope and Hoisting

Functions and variables can be used before they are declared because they are "hoisted" or automatically declared at top of a program.

Variables declared with let or const are NOT hoisted

Initializations (var y=5;) are NOT hoisted, however the declaration (var y;) will be hoisted.

document.write(myNum); //writes undefined
var myNum = 5;
________________

Note: Functions are not hoisted when declared in a variable.


let, var and const

let

var

Not using var or let will make your variable a global variable

Using global varibles is bad programming practice because your variable can be changed anywhere in the program unknown to you.
Use global variables sparingly.

var num = 10;
myFunction();
document.write(num); //prints 5

function myFunction() {
    num = 5
}

JavaScript Date() Functions


JavaScript Builtin Math Functions


Generating a Random Number


JavaScript Error handling