Wednesday, 13 May 2015

JavaScript Date Formats

JavaScript Date Formats

Valid JavaScript Date Strings

There are generally three types of valid JavaScript date formats:
  • ISO Dates
  • Long Dates
  • Short Dates

JavaScript ISO Dates

The ISO 8601 syntax (YYYY-MM-DD) is the newest (and preferred) JavaScript date format:

Example

var d = new Date("2015-03-25"); 
 
Or as: "2014-12" (YYYY-MM):

Example

var d = new Date("2015-03");
  

Or as "2014" (YYYY):

Example

var d = new Date("2015"); 
 
Or as "2014-12-24T12:00:00":

Example

var d = new Date("2015-03-25T12:00:00"); 
 

JavaScript Long Dates.

Long dates are most often written with a "MMM DD YYYY" syntax like this:

Example

var d = new Date("Mar 25 2015"); 
 
But, year, month, and day can be in any order:

Example

var d = new Date("25 Mar 2015"); 
 

Example

var d = new Date("2015 Mar 25"); 
 
And, month can be written in full (January), or abbreviated (Jan):

Example

var d = new Date("January 25 2015"); 
 

Example

var d = new Date("Jan 25 2015"); 
 
Commas are ignored. Names are case insensitive:

Example

var d = new Date("2015, JANUARY, 25"); 
 

JavaScript Short Dates.

Short dates are most often written with an "MM/DD/YYYY" syntax like this:

Example

var d = new Date("03/25/2015");
 
Either "/" or "-" can be used as a separator:

Example

var d = new Date("03-25-2015"); 
 
JavaScript will also accept "YYYY/MM/DD":

Example

var d = new Date("2015/03/25"); 
 

Full Format

JavaScript will accept date strings in "full JavaScript format":

Example

var d = new Date("Wed Mar 25 2015 09:56:24 GMT+0100 (W. Europe Standard Time)"); 
 
JavaScript will ignore errors both in the day name and in the time parentheses:

Example

var d = new Date("Fri Mar 25 2015 09:56:24 GMT+0100 (Tokyo Time)");
 
 
 
 
 
 
 
 
 
 
 
 

 

JavaScript Dates

JavaScript Dates

The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds)

JavaScript Date Formats

A JavaScript date can be written as a string:
Thu May 07 2015 14:12:12 GMT+0800 (Malay Peninsula Standard Time)
or as a number:
1430979132166
Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00.

Displaying Dates

In this tutorial we use a script to display dates inside a <p> element with id="demo":

Example

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Date();
</script>
 

Creating Date Objects

The Date object lets us work with dates.
A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.
Date objects are created with the new Date() constructor.
There are 4 ways of initiating a date:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Using new Date(), creates a new date object with the current date and time:

Example

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script> 
 
 Using new Date(date string), creates a new date object from the specified date and time:

Example

<script>
var d = new Date("October 13, 2014 11:13:00");
document.getElementById("demo").innerHTML = d;
</script>
 
Using new Date(number), creates a new date object as zero time plus the number.
Zero time is 01 January 1970 00:00:00 UTC. The number is specified in milliseconds:

Example

<script>
var d = new Date(86400000);
document.getElementById("demo").innerHTML = d;
</script> 
 
Using new Date(7 numbers), creates a new date object with the specified date and time:
The 7 numbers specify the year, month, day, hour, minute, second, and millisecond, in that order:

Example

<script>
var d = new Date(99,5,24,11,33,30,0);
document.getElementById("demo").innerHTML = d;
</script>
 
 Variants of the example above let us omit any of the last 4 parameters:

Example

<script>
var d = new Date(99,5,24);
document.getElementById("demo").innerHTML = d;
</script>
 

Date Methods

When a Date object is created, a number of methods allow you to operate on it.
Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of objects, using either local time or UTC (universal, or GMT) time.
Note Date methods are covered in a later chapter.

Displaying Dates

When you display a date object in HTML, it is automatically converted to a string, with the toString() method.

Example

<p id="demo"></p>

<script>
d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
Is the same as:
<p id="demo"></p>

