Javascript by Example

Introduction

What is JavaScript?

Cross platform language, created by Brendan Eich at Netscape.

Specifications ?

Here are one specification from the very begining :
JavaScript Specification 1.1, 1996
and one rather new Ecma-Script specificaton.
Ecma-262 5.1, 2011

What can I do with JavaScript?

Programming the Browser DOM
Server-side programming (e.g. with Node.js)

Reference JavaScript files in the header

If you want to reference JavaScript that exists already in files you'll link the files in the page header.

<html>
  <body>
    <script type="text/javascript" src="externalScript.js">
    </script>
  </body>
</html>

Put JavaScript in the header

Library functions go usually inside the header.

<head>
  <script script type="text/javascript">
    alert("Hello");
  </script>
</head>

Put JavaScript in the body

You can put your JavaScript anywhere inside the page as long as it is in script tags.
If you put it inside the body, then it will be executed when the page parser reads your script tag.

<script script type="text/javascript">
  ... your script here
</script>

Hiding JavaScript

Very old browsers don't know about script tags. They will show your JavaScript.
You can hide JavaScript for them by wrapping it with HTML comments and hide the HTML comments with js comments. That way, all browsers will be happy.

<script type="text/javascript">
  //<!-- js comment plus html comment to hide script
   // contents from older browsers.
  ... put your JavaScript code here ...
  // End hiding. --> 
</script>
                    

"Hello World" using alert()

Syntax: void window.alert(String txt)
Shows the value of txt in a browser specific pop-up box.

  window.alert("Hello World!");

Using confirm()

Syntax: Boolean window.confirm(String txt)
Shows the value of txt in a browser specific pop-up box with two buttons ('ok' and 'cancel').

  window.confirm("Are you sure ?");

Writing "Hello World" to the page

This will write to the page at the place where your script tag is.

document.write("Hello World!");

Sample page with Javascript

This calls a function which is defined inside the header and writes the result to the page output.
The result look like this:

Simple Example Page

3 + 4 is 7.

The End.

<html>
  <head>
    <script type="text/javascript"> 
      function add(x, y) {
        return x + y;
      }
    </script>
  </head>
  <body>
    <b>Simple Example Page</b>
    <script type="text/javascript">
      document.write("3 + 4 is ");
      document.write( add(3, 4), ".");
    </script>
    <p>The End.</p>
  </body>
</html> 

JS Language

Comments

Comments are not executed by JavaScript.
They help understand the code.

// This is a single line comment
// It start with '//' and ends at the end of the line

var x=42;    // a single line comment at the end of a line

/* And
this is a
multi-line comment
*/

var s = "one"; /* inline comment */ var s2 = "two";

Variables names

  • Variable names must begin with a letter, $ or _
  • $ is reserved for internals.
  • Variable names are case sensitive, as function names etc.
  • Variable names should not be keywords of the language.
var myNumber = 1;
var a_string_with_gaps = "ok";
var a__0000 = "ok but funny looking";

// BAD
var _allowed_but_not_used = "not good";
var $allowed_but_reserved = "reserved";
var Math = "this will over-write the predefined Math object";
var 1_notAVariable = "sytax error";
var while = "syntax error";

Data Types

In JavaScript values or data have types, not the variables.
The same varialbe can be successively a number, a string or a date.

JavaScript has primitive data types and reference data types.
JavaScript's primitive data types are:

  • boolean (true and false)
  • number (integer or floating-point)
  • undefined

JavaScript's reference data types are:

  • string
  • object (and null object)
  • function
var i = 42;            // asigns i a number
var b = true;          // asigns b a boolean (true or false)
var s = "Hello";       // asigns s a string literal
var s2 = new String("Hello");      // asigns s2 a new String object
var d = new Date();    // asigns d a new date object, current date and time
var r = /$a.*/ig;      // asigns  r a new regular expression object
var ar = new Array();  // asigns ar a new empty array
var f = function(x) {return x*x;}; // asigns f a function

// changing variables
var x;               // undefined
x = null;        // now it is null
x = "Fritz";     // now it's a string  
x = 1;           // now a number
x = "Fritz" + x; // now a string again
x = new Date();  // and now the current date and time


Type Conversion

Something always good to know and sometimes surprising is type conversion.

To type
function object number boolean string
undefined error null error false "undefined"
function N/C Function object valueOf/error valueOf/true decompile
object
(not null)
(null)

Function object
error

