Javascript
Javascript
Javascript
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>
document.write("Hello World!")
You can place the <script> tags, containing your
</script>
JavaScript, anywhere within you web page, but it is
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
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:
/ Divisio ^= x ^= y x=x^y
n
|= x |= y x=x|y
% Modul
us **= x **= x = x ** y
y
++ Increm
ent
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
JS ASSIGNMENT JS DATA
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".
. Example
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
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
Example
JS OBJECTS
Try it Yourself
Real Life Objects, Properties, and Methods
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:
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
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
Try it Yourself
A variable declared outside a function, JavaScript strings are used for storing and manipulating
becomes GLOBAL. text.
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
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)
String Length
Example
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");
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
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
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 }
Example
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
Example
The toExponential() Method
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
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
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
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.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
Math.abs(x) returns the absolute (positive) value of x: Angle in radians = Angle in degrees x PI / 180.
Example Example
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.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
JS RANDOM
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
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
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
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
Example
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).
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)
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>
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>
JS ARRAY
Example
The following example compares today's date with
January 14, 2100:
var cars = ["Saab", "Volvo", "BMW"];
Example Try it Yourself
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(" * ");
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
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"
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 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:
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
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 }
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
}
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.
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 }
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
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