<script>
d = new Date();
document.getElementById("demo").innerHTML = d.toString();
</script> 
 
The toUTCString() method converts a date to a UTC string (a date display standard).

Example

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script> 
 
The toDateString() method converts a date to a more readable format:

Example

<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toDateString();
</script>
 
 
 

 

JavaScript Math Object

JavaScript Math Object

The Math object allows you to perform mathematical tasks on numbers.

The Math Object

The Math object allows you to perform mathematical tasks.
The Math object includes several mathematical methods.

One common use of the Math object is to create a random number:

Example

Math.random();       // returns a random number 
 

Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:

Example

Math.min(0, 150, 30, 20, -8);      // returns -8 
 

Example

Math.max(0, 150, 30, 20, -8);      // returns 150 
 

Math.random()

Math.random() returns a random number between 0 and 1:

Example

Math.random();              // returns a random number 
 

Math.round()

Math.round() rounds a number to the nearest integer:

Example

Math.round(4.7);            // returns 5Math.round(4.4);            // returns 4 
 

Math.ceil()

Math.ceil() rounds a number up to the nearest integer:

Example

Math.ceil(4.4);             // returns 5 
 

Math.floor()

Math.floor() rounds a number down to the nearest integer:

Example

Math.floor(4.7);            // returns 4 
 
Math.floor() and Math.random() can be used together to return a random number between 0 and 10:

Example

Math.floor(Math.random() * 11);   // returns a random number between 0 and 10 
 

Math Constants

JavaScript provides 8 mathematical constants that can be accessed with the Math object:

Example

Math.E          // returns Euler's number Math.PI         // returns PI Math.SQRT2      // returns the square root of 2 Math.SQRT1_2    // returns the square root of 1/2 Math.LN2        // returns the natural logarithm of 2 Math.LN10       // returns the natural logarithm of 10 Math.LOG2E      // returns base 2 logarithm of E Math.LOG10E     // returns base 10 logarithm of E 
 

Math Object Methods

Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
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
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
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)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
 
 
 
 
 
 
 
 
 
 

JavaScript Number Methods

JavaScript Number Methods

Number methods help you to work with numbers.

Global Methods

JavaScript global functions can be used on all JavaScript data types.
These are the most relevant methods, when working with numbers:
Method Description
Number() Returns a number, converted from its argument.
parseFloat() Parses its argument and returns a floating point number
parseInt() Parses its argument and returns an integer

Number Methods

JavaScript number methods are methods that can be used on numbers:
Method Description
toString() Returns a number as a string
toExponential() Returns a string, with a number rounded and written using exponential notation.
toFixed() Returns a string, with a number rounded and written with a specified number of decimals.
toPrecision() Returns a string, with a number written with a specified length
valueOf() Returns a number as a number
Note All number methods return a new variable. They do not change the original variable.

The toString() Method

toString() returns a number as a string.
All number methods can be used on any type of numbers (literals, variables, or expressions):

Example

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 
 

The toExponential() Method

toExponential() returns a string, with a number rounded and written using exponential notation.
A parameter defines the number of characters behind the decimal point:

Example

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 
 
The parameter is optional. If you don't specify it, JavaScript will not round the number.

The toFixed() Method

toFixed() returns a string, with the number written with a specified number of decimals:

Example

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 
 

The toPrecision() Method

toPrecision() returns a string, with a number written with a specified length:

Example

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 
 

Converting Variables to Numbers

There are 3 JavaScript functions that can be used to convert variables to numbers:
  • The Number() method
  • The parseInt() method
  • The parseFloat() method
These methods are not number methods, but global JavaScript methods.

The Number() Method

Number(), can be used to convert JavaScript variables to numbers:

Example

x = true;
Number(x);        // returns 1x = false;    
Number(x);        // returns 0x = new Date();
Number(x);        // returns 1404568027739 x = "10"
Number(x);        // returns 10 x = "10 20"
Number(x);        // returns NaN 
 

The parseInt() Method

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:

Example