N/C

valueOf/error
0

valueOf/true
false

toString/valueOf1
"null"
From type number
(zero)
(nonzero)
(NaN)
(+Infinity)
(-Infinity)

error
error
error
error
error

Number
Number
Number
Number
Number

N/C

false
true
false
true
true

"0"
default*
"NaN"
"+Infinity"
"-Infinity"
Boolean
(false)
(true)

error
error

Boolean
Boolean

0
1

N/C

"false"
"true"
string
(empty)
(non-empty)

error
error

String
String

error
number/error

false
true

N/C

Key (Explanation)

When two results separated by a slash are given, JavaScript tries the first, and if unsuccessful, uses the second.

N/C: No conversion necessary.
decompile: A string containing the function's canonical source.
toString: The result of calling the toString method.
valueOf: The result of calling the valueOf method, if it returns a value of the To type.
number: Numeric value if string is a valid integer or floating-point literal.

Booleans

There are two primitif booleans: true and false.

Take care when you test booleans with equality.
A Boolean object that is true is equal to true but not strictly equal.

But JavaScript will convert any value to a boolean if needed.
When you apply a double logical-not you'll get JavaScripts boolean interpretation of that value.

 

var b = true; // b is true primitif
b == true;    // is true
b === true;   // since b is true and primitif

var bO = new Boolean(true); bO is true, but an object
bO == true;    // true
bO !== true;   // bO is an object

var bS = new Boolean("hallo");
var bS2 = bS.valueOf()); // true, non-empty strings convert to true

var bS = !! "hallo"; // true, non-empty string
var bE = !! "";      // false, empty string
var b0 = !! 0;       // false, 0 converts to false
var b1 = !! 1;       // true, numbers != 0 convert to true
var bF = !! new Object(false); // true, objects convert to true
var bN = !! null;    // false; null is false

Numbers

A number can be either an integer or floating-point; JavaScript does not explicitly distinguish between them.

Internally, all numbers are represented as 64-bit floating point. Floating-point numbers are in 64-bit IEEE 754 format.

If an operation cannot produce a normal result the value is NaN (not a number)

var i = 1; // == 1.0; integer syntax
i = 1.123; // fraction syntax 
i = 1e2;   // ==100; exponent syntax

i = 1/4    // == .25
i = 1/'s'  // NaN
i = 1e+308 // == 1e308
i = 1e309  // == Infinity 
i = 0.1 + 0.2 // != 0.3 BUT 0.30000000000000004 :) that is IEEE 754
// number objects
var n = new Number(7); // object of type number, value 7
var max = Number.MAX_VALUE; // 1.7976931348623157e+308

undefined

Any variable that has not been assigned a value is of type undefined.

var a; 
if(typeof(a) == 'undefined') // test type, this is true
if(a)   // false, 'undefined' converts to boolean false

Strings

A string is a sequence of ASCII characters created by use of a string literal or a string expression.

Note the reference-type behavior for assignment operations, but not for equality and relational operations.

var s1 = new String("Hello "); // using a constructor function
var s2 = "John!"; // string literal
// concatenation
var s3 = s1 + s2; // "Hello John!"
var s4 = 1+4+"x"  // "5x"
var s5 = 1+"x"+4  // "1x4"
// indexing
s[1]       // "e", access by index
// length
s3.length  // 11
// comparison
s1 < s2    // true, lexicographical precedence

Objects

Objects can be build-in objects (like Date, Array, Math, Number, String, Regular Expression) or user defined objects.

An object is a container for properties. Each property of an object can be of any type and can be named by any string.

A property name that is a nonnegative integer literal is called an index.

Objects are defined by constructor functions.

// Custom object constructor function
var Person = function(first, last) {
  this.first = first;
  this.last = last;
  this.fullName = function() {
    return this.first + ' ' + this.last;
  };
};
// using the Person constructor  
var s = new Person("David", "Hume");
var n0 = s.fullName();    // David Hume
var n1 = s.last;      // Hume
var n2 = s["last"];   // Hume

for(x in s){          // "first", "last", "fullName"
 console.log(x);      // shows all enumerable properties
} 

var a = Object.keys(s);   // [ "first" , "last" , "fullName" ] 

object.toString()

