What Can JavaScript Do?

JavaScript can change HTML content.


JavaScript can change HTML attribute values.

In this case JavaScript changes the value of the src (source) attribute of an image.


JavaScript can change the style of an HTML element.


JavaScript can hide HTML elements.


JavaScript Functions

A JavaScript function is a block of JavaScript code, that can be executed when "called" for.
For example, a function can be called when an event occurs, like when the user clicks a button.


A Paragraph


JavaScript Output Possibilities

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

To access an HTML element, JavaScript can use the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML content:

Number below is the result of 5000 + 6666 posted to [para id=demo_5] using command:
document.getElementById("demo_5").innerHTML = 5000 + 6666;


You can use an alert box to display data: 5000 + 6666

For debugging purposes, you can use the console.log() method to display data. Don't forget to show console found in Developers Tools (F12 for shortcut)

Next lesson Javascript Statements

JavaScript Statements

JavaScript supports or the usual mathamatical and algebraic Statements.

JavaScript programmers tend to use camel case that starts with a lowercase letter: firstName, lastName, masterCard, interCity.
JavaScript uses the Unicode character set. Unicode covers (almost) all the characters, punctuations, and symbols in the world.

JavaScript Data Types

Declaration Examples:

Number: var pi = 3.14;
String: var person = "John Doe";
String var answer = 'Yes I am!';

Create a variable, assign a value to it, and display it:

JavaScript Data Types

JavaScript variables can hold many data types: numbers, strings, objects and more:

 var length = 16;                               // Number
 var lastName = "Johnson";                      // String
 var x = {firstName:"John", lastName:"Doe"};    // Object

In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type. Without data types, a computer cannot safely solve this:
JavaScript evaluates expressions from left to right. Different sequences can produce different results:
var x = 16 + 4 + "Volvo"; Evaluates as 20Volvo
var x = "Volvo" + 16 + 4; Evaluates as Volvo164 (All converted to string)

JavaScript Types are Dynamic
This means that the same variable can be used to hold different data types:

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

JavaScript Numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:

var x1 = 34.00;     // Written with decimals
var x2 = 34;        // Written without decimals

JavaScript Booleans
Booleans can only have two values: true or false.

 var x = 5;
 var y = 5;
 var z = 6;
 (x == y)       // Returns true
 (x == z)       // Returns false

JavaScript Arrays
JavaScript arrays are written with square brackets. Array items are separated by commas. The following code declares (creates) an array called cars, containing three items (car names):

var cars = ["Saab", "Volvo", "BMW"];

JavaScript Objects
JavaScript objects are written with curly braces {}. Object properties are written as name:value pairs, separated by commas. Array items are separated by commas. The following code declares (creates) an array called cars, containing three items (car names):

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

The typeof Operator
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:

typeof ""             // Returns "string"
typeof "John"         // Returns "string"
typeof "John Doe"     // Returns "string"
typeof 0              // Returns "number"
typeof 314            // Returns "number"
typeof 3.14           // Returns "number"
typeof (3)            // Returns "number"
typeof (3 + 4)        // Returns "number"
var car;              // Value is undefined, type is undefined
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null;    // Now value is null, but type is still an object
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = undefined;   // Now both value and type is undefined
Note:
typeof undefined           // undefined
typeof null                // object
null === undefined         // false
null == undefined          // true

Primitive Data
A primitive data value is a single simple data value with no additional properties and methods. The typeof operator can return one of these primitive types:

string
number
boolean
undefined

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)

Complex Data
The typeof operator can return one of two complex types:
function
object
The typeof operator returns "object" for objects, arrays, and null. The typeof operator does not return "object" for functions.

typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4]             // Returns "object" (not "array", see note below)
typeof null                  // Returns "object"
typeof function myFunc(){}   // Returns "function"

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

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

function myFunction(p1, p2) {
  return p1 * p2;   // The function returns the product of p1 and p2
}

Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
A Function is much the same as a Procedure or a Subroutine, in other programming languages.

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code

Function Return

Example
Calculate the product of two numbers, and return the result:
       
var x = myFunction(4, 3);   // Function is called, return value will end up in x
        
function myFunction(a, b) {
return a * b;             // Function returns the product of a and b
}
The result in x will be:
      
12

Functions Used as Variable Values
Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.
Example
Instead of using a variable to store the return value of a function:

var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";

You can use the function directly, as a variable value:
       
var text = "The temperature is " + toCelsius(77) + " Celsius";

Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
Example

// code here can NOT use carName
       
function myFunction() {
    var carName = "Volvo";
    // code here CAN use carName
}
        
// code here can NOT use carName

JavaScript Objects

Real Life Objects, Properties, and Methods
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:

Object:
CAR

Properties:
    car.name = Fiat
    car.model = 500
    car.weight = 850kg
    car.color = white	

Methods:
    car.start()
    car.drive()
    car.brake()
    car.stop()

All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.

JavaScript Objects
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
var car = "Fiat";
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:"Fiat", model:"500",
The values are written as name:value pairs (name and value separated by a colon).
JavaScript objects are containers for named values called properties or methods.

Object Definition
You define (and create) a JavaScript object with an object literal:
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span multiple lines:

var person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue"
    };

Object Properties
The name:values pairs in JavaScript objects are called properties:

    Property	Property Value
    firstName	John
    lastName	Doe
    age	        50
    eyeColor	blue

Accessing Object Properties
You can access object properties in two ways:

    objectName.propertyName
    or
    objectName["propertyName"]

    Example1
    person.lastName;

    Example2
    person["lastName"];

Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.

    Property	Property Value
    firstName	John
    lastName	Doe
    age	        50
    eyeColor	blue
    fullName	function() {return this.firstName + " " + this.lastName;}
    

A method is a function stored as a property.
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
    return this.firstName + " " + this.lastName;
    }
};    

The this Keyword
In a function definition, this refers to the "owner" of the function.
In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.

Accessing Object Properties
You can access object properties in two ways:

objectName.propertyName
or
objectName["propertyName"]
        
Example1
  person.lastName;
       
Example2
  person["lastName"];   
 

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:

var x = new String();        // Declares x as a String object
var y = new Number();        // Declares y as a Number object
var z = new Boolean();       // Declares z as a Boolean object

Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.

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

HTML events are "things" that happen to HTML elements. An HTML event can be something the browser does, or something a user does. 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
Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
With single quotes:


With double quotes:
   
> In the following example, an onclick attribute (with code), is added to a button element:
Example

In the example above, the JavaScript code changes the content of the element with id="demo". In the next example, the code changes the content of its own element (using this.innerHTML):
Example

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

Click the button to display the date.



<script>
    function displayDate() {
    document.getElementById("demo_7").innerHTML = Date();
    }
</script>
        
<p id="demo">

Common HTML Events
Here is a list of some 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
    
The list is much longer: W3Schools JavaScript Reference HTML DOM Events.
https://www.w3schools.com/jsref/dom_obj_event.asp

What can JavaScript Do?

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

Things that should be done every time a page loads
Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data
And more ...
Many different methods can be used to let JavaScript work with events:
      
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 ...

JavaScript Strings

A JavaScript string is zero or more characters written inside quotes.
String Length
To find the length of a string, use the built-in length property:

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Escape Character
Code	Result	Description
\'	'	Single quote
\"	"	Double quote
\\	\	Backslash    
Six other escape sequences are valid in JavaScript:
Code	Result
\b	Backspace
\f	Form Feed
\n	New Line
\r	Carriage Return
\t	Horizontal Tabulator
\v	Vertical Tabulator    

HTML Events

HTML events are "things" that happen to HTML elements. An HTML event can be something the browser does, or something a user does. 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

Strings Can be Objects
Normally, JavaScript strings are primitive values, created from literals:
var firstName = "John";
But strings can also be defined as objects with the keyword new:
var firstName = new String("John");

Example
var x = "John";
var y = new String("John");
    
// typeof x will return string
// typeof y will return object   

Don't create strings as objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:
When using the === operator, equal strings are not equal, because the === operator expects equality in both type and value.
Example
var x = "John";             
var y = new String("John");
    
// (x === y) is false because x and y have different types (string and object)   

Or even worse. Objects cannot be compared:
Example
var x = new String("John");             
var y = new String("John");

// (x == y) is false because x and y are different objects

Example
var x = new String("John");             
var y = new String("John");

// (x === y) is false because x and y are different objects

JavaScript String Methods

Examples:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");

Note: 
Both indexOf(), and lastIndexOf() return -1 if the text is not found.

Both methods accept a second parameter as the starting position for the search:
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate", 15);

The lastIndexOf() methods searches backwards (from the end to the beginning), 
meaning: if the second parameter is 15, the search starts at position 15, 
and searches to the beginning of the string.

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate", 15);

Searching for a String in a String
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");

Note:
The two methods, indexOf() and search(), are not equal!
The search() method cannot take a second start position argument.
The indexOf() method cannot take powerful search values (regular expressions).

Extracting String Parts
There are 3 methods for extracting a part of a string:

slice(start, end)
substring(start, end)
substr(start, length)

substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
The result of res will be: Banana

substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);
The result of res will be: Banana

The replace() method replaces a specified value with another value in a string:
The replace() method does not change the string it is called on. It returns a new string.
By default, the replace() method replaces only the first match:

str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3Schools");

By default, the replace() method is case sensitive.
To replace case insensitive, use a regular expression with an /i flag (insensitive):
str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3Schools");

To replace all matches, use a regular expression with a /g flag (global match):
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools");

Converting to Upper and Lower Case
var text1 = "Hello World!";       // String
var text2 = text1.toUpperCase();  // text2 is text1 converted to upper

A string is converted to lower case with toLowerCase():
var text1 = "Hello World!";       // String
var text2 = text1.toLowerCase();  // text2 is text1 converted to lower

The concat() Method
concat() joins two or more strings:
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);

The concat() method can be used instead of the plus operator. These two lines do the same:
var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ", "World!");

String.trim()
The trim() method removes whitespace from both sides of a string:
var str = "       Hello World!        ";
alert(str.trim());

The trim() method is not supported in Internet Explorer 8 or lower.

If you need to support IE 8, you can use replace() with a regular expression instead:
var str = "       Hello World!        ";
alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));

Extracting String Characters
There are 3 methods for extracting string characters:

charAt(position)
charCodeAt(position)
Property access [ ]

var str = "HELLO WORLD";
str.charAt(0);            // returns H

The charCodeAt() Method
The charCodeAt() method returns the unicode of the character at a specified index in a string:
var str = "HELLO WORLD";
str.charCodeAt(0);         // returns 72

Property Access
ECMAScript 5 (2009) allows property access [ ] on strings:
var str = "HELLO WORLD";
str[0];    // returns H

Property access might be a little unpredictable:

It does not work in Internet Explorer 7 or earlier
It makes strings look like arrays (but they are not)
If no character is found, [ ] returns undefined, while charAt() returns an empty string.
It is read only. str[0] = "A" gives no error (but does not work!)

var str = "HELLO WORLD";
str[0] = "A";             // Gives no error, but does not work
str[0];                   // returns H

Converting a String to an Array
A string can be converted to an array with the split() method:

var txt = "a,b,c,d,e";   // String
txt.split(",");          // Split on commas
txt.split(" ");          // Split on spaces
txt.split("|");          // Split on pipe

----------------------------
p id="demo">

script> function myFunction() { var str = "a,b,c,d,e,f"; var arr = str.split(","); document.getElementById("demo").innerHTML = arr[0]; } /script> ---------------------------- Print and 'a' to the screen where (para id "demo") is located var txt = "Hello"; // String txt.split(""); // Split in characters ---------------------------- p id="demo">

script> var str = "Hello"; var arr = str.split(""); var text = ""; var i; for (i = 0; i < arr.length; i++) { text += arr[i] + "
" } document.getElementById("demo").innerHTML = text; /script> ----------------------------

JavaScript Numbers

JavaScript Numbers are Always 64-bit Floating Point Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc. 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 (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:

Precision
Integers (numbers without a period or exponent notation) are accurate up to 15 digits.
        
Example
var x = 999999999999999;   // x will be 999999999999999
var y = 9999999999999999;  // y will be 10000000000000000   

The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:
Example
var x = 0.2 + 0.1;         // x will be 0.30000000000000004

To solve the problem above, it helps to multiply and divide:
var x = (0.2 * 10 + 0.1 * 10) / 10;       // x will be 0.3

Numeric Strings
JavaScript strings can have numeric content:

var x = 100;         // x is a number
var y = "100";       // y is a string

JavaScript will try to convert strings to numbers in all numeric operations:
This will work:

var x = "100";
var y = "10";
var z = x / y;       // z will be 10

But this will not work:
var x = "100";
var y = "10";
var z = x + y;       // z will not be 110 (It will be 10010)

NaN - Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal number.
Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number)

var x = 100 / "Apple";  // x will be NaN (Not a Number)

var x = NaN;
var y = "5";
var z = x + y;         // z will be NaN5

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

var myNumber = 2;
while (myNumber != Infinity) {   // Execute until Infinity
  myNumber = myNumber * myNumber;
}
Result stops and prints the word 'Infinity'

var x =  2 / 0;       // x will be Infinity
var y = -2 / 0;       // y will be -Infinity

Infinity is a number: typeof Infinity returns number.
typeof Infinity;     // returns "number"

Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
var x = 0xFF;        // x will be 255

Never write a number with a leading zero (like 07).
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.
Hexadecimal is base 16. Decimal is base 10. Octal is base 8. Binary is base 2.

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

Numbers can be objects

Normally JavaScript numbers are primitive values created from literals:

var x = 123;
But numbers can also be defined as objects with the keyword new:
        
var y = new Number(123);
        
Example
var x = 123;
var y = new Number(123);
        
// typeof x returns number
// typeof y returns object
Do not create Number objects. It slows down execution speed. The new keyword complicates the code. This can produce some unexpected results:
When using the == operator, equal numbers are equal:
Example
var x = 500;             
var y = new Number(500);
// (x == y) is true because x and y have equal values

var x = 500;             
var y = new Number(500);
// (x === y) is false because x and y have different types

var x = new Number(500);             
var y = new Number(500);
// (x == y) is false because objects cannot be compared

JavaScript Number Methods

Just switch to w3schools from here on in.
W3Schools.com Learn Javascript

Click on image below to make it dissappear!

Button to display car list object: color = 'red'.