parseInt("10");         // returns 10 parseInt("10.33");      // returns 10 parseInt("10 20 30");   // returns 10 parseInt("10 years");   // returns 10parseInt("years 10");   // returns NaN 
  


The parseFloat() Method

parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:

Example

parseFloat("10");        // returns 10 parseFloat("10.33");     // returns 10.33 parseFloat("10 20 30");  // returns 10 parseFloat("10 years");  // returns 10parseFloat("years 10");  // returns NaN 
 

The valueOf() Method

valueOf() returns a number as a number.

Example

var x = 123;
x.valueOf();            // returns 123 from variable x (123).valueOf();        // returns 123 from literal 123 (100 + 23).valueOf();   // returns 123 from expression 100 + 23 
 
In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).
The valueOf() method is used internally in JavaScript to convert Number objects to primitive values.
There is no reason to use it in your code.
Note In JavaScript, all data types have a valueOf() and a toString() method.
 
 
 
 
 
 

 

Tuesday, 12 May 2015

JavaScript Numbers

JavaScript Numbers

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

JavaScript Numbers

JavaScript numbers can be written with, or without decimals:

Example

var x = 34.00;    // A number with decimals var y = 34;       // A number without decimals
Extra large or extra small numbers can be written with scientific (exponent) notation:

Example

var x = 123e5;    // 12300000 var y = 123e-5;   // 0.00123

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:
Value (aka Fraction/Mantissa) Exponent Sign
52 bits (0 - 51)  11 bits (52 - 62) 1 bit (63)

Precision

Integers (numbers without a period or exponent notation) are considered 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:

Example

var x = (0.2 * 10 + 0.1 * 10) / 10;       // x will be 0.3
 

Hexadecimal

JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.

Example

var x = 0xFF;             // x will be 255 
 
By default, Javascript displays numbers as base 10 decimals.
But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).

Example

var myNumber = 128;
myNumber.toString(16);     // returns 80 myNumber.toString(8);      // returns 200 myNumber.toString(2);      // returns 10000000
 

Infinity

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

Example

var myNumber = 2;
while (myNumber != Infinity) {          // Execute until Infinity    myNumber = myNumber * myNumber;
} 
 
Division by 0 (zero) also generates Infinity:

Example

var x =  2 / 0;          // x will be Infinity var y = -2 / 0;          // y will be -Infinity 
 
Infinity is a number: typeOf Infinity returns number.

Example

typeof Infinity;        // returns "number"
 

NaN - Not a Number

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

Example

var x = 100 / "Apple";  // x will be NaN (Not a Number)
 
However, if the string contains a numeric value , the result will be a number:

Example

var x = 100 / "10";     // x will be 10
 
You can use the global JavaScript function isNaN() to find out if a value is a number.

Example

var x = 100 / "Apple";
isNaN(x);               // returns true because x is Not a Number 
 
Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN.

Example

var x = NaN;
var y = 5;
var z = x + y;         // z will be NaN 
 
NaN is a number: typeOf NaN returns number.

Example

typeof NaN;             // returns "number"
 

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 
 
When using the == equality operator, equal numbers looks equal:

Example

var x = 500;            
var y = new Number(500);

// (x == y) is true because x and y have equal values 
 
When using the === equality operator, equal numbers are not equal, because the === operator expects equality in both type and value.

Example

var x = 500;            
var y = new Number(500);

// (x === y) is false because x and y have different types 
 
Or even worse. Objects cannot be compared:

Example

var x = new Number(500);            
var y = new Number(500);

// (x == y) is false because objects cannot be compared
  


Number Properties and Methods

Primitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

Number Properties

Property Description
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a "Not-a-Number" value
POSITIVE_INFINITY Represents infinity (returned on overflow)

Example

var x = Number.MAX_VALUE; 
 
Number properties belongs to the JavaScript's number object wrapper called Number.
These properties can only be accessed as Number.MAX_VALUE.
Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined:

Example

var x = 6;
var y = x.MAX_VALUE;    // y becomes undefined
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

JavaScript String Methods

JavaScript String Methods

String methods help you to work with strings.

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:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate"); 
 
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate"); 
 
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.
Note JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...
Both methods accept a second parameter as the starting position for the search.

Searching for a String in a String

The search() method searches a string for a specified value and returns the position of the match:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate"); 
 
The two methods, indexOf() and search(), are equal.
They accept the same arguments (parameters), and they return the same value.
The two methods are equal, but the search() method can take much more powerful search values.
You will learn more about powerful search values in the chapter about 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)

The slice() Method

slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the starting index (position), and the ending index (position).
This example slices out a portion of a string from position 7 to position 13:

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);
The result of res will be:
Banana
 
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6);
The result of res will be:
Banana
 
If you omit the second parameter, the method will slice out the rest of the string:

Example

var res = str.slice(7); 
 
or, counting from the end:

Example

var res = str.slice(-12); 
 

The substring() Method

substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);
The result of res will be:
Banana
 
If you omit the second parameter, substring() will slice out the rest of the string.

The substr() Method

substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(7,6);
The result of res will be:
Banana
 
If the first parameter is negative, the position counts from the end of the string.
The second parameter can not be negative, because it defines the length.
If you omit the second parameter, substr() will slice out the rest of the string.


The replace() method can also take a regular expression as the search value.


Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():

Example

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

Example

var text1 = "Hello World!";       // String var text2 = text1.toLowerCase();  // text2 is text1 converted to lower 
 

The concat() Method

concat() joins two or more strings:

Example

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

Example

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");
Note All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.

Extracting String Characters

There are 2 safe methods for extracting string characters:
  • charAt(position)
  • charCodeAt(position)

The charAt() Method

The charAt() method returns the character at a specified index (position) in a string:

Example

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:

Example

var str = "HELLO WORLD";

str.charCodeAt(0);         // returns 72
  


Accessing a String as an Array is Unsafe

You might have seen code like this, accessing a string as an array:
var str = "HELLO WORLD";

str[0];                   // returns H
This is unsafe and unpredictable:
  • It does not work in all browsers (not in IE5, IE6, IE7)
  • It makes strings look like arrays (but they are not)
  • str[0] = "H" does not give an error (but does not work)
If you want to read a string as an array, convert it to an array first.

Converting a String to an Array

A string can be converted to an array with the split() method:

Example

var txt = "a,b,c,d,e";   // String txt.split(",");          // Split on commas txt.split(" ");          // Split on spaces txt.split("|");          // Split on pipe 
 
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is "", the returned array will be an array of single characters:

Example

var txt = "Hello";       // String txt.split("");           // Split in characters
 
 
 
 
 
 
 
 
 
 
 

 

JavaScript Strings

JavaScript Strings

JavaScript strings are used for storing and manipulating text.

JavaScript Strings

A JavaScript string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:

Example

var carname = "Volvo XC60";
var carname = 'Volvo XC60'; 
 
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Example

var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
 

String Length

The length of a string is found in the built in property length:

Example

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

Special Characters

Because strings must be written within quotes, JavaScript will misunderstand this string:
var y = "We are the so-called "Vikings" from the north."
The string will be chopped to "We are the so-called ".
The solution to avoid this problem, is to use the \ escape character.
The backslash escape character turns special characters into string characters:

Example

var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north."
 
The escape character (\) can also be used to insert other special characters in a string.
This is the list of special characters that can be added to a text string with the backslash sign:
Code Outputs
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed

Breaking Long Code Lines

For best readability, programmers often like to avoid code lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

Example

document.getElementById("demo").innerHTML =
"Hello Dolly.";
 
You can also break up a code line within a text string with a single backslash:

Example

document.getElementById("demo").innerHTML = "Hello \
Dolly!"
; 
 
The safest (but a little slower) way to break a long string is to use string addition:

Example

document.getElementById("demo").innerHTML = "Hello" +
"Dolly!"; 
 
You cannot break up a code line with a backslash:

Example

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

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
 
When using the == equality operator, equal strings looks equal:

Example

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

// (x == y) is true because x and y have equal values 
 
When using the === equality 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 
 
Or even worse. Objects cannot be compared:

Example

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

// (x == y) is false because objects cannot be compared 
 

String Properties and Methods

Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
String methods are covered in next chapter.

String Properties

Property Description
constructor Returns the function that created the String object's prototype
length Returns the length of a string
prototype Allows you to add properties and methods to an object

String Methods

Method Description
charAt() Returns the character at the specified index (position)
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a copy of the joined strings
fromCharCode() Converts Unicode values to characters
indexOf() Returns the position of the first found occurrence of a specified value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
localeCompare() Compares two strings in the current locale
match() Searches a string for a match against a regular expression, and returns the matches
replace() Searches a string for a value and returns a new string with the value replaced
search() Searches a string for a value and returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
substr() Extracts a part of a string from a start position through a number of characters
substring() Extracts a part of a string between two specified positions
toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale
toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object
 
 
 
 
 
 
 
 
 
 
 

 

JavaScript Events

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

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:
<some-HTML-element some-event='some JavaScript'>
With double quotes:
<some-HTML-element some-event="some JavaScript">
In the following example, an onclick attribute (with code), is added to a button element:

Example

<button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>

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 it's own element (using this.innerHTML):

Example

<button onclick="this.innerHTML=Date()">The time is?</button>

Example

<button onclick="displayDate()">The time is?</button>
 

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


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 Scope

JavaScript Scope

Scope is the set of variables you have access to.

JavaScript Scope

In JavaScript, objects and functions, are also variables.
In JavaScript, scope is the set of variables, objects, and functions you have access to.
JavaScript has function scope: The scope changes inside functions.

Local JavaScript Variables

Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have local scope: They can only be accessed within the function.

Example

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

    // code here can use carName
} 
 
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.

Global JavaScript Variables

A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.

Example

var carName = " Volvo";

// code here can use carName
function myFunction() {

    // code here can use carName
} 
 

Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
This code example will declare carName as a global variable, even if it is executed inside a function.

Example

// code here can use carName
function myFunction() {
    carName = "Volvo";

    // code here can use carName
} 
 

The Lifetime of JavaScript Variables

The lifetime of a JavaScript variable starts when it is declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.

Function Arguments

Function arguments (parameters) work as local variables inside functions.

Global Variables in HTML

With JavaScript, the global scope is the complete JavaScript environment.
In HTML, the global scope is the window object: All global variables belong to the window object.

Example

// code here can use window.carName
function myFunction() {
    carName = "Volvo";
} 
 
 
 
 
 

 

JavaScript Functions

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 myFunction(p1, p2) {
    return p1 * p2;              // The function returns the product of p1 and p2 }

JavaScript Function Syntax

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: {}
function name(parameter1, parameter2, parameter3) {
    code to be executed
}
Function parameters are the names listed in the function definition.
Function arguments are the real values received by the function when it is invoked.
Inside the function, the arguments are used as local variables.
Note 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
  • Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.

Function Return

When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":

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 
 

Why Functions?

You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.

Example

Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(32);
 

The () Operator Invokes the Function

Using the example above, toCelsius refers to the function object, and toCelcius() refers to the function result.

Example

Accessing a function without () will return the function definition:
function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
 

Functions Used as Variables

In JavaScript, you can use functions the same way as you use variables.

Example

You can use:
var text = "The temperature is " + toCelsius(32) + " Centigrade";
Instead of:
var x = toCelsius(32);
var text = "The temperature is " + x + " Centigrade";
 
 
 

 

JavaScript Assignment

JavaScript Assignment

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.
Operator Example Same As
= x = y 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
The = assignment operator assigns a value to a variable.

Assignment

var x = 10;
 
The += assignment operator adds a value to a variable.

Assignment

var x = 10;
x += 5;
 
The -= assignment operator subtracts a value from a variable.

Assignment

var x = 10;
x -= 5;
 
The *= assignment operator multiplies a variable.

Assignment

var x = 10;
x *= 5;
 
The /= assignment divides a variable.

Assignment

var x = 10;
x /= 5;
 
The %= assignment operator assigns a remainder to a variable.

Assignment

var x = 10;
x %= 5;
 
 
 
 
 
 
 

JavaScript Arithmetic

JavaScript Arithmetic

A typical thing to do with numbers is arithmetic.

JavaScript Arithmetic Operators

Arithmetic operators perform arithmetic on numbers (literals or variables).
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement

Arithmetic Operations

A typical arithmetic operation operates on two numbers.
The two numbers can be literals:

Example

var x = 100 + 50; 
 
or variables:

Example

var x = a + b; 
 
or expressions:

Example

var x = (100 + 50) * a; 
 

Operators and Operands

The numbers (in an arithmetic operation) are called operands.
The operation (to be performed between the two operands) is defined by an operator.
Operand Operator Operand
100 + 50
The addition operator (+) adds numbers:

Adding

var x = 5;
var y = 2;
var z = x + y;
  

The subtraction operator (-) subtracts numbers.

Subtracting

var x = 5;
var y = 2;
var z = x - y; 
 
The multiplication operator (*) multiplies numbers.

Multiplying

var x = 5;
var y = 2;
var z = x * y; 
 
The division operator (/) divides numbers.

Dividing

var x = 5;
var y = 2;
var z = x / y; 
 
The modular operator (%) returns the division remainder.

Modulus

var x = 5;
var y = 2;
var z = x % y; 
 
The increment operator (++) increments numbers.

Incrementing

var x = 5;
x++;
var z = x;
 
The decrement operator (--) decrements numbers.

Decrementing

var x = 5;
x--;
var z = x;
  

Operator Precedence

Operator precedence describes the order in which operations are performed in an arithmetic expression.

Example

var x = 100 + 50 * 3; 
 
Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?
Is the addition or the multiplication done first?
As in traditional school mathematics, the multiplication is done first.
Multiplication (*) and division (/) have higher precedence than addition (+) and subraction (-).
And (as in school mathematics) the precedence can be changed by using parentheses:

Example

var x = (100 + 50) * 3; 
 
When using parentheses, the operations inside the parentheses are computed first.
When many operations have the same precedence (like addition and subtraction), they are computed from left to right:

Example

var x = 100 + 50 - 3; 
 

Arithmetic Operator Precedence

The following table lists JavaScript arithmetic operators, ordered from highest to lowest precedence:
Operator Precedence
( ) Expression grouping
++ -- Increment and decrement
* / % Multiplication, division, and modulo division
+ - Addition and subtraction
 
 
 
 
 
 
 
 
 

 

JavaScript Operators

JavaScript Operators

Example

Assign values to variables and add them together:
var x = 5;         // assign the value 5 to x var y = 2;         // assign the value 2 to y var z = x + y;     // assign the value 7 to z (x + y)


JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic on numbers (literals or variables).
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
The addition operator (+) adds numbers:

Adding

var x = 5;
var y = 2;
var z = x + y; 
 
The multiplication operator (*) multiplies numbers.

Multiplying

var x = 5;
var y = 2;
var z = x * y; 
 

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.
Operator Example Same As
= x = y 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
The assignment operator (=) assigns a value to a variable.

Assignment

var x = 10;
 
The addition assignment operator (+=) adds a value to a variable.

Assignment

var x = 10;
x += 5;
 

JavaScript String Operators

The + operator can also be used to add (concatenate) strings.
Note When used on strings, the + operator is called the concatenation operator.

Example

txt1 = "John";
txt2 = "Doe";
txt3 = txt1 + " " + txt2;
The result of txt3 will be:
John Doe
 
The += assignment operator can also be used to add (concatenate) strings:

Example

txt1 = "What a very ";
txt1 += "nice day";
The result of txt1 will be:
What a very nice day
 

Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a number and a string will return a string:

Example

x = 5 + 5;
y = "5" + 5;
z= "Hello" + 5;
The result of x, y, and z will be:
10
55
Hello5
 
The rule is: If you add a number and a string, the result will be a string!

JavaScript Comparison and Logical 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