Every object has a toString method used to convert the object to a string value, as follows:

  • Boolean objects are converted to the string literal expression of their value: "true" or "false."
  • Number objects are converted to the string literal expression of their value: decimal if integer and floating-point otherwise.
  • Functions are decompiled, that is, a string containing the function's source definition is pretty-printed.
  • Objects are converted by trying the object's toString method. If that is not defined, then the object's valeuOf method is tried. If that does not exist or does not return a string, then the result is a string of the form "[object class]", where class is the capitalized type name.
function f() { return 42 }
f.toString();     // "function f() { return 42 }"

true.toString();  // "true"

var n0=0; 
console.log(n0.toString()); // "0"

var s = new Person("David", "Hume");
s.toString();     // "[object Object]"

var d = new Date();
d.toString();     // "function Date() { [native code] }"



object.valueOf()

Every object has a valueOf method that returns the value associated with the object, if any.

 

var b = new Boolean(true);
b !== true  // b is an object, it is not strictly eq to true
b.valueOf() === true; // but the primitive is equal

null

A value of type object that refers to no object is a special null reference.

var a;        // 'undefined'
a == null     // 'undefined' converts to null object.
a !== null    // 'undefined' is not the same type as null.

var b = null;
b == null     // true
if(b)         // false, null converts to boolean false.

Functions

A function is a set of statements that performs a specific task. It constist of (name, parameters, body of statements.

A function call executes the function statements and optionally returns a value.

The number of arguments in a call does not have to match the number of arguments in the function definition. Any argument in the definition which has no argument in the call will be undefined. Any extra argument in the function will be ignored by default.

You can a default value to any argument.

You can access all arguments sent to a function via the functions arguments array.

Every function has a caller property. It is a reference to the caller function if there is one, otherwise it's null.

function myFunc(a, b){ 
  return a + b; 
}
function myFunc2(a, b=1){ // default value for b
  return myFunc(a, b); 
}
function myFunc3(a){
  if(myFunc3.arguments.length > 1){
    return myFunc(a, myFunc3.arguments[1]); // arguments array
  }
  else{
    return a;
  }
}
// call function
var x0 = myFunc(1, 3); // 4

// call function with less arguments
x = myFunc(1);     // NaN; 1 + undefined is not a number
x = myFunc2(1);    // 2; b takes the default value

// call function with more arguments
x = myFunc3(1, 5); // 6

// caller property
function inner (){ return inner.caller.name; } // returns "outer"
function outer (){ return inner(); } 
var y = outer(); // y = "outer";

Math object

The built-in Math object has properties and methods for common mathematical operations.

Mathematical constants are read-only properties.

 

 

// contants
Math.PI      // pi = 3.141592653589793
Math.E       // Euler's constant = 2.718281828459045
Math.LN2     // natural logarithm of 2 = 0.6931471805599453
Math.LN10    // natural logarithm of 10 = 2.302585092994046
Math.LOG2E   // base 2 logarithm of e = 1.4426950408889634
Math.LOG10E  // base 10 logarithm of e = 0.4342944819032518
Math.SQRT2   // square root of 2 = 1.4142135623730951
Math.SQRT1_2 // square root of 1/2 = 0.7071067811865476

// functions
Math.abs(-1)        // 1, absolute value of a number
Math.acos(0.5)      // ~Math.PI/3, arc cosine (in radians) of a number [-1, 1]
Math.asin(0.5)      // ~Math.PI/6, arc sine (in radians) of a number [-1, 1]
Math.atan(1)        // arc tangent (in radians) of a number
Math.ceil(1.1)      // 2, least integer greater than or equal to its argument.
Math.cos(Math.PI)   // -1, cosine of a number.
Math.exp(2)         // 7.389..., that is ex,
Math.log(2)         // 0.693..., natural logarithm (base e)
Math.max(1, 2)      // 2, the greater of two numbers
Math.min(1, 2)      // 1, the lesser of two numbers
Math.pow(2, 8)      // 256, 2 to the 8th power
Math.random()       // 0.42, pseudo-random number between zero and one
Math.round(1.4)     // 1, value of a number rounded to the nearest integer, .5 is rounded to the next highest integer.
Math.sin(Math.PI/2) // 1, sine of a number
Math.sqrt(256)      // 16, square root of a non-negative number
Math.tan(x)         // tangent of a number. 

Math.sin = function(x){ return x*x; } // function is overwritten
Math.sin(2);        // is now 4

Date object


                    

RegularExpressions


                    


                    






Syntax



Syntax - Control Flow



Object Orientated JavaScript






Advanced JavaScript



No comments: