You are on page 1of 26

NAME: ALRES C.

ARENA
PRENCISS ANN JUNI script. A simple syntax of your JavaScript will appear

as follows.
SYSTEM NAME: PASTE TOOL
UNIQUE NAME: PasteIt
<script ...>
WHAT IS JAVASCRIPT?
JAVASCRIPT is a programming language of HTML and JavaScript code
the Web.
</script>

EXAMPLES OF JAVASCRIPT FRAMEWORK


The script tag takes two important attributes
AngularJS -is a JavaScript-based open-
source front-end web application framework mainly
Language This attribute specifies what
maintained by Google and by a community of
individuals and corporations to address many of the scripting language you are using. Typically, its
challenges encountered in developing single-page
applications. value will be javascript. Although recent

versions of HTML (and XHTML, its successor)


Backbone.js- is a JavaScript framework with
a RESTful JSON interface and is based on the model have phased out the use of this attribute.
viewpresenter (MVP) application design paradigm.

Dojo Toolkit - is an open Type This attribute is what is now


source modular JavaScript library (or more recommended to indicate the scripting
specifically JavaScript toolkit) designed to ease the
rapid development of cross-platform, JavaScript/Ajax- language in use and its value should be set to
based applications and web sites.
"text/javascript".
Ember.js is an open-source JavaScript web
framework, based on the Modelview So your JavaScript segment will look like
viewmodel (MVVM) pattern. It allows developers to
create scalable single-page web applications[1] by
incorporating common idioms and best practices into <script language="javascript" type="text/javascript">
the framework.
JavaScript code
Enyo is an open source JavaScript
framework for cross-platform mobile, desktop, TV and </script>
web applications emphasizing object-oriented
encapsulation and modularity.[1] Initially developed
by Palm, which was later acquired by Hewlett- document.write function can be used to write text,
Packard and then released under an Apache 2.0 HTML, or both. Take a look at the following code.
license.[2] It is sponsored by LG Electronics and Hewlett-
Packard.
<html>
JS SYNTAX
<body>
JavaScript can be implemented using JavaScript

statements that are placed within the <script>... <script language="javascript"


type="text/javascript">
</script> HTML tags in a web page.

document.write("Hello World!")
You can place the <script> tags, containing your
</script>
JavaScript, anywhere within you web page, but it is

normally recommended that you should keep it within </body>


the <head> tags.
</html>

The <script> tag alerts the browser program to start


This code will produce the following result
interpreting all the text between these tags as a
First Page";
Hello World!
document.getElementById("myP").innerHTML = "My
first paragraph.";
JS STATEMENT
JavaScript statements are "instructions" to be
"executed" by the web browser.
JS VARIABLES
This statement tells the browser to write "Hello Dolly." JavaScript variables are containers for storing data
inside an HTML element with id="demo": values.

Example In this example, x, y, and z, are variables:

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

var x = 5;
var y = 6;
JS COMMENT var z = x + y;
JavaScript comments can be used to explain JavaScript
code, and to make it more readable. Try it Yourself

From the example above, you can expect:


JavaScript comments can also be used to prevent
execution, when testing alternative code.
x stores the value 5
Single Line Comments
y stores the value 6
Single line comments start with //.
z stores the value 11
Any text between // and the end of the line will be
ignored by JavaScript (will not be executed).

This example uses a single-line comment before each


JS OPERATORS
code line:
JavaScript Arithmetic Operators
Example
Arithmetic operators are used to perform arithmetic on
// Change heading: numbers:
document.getElementById("myH").innerHTML = "My
First Page";
JavaScript Assignment Operators
// Change paragraph:
document.getElementById("myP").innerHTML = "My Assignment operators assign values to JavaScript
first paragraph."; variables.

Multi-line Comments
JavaScript String Operators
Multi-line comments start with /* and end with */.
The + operator can also be used to add (concatenate)
Any text between /* and */ will be ignored by strings.
JavaScript.
JavaScript Comparison Operators
This example uses a multi-line comment (a comment JavaScript Logical Operators
block) to explain the code:

Example JavaScript Type Operators

/* JavaScript Bitwise Operators


The code below will change
Bit operators work on 32 bits numbers.
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My JS ARITHMETIC
A typical thing to do with numbers is arithmetic.
-= x -= y x=xy

JavaScript Arithmetic Operators *= x *= y x=x*y

Arithmetic operators perform arithmetic on numbers /= x /= y x=x/y


(literals or variables).
%= x %= x=x%y
y
Op Descri
era ption <<= x <<= x = x <<
tor y y

+ Additio >>= x >>= x = x >>


n y y

- Subtra >>>= x x=x


ction >>>= >>> y
y
* Multipl
ication &= x &= y x=x&y

/ Divisio ^= x ^= y x=x^y
n
|= x |= y x=x|y
% Modul
us **= x **= x = x ** y
y
++ Increm
ent

-- Decre Assignment Examples


ment
The = assignment operator assigns a value to a
variable.

Assignment

Arithmetic Operations
var x = 10;
A typical arithmetic operation operates on two
Try it Yourself
numbers.
The += assignment operator adds a value to a
The two numbers can be literals: variable.

Example Assignment

var x = 100 + 50; var x = 10;


x += 5;
Try it Yourself

JS ASSIGNMENT JS DATA

Assignment operators assign values to JavaScript


variables. JavaScript Data Types

JavaScript variables can hold many data types:


Opera Exam Same As numbers, strings, objects and more:
tor ple
var length = 16; // Number
= x=y x=y var lastName = "Johnson"; // String
var x = {firstName:"John", lastName:"Doe"}; //
+= x += y x=x+y Object
Array indexes are zero-based, which means the first
item is [0], second is [1], and so on.

JavaScript Strings
You will learn more about arrays later in this tutorial.
A string (or a text string) is a series of characters like
"John Doe".

Strings are written with quotes. You can use single or


double quotes: JavaScript Objects

JavaScript objects are written with curly braces.


Example
Object properties are written as name:value pairs,
var carName = "Volvo XC60"; // Using double quotes separated by commas.
var carName = 'Volvo XC60'; // Using single quotes

. Example

JavaScript Numbers var person = {firstName:"John", lastName:"Doe",


age:50, eyeColor:"blue"};
JavaScript has only one type of numbers.

Numbers can be written with, or without decimals: Try it Yourself

The object (person) in the example above has 4


Example properties: firstName, lastName, age, and eyeColor.

var x1 = 34.00; // Written with decimals You will learn more about objects later in this tutorial.
var x2 = 34; // Written without decimals

JavaScript Booleans
The typeof Operator
Booleans can only have two values: true or false.
You can use the JavaScript typeof operator to find the
type of a JavaScript variable.
Example

The typeof operator returns the type of a variable or


var x = true;
an expression:
var y = false;

Booleans are often used in conditional testing. Example

You will learn more about conditional testing later in typeof "" // Returns "string"
this tutorial. typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"

Try it Yourself

JavaScript Arrays

JavaScript arrays are written with square brackets. JS FUNCTIONS


A JavaScript function is a block of code designed to
perform a particular task.
Array items are separated by commas.

A JavaScript function is executed when "something"


The following code declares (creates) an array called
invokes it (calls it).
cars, containing three items (car names):

Example

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


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

JS OBJECTS
Try it Yourself
Real Life Objects, Properties, and Methods

In real life, a car is an object.

JavaScript Function Syntax A car has properties like weight and color,
and methods like start and stop:
A JavaScript function is defined with
the function keyword, followed by a name, followed
by parentheses (). All cars have the same properties, but the property
values differ from car to car.
Function names can contain letters, digits,
underscores, and dollar signs (same rules as variables). All cars have the same methods, but the methods are
performed at different times.
The parentheses may include parameter names
separated by commas:
(parameter1, parameter2, ...)

JavaScript Objects
The code to be executed, by the function, is placed
inside curly brackets: {} You have already learned that JavaScript variables are
containers for data values.
function name(parameter1, parameter2, parameter3) {
code to be executed This code assigns a simple value (Fiat) to
} a variable named car:

Function parameters are the names listed in the


function definition. var car = "Fiat";

Try it Yourself
Function arguments are the real values received by
the function when it is invoked. Objects are variables too. But objects can contain
many values.
Inside the function, the arguments (the parameters)
behave as local variables. This code assigns many values (Fiat, 500, white) to
a variable named car:
A Function is much the same as a Procedure or a
Subroutine, in other programming languages. var car = {type:"Fiat", model:"500", color:"white"};

Try it Yourself

Example JS SCOPE
Scope is the set of variables you have access to.
Calculate the product of two numbers, and return the
result: Local JavaScript Variables

Variables declared within a JavaScript function,


var x = myFunction(4, 3); // Function is called,
become LOCAL to the function.
return value will end up in x

function myFunction(a, b) { Local variables have local scope: They can only be
return a * b; // Function returns the product accessed within the function.
of a and b
} Example

// code here can not use carName


The result in x will be:
function myFunction() {
12 var carName = "Volvo";
// code here can use carName
onload The browser has finished loading
the page
}

Try it Yourself

Global JavaScript Variables JS STRINGS

A variable declared outside a function, JavaScript strings are used for storing and manipulating
becomes GLOBAL. text.

A global variable has global scope: All scripts and


functions on a web page can access it.

JavaScript Strings
Example
A JavaScript string simply stores a series of characters
var carName = " Volvo"; like "John Doe".

// code here can use carName A string can be any text inside quotes. You can use
single or double quotes:
function myFunction() {
Example
// code here can use carName

} var carname = "Volvo XC60";


var carname = 'Volvo XC60';
Try it Yourself
Try it Yourself

JS EVENTS Special Characters


HTML events are "things" that happen to HTML
elements. Co Outputs
de
Example
\' single quote
<button onclick="document.getElementById('demo').in
\" double quote
nerHTML = Date()">The time is?</button>

Try it Yourself \\ backslash

In the example above, the JavaScript code changes the


content of the element with id="demo".
Co Outputs
Common HTML Events de
Here is a list of some common HTML events:
\b Backspace

Event Description \r Carriage Return

onchange An HTML element has been \f Form Feed


changed
\t Horizontal Tabulator
onclick The user clicks an HTML element
\v Vertical Tabulator
onmouseo The user moves the mouse over
ver an HTML element

onmouseo The user moves the mouse away Breaking Long Code Lines
ut from an HTML element
Example
onkeydow The user pushes a keyboard key
n document.getElementById("demo").innerHTML =
"Hello Dolly.";
Try it Yourself slice(start, end)

JS STRING METHODS substring(start, end)

String methods help you to work with strings. substr(start, length)

String Length

The length property returns the length of a string:


The slice() Method
Example
slice() extracts a part of a string and returns the
extracted part in a new string.
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
The method takes 2 parameters: the starting index
Try it Yourself (position), and the ending index (position).

Example

var str = "Apple, Banana, Kiwi";


Finding a String in a String var res = str.slice(7, 13);
The indexOf() method returns the index of (the The result of res will be:
position of) the first occurrence of a specified text in a
string:
Banana

Example Try it Yourself

The substring() Method


var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate"); substring() is similar to slice().
Try it Yourself
The difference is that substring() cannot accept
The lastIndexOf() method returns the index of negative indexes.
the last occurrence of a specified text in a string:
Example
Example
var str = "Apple, Banana, Kiwi";
var str = "Please locate where 'locate' occurs!"; var res = str.substring(7, 13);
var pos = str.lastIndexOf("locate");
The result of res will be:
Try it Yourself
Banana

Try it Yourself

Searching for a String in a String If you omit the second parameter, substring() will slice
out the rest of the string.
The search() method searches a string for a specified
value and returns the position of the match:

Example
The substr() Method
var str = "Please locate where 'locate' occurs!";
substr() is similar to slice().
var pos = str.search("locate");

Try it Yourself The difference is that the second parameter specifies


the length of the extracted part.

Example
Extracting String Parts
var str = "Apple, Banana, Kiwi";
There are 3 methods for extracting a part of a string: var res = str.substr(7, 6);
The result of res will be: All string methods return a new string. They don't
modify the original string.
Banana Formally said: Strings are immutable: Strings cannot be
changed, only replaced.
Try it Yourself

Extracting String Characters


Replacing String Content
There are 2 safe methods for extracting string
The replace() method replaces a specified value with
characters:
another value in a string:

charAt(position)
Example

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

Try it Yourself
The charAt() Method
Converting to Upper and Lower Case
The charAt() method returns the character at a
A string is converted to upper case specified index (position) in a string:
with toUpperCase():
Example
Example
var str = "HELLO WORLD";
var text1 = "Hello World!"; // String str.charAt(0); // returns H
var text2 = text1.toUpperCase(); // text2 is text1
converted to upper Try it Yourself

Try it Yourself

A string is converted to lower case


with toLowerCase(): The charCodeAt() Method

Example The charCodeAt() method returns the unicode of the


character at a specified index in a string:
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 Example
converted to lower
var str = "HELLO WORLD";
The concat() Method

concat() joins two or more strings: str.charCodeAt(0); // returns 72

Converting a String to an Array


Example
A string can be converted to an array with
the split() method:
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ", text2); Example

Try it Yourself var txt = "a,b,c,d,e"; // String


The concat() method can be used instead of the plus txt.split(","); // Split on commas
operator. These two lines do the same: txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe

Example Try it Yourself

var text = "Hello" + " " + "World!";


var text = "Hello".concat(" ", "World!");
JS NUMBERS
JavaScript has only one type of number. Example

Numbers can be written with, or without, decimals. var myNumber = 128;


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

JavaScript Numbers
Try it Yourself
JavaScript numbers can be written with, or without
decimals:

Example
Infinity
var x = 34.00; // A number with decimals
Infinity (or -Infinity) is the value JavaScript will return if
var y = 34; // A number without decimals
you calculate a number outside the largest possible
Extra large or extra small numbers can be written with number.
scientific (exponent) notation:
Example
Example
var myNumber = 2;
var x = 123e5; // 12300000 while (myNumber != Infinity) { // Execute until
var y = 123e-5; // 0.00123 Infinity
myNumber = myNumber * myNumber;
Precision }

Integers (numbers without a period or exponent Try it yourself


notation) are considered accurate up to 15 digits.
Division by 0 (zero) also generates Infinity:
Example
NaN - Not a Number
var x = 999999999999999; // x will be NaN is a JavaScript reserved word indicating that a
999999999999999 number is not a legal number.
var y = 9999999999999999; // y will be
10000000000000000
Trying to do arithmetic with a non-numeric string will
Try it Yourself result in NaN (Not a Number):

Example

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


Hexadecimal

JavaScript interprets numeric constants as hexadecimal


if they are preceded by 0x.

Example
Numbers Can be Objects

var x = 0xFF; // x will be 255 Normally JavaScript numbers are primitive values
created from literals: var x = 123
Try it Yourself

Never write a number with a leading zero (like 07). But numbers can also be defined as objects with the
Some JavaScript versions interpret numbers as octal if keyword new: var y = new Number(123)
they are written with a leading zero.
Example
By default, JavaScript displays numbers as base 10
decimals. var x = 123;
var y = new Number(123);
But you can use the toString() method to output
numbers as base 16 (hex), base 8 (octal), or base 2 // typeof x returns number
(binary). // typeof y returns object
Try it yourself

The toPrecision() Method


JS NUMBER METHODS
toPrecision() returns a string, with a number written
The toString() Method with a specified length:

toString() returns a number as a string.


Example

All number methods can be used on any type of


numbers (literals, variables, or expressions): var x = 9.656;
x.toPrecision(); // returns 9.656
x.toPrecision(2); // returns 9.7
Example x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600
var x = 123;
x.toString(); // returns 123 from variable x Try it Yourself
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression
100 + 23

Try it Yourself The valueOf() Method

valueOf() returns a number as a number.

Example
The toExponential() Method

toExponential() returns a string, with a number var x = 123;


rounded and written using exponential notation. x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression
A parameter defines the number of characters behind 100 + 23
the decimal point:
Try it Yourself
Example
In JavaScript, a number can be a primitive value
(typeof = number) or an object (typeof = object).
var x = 9.656;
x.toExponential(2); // returns 9.66e+0
The valueOf() method is used internally in JavaScript to
x.toExponential(4); // returns 9.6560e+0
convert Number objects to primitive values.
x.toExponential(6); // returns 9.656000e+0

Try it yourself There is no reason to use it in your code.

The parameter is optional. If you don't specify it,


JavaScript will not round the number. All JavaScript data types have a valueOf() and a
toString() method.

The toFixed() Method


Converting Variables to Numbers
toFixed() returns a string, with the number written
with a specified number of decimals: There are 3 JavaScript methods that can be used to
convert variables to numbers:

Example
The Number() method
var x = 9.656;
x.toFixed(0); // returns 10 The parseInt() method
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560 The parseFloat() method
x.toFixed(6); // returns 9.656000
These methods are not number methods,
Try it yourself
but global JavaScript methods.
toFixed(2) is perfect for working with money.
Global Methods

JavaScript global methods can be used on all JavaScript


data types. Number Properties

These are the most relevant methods, when working Property Description
with numbers:
MAX_VALUE Returns the largest number
possible in JavaScript
Method Description
MIN_VALUE Returns the smallest number
Number() Returns a number, converted from possible in JavaScript
its argument.
NEGATIVE_INFI Represents negative infinity
parseFloa Parses its argument and returns a NITY (returned on overflow)
t() floating point number
NaN Represents a "Not-a-Number"
parseInt( Parses its argument and returns value
) an integer
POSITIVE_INFINI Represents infinity (returned on
TY overflow)

Example
The parseInt() Method

parseInt() parses a string and returns a whole var x = Number.MAX_VALUE;


number. Spaces are allowed. Only the first number is
returned: Try it yourself

Number properties belongs to the JavaScript's number


Example object wrapper called Number.

parseInt("10"); // returns 10 These properties can only be accessed


parseInt("10.33"); // returns 10 as Number.MAX_VALUE.
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
Using myNumber.MAX_VALUE, where myNumber is a
parseInt("years 10"); // returns NaN
variable, expression, or value, will return undefined:
Try it yourself
Example
If the number cannot be converted, NaN (Not a
Number) is returned.
var x = 6;
var y = x.MAX_VALUE; // y becomes undefined

JS MATH OBJECT
The parseFloat() Method
The JavaScript Math object allows you to perform
parseFloat() parses a string and returns a number.
mathematical tasks on numbers.
Spaces are allowed. Only the first number is returned:

Example
Example

Math.PI; // returns 3.141592653589793


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

Try it yourself
Math.round()
If the number cannot be converted, NaN (Not a
Math.round(x) returns the value of x rounded to its
Number) is returned.
nearest integer:
Example Example

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


Math.round(4.4); // returns 4
Try it Yourself
Try it Yourself

Math.sin()
Math.pow()
Math.sin(x) returns the sine (a value between -1 and 1)
Math.pow(x, y) returns the value of x to the power of y: of the angle x (given in radians).

Example If you want to use degrees instead of radians, you have


to convert degrees to radians:
Math.pow(8, 2); // returns 64
Angle in radians = Angle in degrees x PI / 180.
Try it Yourself
Example

Math.sin(90 * Math.PI / 180); // returns 1 (the sine of


Math.sqrt() 90 degrees)

Math.sqrt(x) returns the square root of x: Try it Yourself

Example

Math.sqrt(64); // returns 8 Math.cos()


Try it Yourself Math.cos(x) returns the cosine (a value between -1 and
1) of the angle x (given in radians).

If you want to use degrees instead of radians, you have


to convert degrees to radians:
Math.abs()

Math.abs(x) returns the absolute (positive) value of x: Angle in radians = Angle in degrees x PI / 180.

Example Example

Math.abs(-4.7); // returns 4.7 Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0


degrees)
Try it Yourself
Try it Yourself

Math.ceil()
Math.min() and Math.max()
Math.ceil(x) returns the value of x rounded up to its
nearest integer: Math.min() and Math.max() can be used to find the
lowest or highest value in a list of arguments:
Example
Example
Math.ceil(4.4); // returns 5
Math.min(0, 150, 30, 20, -8, -200); // returns -200
Try it Yourself
Try it Yourself
Math.floor()

Math.floor(x) returns the value of x rounded down to Example


its nearest integer:
Math.max(0, 150, 30, 20, -8, -200); // returns 150
acos(x) Returns the arccosine of x, in
Try it Yourself radians

asin(x) Returns the arcsine of x, in radians

atan(x) Returns the arctangent of x as a


Math.random() numeric value between -PI/2 and
PI/2 radians
Math.random() returns a random number between 0
(inclusive), and 1 (exclusive): atan2( Returns the arctangent of the
y, x) quotient of its arguments
Example
ceil(x) Returns the value of x rounded up
to its nearest integer
Math.random(); // returns a random number

Try it Yourself cos(x) Returns the cosine of x (x is in


radians)
You will learn more about Math.random() in the next
chapter of this tutorial. exp(x) Returns the value of Ex

floor(x) Returns the value of x rounded


down to its nearest integer

Math Properties (Constants) log(x) Returns the natural logarithm


(base E) of x
JavaScript provides 8 mathematical constants that can
be accessed with the Math object:
max(x, Returns the number with the
y, z, ..., highest value
Example n)

Math.E // returns Euler's number min(x, Returns the number with the
Math.PI // returns PI y, z, ..., lowest value
Math.SQRT2 // returns the square root of 2 n)
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2 pow(x, Returns the value of x to the
Math.LN10 // returns the natural logarithm of 10 y) power of y
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E rando Returns a random number
m() between 0 and 1
Try it Yourself
round( Returns the value of x rounded to
x) its nearest integer

sin(x) Returns the sine of x (x is in


Math Constructor radians)
Unlike other global objects, the Math object has no
sqrt(x) Returns the square root of x
constructor. Methods and properties are static.
tan(x) Returns the tangent of an angle
All methods and properties (constants) can be used
without creating a Math object first.

JS RANDOM

Math Object Methods Math.random()

Metho Description Math.random() returns a random number between 0


d (inclusive), and 1 (exclusive):

abs(x) Returns the absolute value of x Example

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


Try it Yourself This JavaScript function always returns a random
number between min (included) and max (excluded):
Math.random() always returns a number lower than 1.
Example

function getRndInteger(min, max) {


JavaScript Random Integers return Math.floor(Math.random() * (max - min) ) +
min;
Math.random() used with Math.floor() can be used to }
return random integers.
Try it Yourself
Example This JavaScript function always returns a random
number between min and max (both included):
Math.floor(Math.random() * 10); // returns a number
between 0 and 9 Example
Try it Yourself
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) )
Example
+ min;
}
Math.floor(Math.random() * 11); // returns a number
between 0 and 10

Try it Yourself
JS DATES
Example
The Date object lets you work with dates (years,
Math.floor(Math.random() * 100); // returns a number months, days, hours, minutes, seconds, and
between 0 and 99 milliseconds)

Try it Yourself

Example
JavaScript Date Formats
Math.floor(Math.random() * 101); // returns a number A JavaScript date can be written as a string:
between 0 and 100

Try it Yourself Thu Mar 09 2017 15:19:31 GMT+0800 (Taipei


Standard Time)
Example
or as a number:
Math.floor(Math.random() * 10) + 1; // returns a
number between 1 and 10 1489043971977

Try it Yourself Dates written as numbers, specifies the number of


milliseconds since January 1, 1970, 00:00:00.
Example

Math.floor(Math.random() * 100) + 1; // returns a


number between 1 and 100
Displaying Dates
Try it Yourself
In this tutorial we use a script to display dates inside a
<p> element with id="demo":

Example
A Proper Random Function

As you can see from the examples above, it might be a <p id="demo"></p>
good idea to create a proper random function to use for
all random integer purposes. <script>
document.getElementById("demo").innerHTML =
Date(); JavaScript ISO Dates
</script>
ISO 8601 is the international standard for the
Try it Yourself representation of dates and times.

Time Zones
The ISO 8601 syntax (YYYY-MM-DD) is also the
When setting a date, without specifying the time zone, preferred JavaScript date format:
JavaScript will use the browser's time zone.
Example (Complete date)
When getting a date, without specifying the time zone,
the result is converted to the browser's time zone var d = new Date("2015-03-25");

Try it Yourself
JS DATE FORMATS

JavaScript Date Input


ISO Dates (Year and Month)
There are generally 4 types of JavaScript date input
ISO dates can be written without specifying the day
formats:
(YYYY-MM):

Typ Example Example


e
var d = new Date("2015-03");
ISO "2015-03-25" (The International
Dat Standard) Try it Yourself
e
Time zones will vary the result above between
Sho "03/25/2015" February 28 and March 01.
rt
Dat
e

Lon "Mar 25 2015" or "25 Mar 2015" ISO Dates (Only Year)
g ISO dates can be written without month and day
Dat (YYYY):
e

Full "Wednesday March 25 2015" Example


Dat
e var d = new Date("2015");

The ISO format follows a strict standard in JavaScript. Try it Yourself

Time zones will vary the result above between


The other formats are not so well defined and might be
December 31 2014 and January 01 2015.
browser specific.

ISO Dates (Date-Time)


JavaScript Date Output
ISO dates can be written with added hours, minutes,
Independent of input format, JavaScript will (by default)
and seconds (YYYY-MM-DDTHH:MM:SSZ):
output dates in full text string format:

Example
Wed Mar 25 2015 08:00:00 GMT+0800 (Taipei Standard
Time)
var d = new Date("2015-03-25T12:00:00Z");

Try it Yourself

Date and time is separated with a capital T.

UTC time is defined with a capital letter Z.


If you want to modify the time relative to UTC, remove JavaScript will ignore errors both in the day name and
the Z and add +HH:MM or -HH:MM instead: in the time parentheses:

Example

var d = new Date("2015-03-25T12:00:00-06:30"); JS DATE METHODS

Try it Yourself Date methods let you get and set date values (years,
months, days, hours, minutes, seconds, milliseconds)
UTC (Universal Time Coordinated) is the same as GMT
(Greenwich Mean Time).

Omitting T or Z in a date-time string can give different


result in different browser. Date Get Methods

Get methods are used for getting a part of a date. Here


are the most common (alphabetically):

Time Zones
Method Description
When setting a date, without specifying the time zone,
JavaScript will use the browser's time zone. getDate() Get the day as a number (1-31)

When getting a date, without specifying the time zone, getDay() Get the weekday as a number (0-
the result is converted to the browser's time zone. 6)

getFullYear() Get the four digit year (yyyy)


In other words: If a date/time is created in GMT
(Greenwich Mean Time), the date/time will be
getHours() Get the hour (0-23)
converted to CDT (Central US Daylight Time) if a user
browses from central US.
getMillisecon Get the milliseconds (0-999)
ds()
JavaScript Short Dates.
getMinutes() Get the minutes (0-59)
Short dates are written with an "MM/DD/YYYY" syntax
like this:
getMonth() Get the month (0-11)

Example getSeconds() Get the seconds (0-59)

var d = new Date("03/25/2015"); getTime() Get the time (milliseconds since


January 1, 1970)
Try it Yourself

JavaScript Long Dates.

Long dates are most often written with a "MMM DD


YYYY" syntax like this:
The getTime() Method

Example getTime() returns the number of milliseconds since


January 1, 1970:
var d = new Date("Mar 25 2015");
Example
Try it Yourself

JavaScript Full Date <script>


var d = new Date();
JavaScript will accept date strings in "full JavaScript document.getElementById("demo").innerHTML =
format": d.getTime();
</script>
Example
Try it Yourself
var d = new Date("Wed Mar 25 2015 09:56:24
GMT+0100 (W. Europe Standard Time)");

Try it Yourself
The getFullYear() Method
setFullYear() Set the year (optionally month and
getFullYear() returns the year of a date as a four digit day)
number:
setHours() Set the hour (0-23)
Example
setMillisecon Set the milliseconds (0-999)
ds()
<script>
var d = new Date(); setMinutes() Set the minutes (0-59)
document.getElementById("demo").innerHTML =
d.getFullYear(); setMonth() Set the month (0-11)
</script>

Try it Yourself setSeconds() Set the seconds (0-59)

setTime() Set the time (milliseconds since


January 1, 1970)

The getDay() Method

getDay() returns the weekday as a number (0-6):


The setFullYear() Method
Example
setFullYear() sets a date object to a specific date. In
<script> this example, to January 14, 2020:
var d = new Date();
document.getElementById("demo").innerHTML = Example
d.getDay();
</script> <script>
var d = new Date();
Try it Yourself
d.setFullYear(2020, 0, 14);
In JavaScript, the first day of the week (0) means document.getElementById("demo").innerHTML = d;
"Sunday", even if some countries in the world consider </script>
the first day of the week to be "Monday"
Try it Yourself

You can use an array of names, and getDay() to return


the weekday as a name:

Example The setDate() Method

setDate() sets the day of the month (1-31):


<script>
var d = new Date();
var days = Example
["Sunday","Monday","Tuesday","Wednesday","Thursday
","Friday","Saturday"]; <script>
document.getElementById("demo").innerHTML = var d = new Date();
days[d.getDay()]; d.setDate(20);
</script> document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself
Try it Yourself

The setDate() method can also be used to add days to


a date:
Date Set Methods
Example
Set methods are used for setting a part of a date. Here
are the most common (alphabetically):
<script>
var d = new Date();
Method Description d.setDate(d.getDate() + 50);
document.getElementById("demo").innerHTML = d;
setDate() Set the day as a number (1-31) </script>
Try it Yourself JavaScript counts months from 0 to 11. January is 0.
December is 11.
If adding days, shifts the month or year, the changes
are handled automatically by the Date object.

UTC Date Methods

Date Input - Parsing Dates UTC date methods are used for working UTC dates
(Universal Time Zone dates):
If you have a valid date string, you can use
the Date.parse() method to convert it to milliseconds.
Method Description
Date.parse() returns the number of milliseconds
between the date and January 1, 1970: getUTCDate() Same as getDate(), but returns the
UTC date
Example
getUTCDay() Same as getDay(), but returns the
UTC day
<script>
var msec = Date.parse("March 21, 2012");
getUTCFullYear() Same as getFullYear(), but returns
document.getElementById("demo").innerHTML = msec;
the UTC year
</script>

Try it Yourself getUTCHours() Same as getHours(), but returns


the UTC hour
You can then use the number of milliseconds
to convert it to a date object: getUTCMillisecon Same as getMilliseconds(), but
ds() returns the UTC milliseconds
Example
getUTCMinutes() Same as getMinutes(), but returns
the UTC minutes
<script>
var msec = Date.parse("March 21, 2012");
getUTCMonth() Same as getMonth(), but returns
var d = new Date(msec);
the UTC month
document.getElementById("demo").innerHTML = d;
</script>
getUTCSeconds() Same as getSeconds(), but returns
Try it Yourself the UTC seconds

JS ARRAY

Compare Dates JavaScript arrays are used to store multiple values in a


single variable.
Dates can easily be compared.

Example
The following example compares today's date with
January 14, 2100:
var cars = ["Saab", "Volvo", "BMW"];
Example Try it Yourself

var today, someday, text;


today = new Date(); JS ARRAY METHODS
someday = new Date();
someday.setFullYear(2100, 0, 14); The strength of JavaScript arrays lies in the array
methods.
if (someday > today) {
text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
} Converting Arrays to Strings
document.getElementById("demo").innerHTML = text;
The JavaScript method toString() converts an array to
Try it Yourself a string of (comma separated) array values.
Example var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi")
var fruits = ["Banana", "Orange", "Apple", "Mango"]; to fruits
document.getElementById("demo").innerHTML =
Try it Yourself
fruits.toString();
The push() method returns the new array length:
Result
Example
Banana,Orange,Apple,Mango
var fruits = ["Banana", "Orange", "Apple", "Mango"];
Try it Yourself
var x = fruits.push("Kiwi"); // the value of x is 5
The join() method also joins all array elements into a
Try it Yourself
string.
Shifting Elements
It behaves just like toString(), but in addition you can
Shifting is equivalent to popping, working on the first
specify the separator:
element instead of the last.

Example
The shift() method removes the first array element
and "shifts" all other elements to a lower index.
var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML =
Example
fruits.join(" * ");

var fruits = ["Banana", "Orange", "Apple", "Mango"];


Result
fruits.shift(); // Removes the first element
"Banana" from fruits
Banana * Orange * Apple * Mango
Try it Yourself
Try it Yourself
The shift() method returns the string that was "shifted
Popping out":
The pop() method removes the last element from an
array: Example

Example var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.shift(); // Returns "Banana"
var fruits = ["Banana", "Orange", "Apple", "Mango"]; Try it Yourself
fruits.pop(); // Removes the last element
("Mango") from fruits The unshift() method adds a new element to an array
(at the beginning), and "unshifts" older elements:
Try it Yourself

The pop() method returns the value that was "popped Example
out":
var fruits = ["Banana", "Orange", "Apple", "Mango"];
Example fruits.unshift("Lemon"); // Adds a new element
"Lemon" to fruits
var fruits = ["Banana", "Orange", "Apple", "Mango"]; Try it Yourself
var x = fruits.pop(); // the value of x is "Mango"
The unshift() method returns the new array length.
Try it Yourself

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];


Pushing fruits.unshift("Lemon"); // Returns 5

The push() method adds a new element to an array (at Try it Yourself
the end):

Example
Changing Elements The second parameter (0) defines how
many elements should be removed.
Array elements are accessed using their index
number:
The rest of the parameters ("Lemon" , "Kiwi") define
the new elements to be added.
Array indexes start with 0. [0] is the first array
element, [1] is the second, [2] is the third ...

Example
Using splice() to Remove Elements
var fruits = ["Banana", "Orange", "Apple", "Mango"];
With clever parameter setting, you can use splice() to
fruits[0] = "Kiwi"; // Changes the first element of
remove elements without leaving "holes" in the array:
fruits to "Kiwi"

Try it Yourself Example


The length property provides an easy way to append a
new element to an array: var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of
fruits
Example
Try it Yourself
var fruits = ["Banana", "Orange", "Apple", "Mango"];
The first parameter (0) defines the position where new
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to
elements should be added (spliced in).
fruit

Try it Yourself The second parameter (1) defines how


many elements should be removed.

The rest of the parameters are omitted. No new


elements will be added.
Deleting Elements

Since JavaScript arrays are objects, elements can be


deleted by using the JavaScript operator delete:

Joining Arrays
Example
The concat() method creates a new array by
var fruits = ["Banana", "Orange", "Apple", "Mango"]; concatenating two arrays:
delete fruits[0]; // Changes the first element in
fruits to undefined Example
Try it Yourself
var myGirls = ["Cecilie", "Lone"];
Using delete may leave undefined holes in the array. var myBoys = ["Emil", "Tobias","Linus"];
Use pop() or shift() instead. var myChildren = myGirls.concat(myBoys); //
Concatenates (joins) myGirls and myBoys

Try it Yourself

The concat() method can take any number of array


Splicing an Array arguments:
The splice() method can be used to add new items to
an array: Example

Example var arr1 = ["Cecilie", "Lone"];


var arr2 = ["Emil", "Tobias","Linus"];
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var arr3 = ["Robin", "Morgan"];
fruits.splice(2, 0, "Lemon", "Kiwi"); var myChildren = arr1.concat(arr2, arr3); //
Concatenates arr1 with arr2 and arr3
Try it Yourself
Try it Yourself
The first parameter (2) defines the position where new
elements should be added (spliced in).
Slicing an Array The Boolean() Function

The slice() method slices out a piece of an array into a You can use the Boolean() function to find out if an
new array. expression (or a variable) is true:

This example slices out a part of an array starting from Example


array element 1 ("Orange"):
Boolean(10 > 9) // returns true
Example
Try it Yourself
var fruits = Or even easier:
["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
Example
Try it Yourself
(10 > 9) // also returns true
Automatic toString() 10 > 9 // also returns true
JavaScript will automatically convert an array to a Try it Yourself
string when a primitive value is expected. These two
examples will produce the same result: Comparisons and Conditions

The chapter JS Comparisons gives a full overview of


Example
comparison operators.

var fruits = ["Banana", "Orange", "Apple", "Mango"];


The chapter JS Conditions gives a full overview of
document.getElementById("demo").innerHTML =
conditional statements.
fruits.toString();

Here are some examples:

Opera Descript Example


Sorting Arrays
tor ion
Sorting arrays are covered in the next chapter of this
tutorial. == equal to if (day == "Monday")

> greater if (salary > 9000)


than
JS BOOLEANS
< less than if (age < 18)
A JavaScript Boolean represents one of two JS COMPARISON AND LOGICAL OPERATORS
values: true or false.
Comparison and Logical operators are used to test
for true or false.

Boolean Values

Very often, in programming, you will need a data type Comparison Operators
that can only have one of two values, like
Comparison operators are used in logical statements to
YES / NO determine equality or difference between variables or
values.
ON / OFF
Given that x = 5, the table below explains the
comparison operators:
TRUE / FALSE

For this, JavaScript has a Boolean data type. It can Opera Descript Compar Returns
only take the values true or false. tor ion ing

== equal to x == 8 false
x == 5 true false

x == true ! not !(x == y) is true


"5"

=== equal x === 5 true


value and
equal x === false Conditional (Ternary) Operator
type "5"
JavaScript also contains a conditional operator that
!= not equal x != 8 true assigns a value to a variable based on some condition.

!== not equal x !== 5 false Syntax


value or
not equal x !== true variablename = (condition) ? value1:value2
type "5"
Example
x !== true
8
var voteable = (age < 18) ? "Too young":"Old enough";
> greater x>8 false
Try it Yourself
than

< less than x<8 true


JS IF-ELSE STATEMENT
>= greater x >= 8 false Conditional statements are used to perform different
than or actions based on different conditions.
equal to
Conditional Statements
<= less than x <= 8 true
or equal Very often when you write code, you want to perform
to different actions for different decisions.

You can use conditional statements in your code to do


this.

How Can it be Used


In JavaScript we have the following conditional
Comparison operators can be used in conditional statements:
statements to compare values and take action
depending on the result: Use if to specify a block of code to be
executed, if a specified condition is true
if (age < 18) text = "Too young";
Use else to specify a block of code to be
You will learn more about the use of conditional executed, if the same condition is false
statements in the next chapter of this tutorial.
Use else if to specify a new condition to test, if
Logical Operators the first condition is false
Logical operators are used to determine the logic
between variables or values. Use switch to specify many alternative blocks
of code to be executed
Given that x = 6 and y = 3, the table below explains
the logical operators:

Opera Descript Example The if Statement


tor ion
Use the if statement to specify a block of JavaScript
code to be executed if a condition is true.
&& and (x < 10 && y > 1) is
true
Syntax
|| or (x == 5 || y == 5) is
if (condition) { block of code to be executed if the condition1 is
block of code to be executed if the condition is true false and condition2 is true
} } else {
block of code to be executed if the condition1 is
Note that if is in lowercase letters. Uppercase letters (If false and condition2 is false
or IF) will generate a JavaScript error. }

Example Example

Make a "Good day" greeting if the hour is less than If time is less than 10:00, create a "Good morning"
18:00: greeting, if not, but time is less than 20:00, create a
"Good day" greeting, otherwise a "Good evening":
if (hour < 18) {
greeting = "Good day"; if (time < 10) {
} greeting = "Good morning";
} else if (time < 20) {
The result of greeting will be:
greeting = "Good day";
} else {
Good day greeting = "Good evening";
Try it Yourself }

The else Statement The result of greeting will be:

Use the else statement to specify a block of code to be Good day


executed if the condition is false.

if (condition) { JS SWITCH STATEMENT


block of code to be executed if the condition is true
} else { The switch statement is used to perform different
block of code to be executed if the condition is false actions based on different conditions.
}

Example
The JavaScript Switch Statement
If the hour is less than 18, create a "Good day"
greeting, otherwise "Good evening": Use the switch statement to select one of many blocks
of code to be executed.
if (hour < 18) {
greeting = "Good day"; Syntax
} else {
greeting = "Good evening"; switch(expression) {
} case n:
code block
The result of greeting will be:
break;
case n:
Good day code block
break;
Try it Yourself
default:
code block
}

This is how it works:


The else if Statement

Use the else if statement to specify a new condition if The switch expression is evaluated once.
the first condition is false.
The value of the expression is compared with
Syntax the values of each case.

if (condition1) { If there is a match, the associated block of


block of code to be executed if condition1 is true code is executed.
} else if (condition2) {
Example Statement 3 increases a value (i++) each time the
code block in the loop has been executed.
The getDay() method returns the weekday as a number
between 0 and 6.

(Sunday=0, Monday=1, Tuesday=2 ..)


Statement 1

This example uses the weekday number to calculate Normally you will use statement 1 to initialize the
the weekday name: variable used in the loop (i = 0).

switch (new Date().getDay()) { This is not always the case, JavaScript doesn't care.
case 0: Statement 1 is optional.
day = "Sunday";
break; You can initiate many values in statement 1 (separated
case 1: by comma):
day = "Monday";
break;
Example
}

The result of day will be: for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
Thursday }

Try it Yourself Try it Yourself

JS FOR LOOP JS WHILE LOOP


Loops can execute a block of code as long as a
Loops can execute a block of code a number of times. specified condition is true.

The for loop has the following syntax:

for (statement 1; statement 2; statement 3) {


The While Loop
code block to be executed
} The while loop loops through a block of code as long as
a specified condition is true.
Statement 1 is executed before the loop (the code
block) starts.
Syntax

Statement 2 defines the condition for running the


loop (the code block). while (condition) {
code block to be executed
}
Statement 3 is executed each time after the loop (the
code block) has been executed.
Example

Example
In the following example, the code in the loop will run,
over and over again, as long as a variable (i) is less
for (i = 0; i < 5; i++) { than 10:
text += "The number is " + i + "<br>";
}
Example

Try it Yourself while (i < 10) {


text += "The number is " + i;
From the example above, you can read: i++;
}
Statement 1 sets a variable before the loop starts (var i
= 0).

Statement 2 defines the condition for the loop to run (i JS RESERVED WORDS
must be less than 5).
In JavaScript you cannot use these reserved words as
zed s ent ile
variables, labels, or function names:
Do not use these words as variables. ECMAScript 5/6
abstra argum await* boolea does not have full support in all browsers.
ct ents n

break byte case catch

char class* const contin JavaScript Objects, Properties, and Methods


ue
You should also avoid using the name of JavaScript
built-in objects, properties, and methods:
debug default delete do
ger
Array Date eval functio
doubl else enum* eval n
e
hasOwnPro Infinit isFinite isNaN
export extend false final perty y
* s*
isPrototype lengt Math NaN
finally float for functio Of h
n
name Num Object protot
goto if impleme import ber ype
nts *
String toStri undefi valueO
in instanc int interfa ng ned f
eof ce

let* long native new

null packag private protec


Java Reserved Words
e ted
JavaScript is often used together with Java. You should
public return short static avoid using some Java objects and properties as
JavaScript identifiers:
super* switch synchron this
ized
getClas java JavaAr javaCl
s ray ass
throw throws transient true
JavaObj JavaPack
try typeof var void ect age

volatil while with yield


e
Words marked with* are new in ECMAScript 5 and 6.
You can read more about the different JavaScript
Other Reserved Words
versions in the chapter JS Versions.
JavaScript can be used as the programming language
Removed Reserved Words in many applications.

The following reserved words has been removed from


You should also avoid using the name of HTML and
the ECMAScript 5/6 standard:
Window objects and properties:

abstract boole byte char


alert all anchor anchors
an
area assign blur button
double final float goto
chec clearInte clearTime clientInf
int long native short
kbox rval out ormatio
n
synchroni throw transi volat
close closed confirm constru es nBufferi
ctor ng

crypt decodeU decodeURI default optio outerHei outerWidt packag


o RI Componen Status n ght h es
t
page pageYO parent parseFl
docu element elements embed XOffs ffset oat
ment et

emb encodeU encodeURI escape pars passwor pkcs11 plugin


eds RI Componen eInt d
t
prom property radio reset
even fileUploa focus form pt IsEnum
t d
scree screenY scroll secure
form frame innerHeig innerWi nX
s ht dth
selec self setInterval setTime
layer layers link location t out

mim navigate navigator frames statu submit taint text


eTyp s
es
texta top unescape untaint
fram hidden history image rea
eRat
e wind
ow
imag offscree open opener

You might also like