VBScript
VBScript
VBScript (Visual Basic Script) is the Active Scripting Language , JavaScript is the Client side scripting language, prototype b
lightweight & designed for fast interpreter . and mostly used with web browsers.
Microsoft Developed VBScript. Brendan Eich founded JavaScript and NetScape Develope
VBScript works at both client side and server side. JavaScript works only at client side.
VBScript is not case sensitive language. JavaScipt is case sensitive language.
It runs only on Internet Explorer (IE) browser. It runs on the all browser.
VBScript is used for server side validation. JavaScript is used for client side validation.
VBScript supports functions & subroutines and uses function and end JavaScript supports only functions and uses curly braces fo
function for starting and ending function. starting and ending function.
VBScript Syntax is derived from BASIC language . JavaScript syntax is derived from C language.
VBScript is not the default scripting language , but can be made by JavaScript is default scripting language almost in all brows
specifying in scripting language.
File extension in VBScript is .vba or .vbs File Extension in JavaScript is .js
VBScript Uses ‘ for comment. JavaScript uses // or /* … */ for comments.
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of
data types it supports. These are the type of values that can be represented and
manipulated in a programming language.
JavaScript allows you to work with three primitive data types −
Numbers, eg. 123, 120.50 etc.
Strings of text e.g. "This text string" etc.
Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value. In addition to these primitive data types, JavaScript
supports a composite data type known as object. We will cover objects in detail in a
separate chapter.
Note − JavaScript does not make a distinction between integer values and floating-
point values. All numbers in JavaScript are represented as floating-point values.
JavaScript represents numbers using the 64-bit floating-point format defined by the
IEEE 754 standard.
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.
<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable
initialization at the time of variable creation or at a later point in time when you need
that variable.
For instance, you might create a variable named money and assign the value 2000.50
to it later. For another variable, you can assign a value at the time of initialization as
follows.
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a
value of any data type. Unlike many other languages, you don't have to tell JavaScript
during variable declaration what type of value the variable will hold. The value type of a
variable can change during the execution of a program and JavaScript takes care of it
automatically.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
This produces the following result −
local
JavaScript Statements
JavaScript statements are composed of:
This statement tells the browser to write "Hello Dolly." inside an HTML element
with id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
Try it Yourself »
The statements are executed, one by one, in the same order as they are
written.
Semicolons ;
Semicolons separate JavaScript statements.
Try it Yourself »
When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
Try it Yourself »
var x = y + z;
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!";
Try it Yourself »
One place you will find statements grouped together in blocks, is in JavaScript
functions:
Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
Try it Yourself »
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
++ Increment
-- Decrement
= 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
**= x **= y x = x ** y
JavaScript String Operators
The + operator can also be used to add (concatenate) strings.
Example
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;
John Doe
Example
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
10
55
Hello5
JavaScript Comparison Operators
Operator Description
== equal to
!= not equal
? ternary operator
JavaScript Type Operators
Operator Description
Any numeric operand in the operation is converted into a 32 bit number. The
result is converted back to a JavaScript number.
JavaScript Comments
❮ PreviousNext ❯
Any text between // and the end of the line will be ignored by JavaScript (will
not be executed).
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
Try it Yourself »
This example uses a single line comment at the end of each line to explain the
code:
Example
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2
Try it Yourself »
Multi-line Comments
Multi-line comments start with /* and end with */.
Try it Yourself »
Adding // in front of a code line changes the code lines from an executable line
to a comment.
Example
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
Try it Yourself »
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
JavaScript Functions
❮ PreviousNext ❯
Example
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
Try it Yourself »
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, ...)
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
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:
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
12
Try it Yourself »
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(77);
Try it Yourself »
Accessing a function without () will return the function definition instead of the
function result:
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
Try it Yourself »
Example
Instead of using a variable to store the return value of a function:
var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";
Try it Yourself »
You will learn a lot more about functions later in this tutorial.
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Example
// code here can NOT use carName
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}
Try it Yourself »
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.
JavaScript Expressions and
Statements
Expressions
Any unit of code that can be evaluated to a value is an expression.
Since expressions produce values, they can appear anywhere in a
program where JavaScript expects a value such as the arguments
of a function invocation. As per the MDN documentation,
JavaScript has the following expression categories.
Arithmetic Expressions:
Arithmetic expressions evaluate to a numeric value. Examples
include the following
10; // Here 10 is an expression that is evaluated to the
numeric value 10 by the JS interpreter10+13; // This is another
expression that is evaluated to produce the numeric value 23
String Expressions:
String expressions are expressions that evaluate to a string.
Examples include the following
'hello';
'hello' + 'world'; // evaluates to the string 'hello world'
Logical Expressions:
Expressions that evaluate to the boolean value true or false are
considered to be logical expressions. This set of expressions often
involve the usage of logical operators && (AND), ||(OR) and
!(NOT). Examples include
10 > 9; // evaluates to boolean value true
10 < 20; // evaluates to boolean value false
true; //evaluates to boolean value true
a===20 && b===30; // evaluates to true or false based on the values
of a and b
Primary Expressions:
Primary expressions refer to stand alone expressions such as
literal values, certain keywords and variable values. Examples
include the following
'hello world'; // A string literal
23; // A numeric literal
true; // Boolean value true
sum; // Value of variable sum
this; // A keyword that evaluates to the current object
Left-hand-side Expressions:
Also known as lvalues, left-hand-side expressions are those that
can appear on the left side of an assignment expression. Examples
of left-hand-side expressions include the following
// variables such as i and total
i = 10;
total = 0;// properties of objectsvar obj = {}; // an empty object
with no properties
obj.x = 10; // an assignment expression// elements of arrays
array[0] = 20;
array[1] = 'hello';// Invalid left-hand-side errors
++(a+1); // SyntaxError. Attempting to increment or decrement an
expression that is not an lvalue will lead to errors.
Now that we have covered the basics of expressions, let’s dive a bit
deeper into expressions.
Assignment Expressions:
When expressions use the = operator to assign a value to a
variable, it is called an assignment expression. Examples include
average = 55;var b = (a = 1); // here the assignment expression (a
= 1) evaluates to a value that is assigned to the variable b. b =
(a = 1) is another assignment expression. var is not part of the
expression.
Declaration Statements:
Such type of statements create variables and functions by using
the var and function statements respectively. Examples include
var sum;
var average;// In the following example, var total is the statement
and total = 0 is an assignment expressionvar total = 0;// A
function declaration statement function greet(message) {
console.log(message);
}
Expression Statements:
Wherever JavaScript expects a statement, you can also write an
expression. Such statements are referred to as expression
statements. But the reverse does not hold. You cannot use a
statement in the place of an expression.
var a = var b; // leads to an error cause you cannot use a
statement in the place of an expressionvar a = (b = 1); // since (b
= 1) is an assignment expression and not a statement, this is a
perfectly acceptable line of codeconsole.log(var a); // results in
error as you can pass only expressions as a function argument
Conditional Statements:
Conditional statements execute statements based on the value of
an expression. Examples of conditional statements includes the
if..else and switch statements.
// Syntax of an if statement. If the expression following the if
statement evaluates to a truthy value, statement 1 is executed else
statement 2 is executed.if (expression)
statement 1
else
statement 2
Local scope
Global scope
Variables defined inside a function are not accessible (visible) from outside the
function.
Local variables have Function scope: They can only be accessed from within
the function.
Example
// code here can NOT use carName
function myFunction() {
var carName = "Volvo";
Try it Yourself »
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.
A global variable has global scope: All scripts and functions on a web page can
access it.
Example
var carName = "Volvo";
function myFunction() {
Try it Yourself »
JavaScript Variables
In JavaScript, objects and functions are also variables.
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 a global variable carName, even if the value is
assigned inside a function.
Example
myFunction();
function myFunction() {
carName = "Volvo";
}
Try it Yourself »
Strict Mode
All modern browsers support running JavaScript in "Strict Mode".
You will learn more about how to use strict mode in a later chapter of this
tutorial.
In HTML, the global scope is the window object. All global variables belong to
the window object.
Example
var carName = "Volvo";
Try it Yourself »
Warning
Do NOT create global variables unless you intend to.
Your global variables (or functions) can overwrite window variables (or
functions).
Any function, including the window object, can overwrite your global variables
and functions.
In a web browser, global variables are deleted when you close the browser
window (or tab).
Function Arguments
Function arguments (parameters) work as local variables inside functions.
JavaScript Events
❮ PreviousNext ❯
HTML Events
An HTML event can be something the browser does, or something a user does.
Try it Yourself »
In the example above, the JavaScript code changes the content of the element
with id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
Try it Yourself »
JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
Example
<button onclick="displayDate()">The time is?</button>
Try it Yourself »
Event Description
onchange An HTML element has been changed
onmouseout The user moves the mouse away from an HTML element
The list is much longer: W3Schools JavaScript Reference HTML DOM Events.
JavaScript Strings
A JavaScript string is zero or more characters written inside quotes.
Example
var x = "John Doe";
Try it Yourself »
Example
var carName1 = "Volvo XC60"; // Double quotes
var carName2 = 'Volvo XC60'; // Single quotes
Try it Yourself »
You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
Example
var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';
Try it Yourself »
String Length
To find the length of a string, use the built-in length property:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Try it Yourself »
Escape Character
Because strings must be written within quotes, JavaScript will misunderstand
this string:
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string
characters:
\\ \ Backslash
Example
var x = "We are the so-called \"Vikings\" from the north.";
Try it Yourself »
Example
var x = 'It\'s alright.';
Try it Yourself »
Example
var x = "The character \\ is called backslash.";
Try it Yourself »
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator
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!";
Try it Yourself »
You can also break up a code line within a text string with a single backslash:
Example
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
Try it Yourself »
The \ method is not the preferred method. It might not have universal support.
Some browsers do not allow spaces behind the \ character.
Example
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";
Try it Yourself »
Example
document.getElementById("demo").innerHTML = \
"Hello Dolly!";
Try it Yourself »
But strings can also be defined as objects with the keyword new:
Example
var x = "John";
var y = new String("John");
Try it Yourself »
Example
var x = "John";
var y = new String("John");
Try it Yourself »
When using the === operator, equal strings are not equal, because
the === operator expects equality in both type and value.
Example
var x = "John";
var y = new String("John");
Try it Yourself »
Or even worse. Objects cannot be compared:
Example
var x = new String("John");
var y = new String("John");
Try it Yourself »
Example
var x = new String("John");
var y = new String("John");
Try it Yourself »
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 Length
The length property returns the length of a string:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Try it Yourself »
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
Try it Yourself »
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");
Try it Yourself »
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("John");
Try it Yourself »
Both methods accept a second parameter as the starting position for the
search:
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate", 15);
Try it Yourself »
The lastIndexOf() methods searches backwards (from the end to the beginning),
meaning: if the second parameter is 15, the search starts at position 15, and
searches to the beginning of the string.
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate", 15);
Try it Yourself »
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
Try it Yourself »
They accept the same arguments (parameters), and return the same value?
The two methods are NOT equal. These are the differences:
slice(start, end)
substring(start, end)
substr(start, length)
The method takes 2 parameters: the start position, and the end position (end
not included).
This example slices out a portion of a string from position 7 to position 12 (13-
1):
Example
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
Banana
Try it Yourself »
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);
Banana
Try it Yourself »
If you omit the second parameter, the method will slice out the rest of the
string:
Example
var res = str.slice(7);
Try it Yourself »
Example
var res = str.slice(-12);
Try it Yourself »
Example
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
The result of res will be:
Banana
Try it Yourself »
If you omit the second parameter, substring() will slice out the rest of the string.
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);
Banana
Try it Yourself »
If you omit the second parameter, substr() will slice out the rest of the string.
Example
var str = "Apple, Banana, Kiwi";
var res = str.substr(7);
Banana, Kiwi
Try it Yourself »
If the first parameter is negative, the position counts from the end of the string.
Example
var str = "Apple, Banana, Kiwi";
var res = str.substr(-4);
Kiwi
Try it Yourself »
Example
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
Try it Yourself »
The replace() method does not change the string it is called on. It returns a new
string.
Example
str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
Try it Yourself »
Try it Yourself »
Example
str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3Schools");
Try it Yourself »
Example
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools");
Try it Yourself »
You will learn a lot more about regular expressions in the chapter JavaScript
Regular Expressions.
Try it Yourself »
Example
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
Try it Yourself »
Example
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);
Try it Yourself »
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!");
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.
String.trim()
The trim() method removes whitespace from both sides of a string:
Example
var str = " Hello World! ";
alert(str.trim());
Try it Yourself »
If you need to support IE 8, you can use replace() with a regular expression
instead:
Example
var str = " Hello World! ";
alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));
Try it Yourself »
You can also use the replace solution above to add a trim function to the
JavaScript String.prototype:
Example
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
var str = " Hello World! ";
alert(str.trim());
Try it Yourself »
Extracting String Characters
There are 3 methods for extracting string characters:
charAt(position)
charCodeAt(position)
Property access [ ]
Example
var str = "HELLO WORLD";
str.charAt(0); // returns H
Try it Yourself »
The method returns a UTF-16 code (an integer between 0 and 65535).
Example
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
Try it Yourself »
Property Access
ECMAScript 5 (2009) allows property access [ ] on strings:
Example
var str = "HELLO WORLD";
str[0]; // returns H
Try it Yourself »
Example
var str = "HELLO WORLD";
str[0] = "A"; // Gives no error, but does not work
str[0]; // returns H
Try it Yourself »
If you want to work with a string as an array, you can convert it to an array.
Example
var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
Try it Yourself »
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
Try it Yourself »
JavaScript has only one type of number. Numbers can be written with or
without decimals.
Example
var x = 3.14; // A number with decimals
var y = 3; // A number without decimals
Try it yourself »
Extra large or extra small numbers can be written with scientific (exponent)
notation:
Example
var x = 123e5; // 12300000
var y = 123e-5; // 0.00123
Try it yourself »
Precision
Integers (numbers without a period or exponent notation) are accurate up to 15
digits.
Example
var x = 999999999999999; // x will be 999999999999999
var y = 9999999999999999; // y will be 10000000000000000
Try it Yourself »
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
Try it yourself »
Example
var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3
Try it Yourself »
Example
var x = 10;
var y = 20;
var z = x + y; // z will be 30 (a number)
Try it Yourself »
Example
var x = "10";
var y = "20";
var z = x + y; // z will be 1020 (a string)
Try it Yourself »
If you add a number and a string, the result will be a string concatenation:
Example
var x = 10;
var y = "20";
var z = x + y; // z will be 1020 (a string)
Try it Yourself »
If you add a string and a number, the result will be a string concatenation:
Example
var x = "10";
var y = 20;
var z = x + y; // z will be 1020 (a string)
Try it Yourself »
Example
var x = 10;
var y = 20;
var z = "The result is: " + x + y;
Try it Yourself »
Example
var x = 10;
var y = 20;
var z = "30";
var result = x + y + z;
Try it Yourself »
Numeric Strings
JavaScript strings can have numeric content:
var x = "100";
var y = "10";
var z = x / y; // z will be 10
Try it Yourself »
var x = "100";
var y = "10";
var z = x * y; // z will be 1000
Try it Yourself »
var x = "100";
var y = "10";
var z = x - y; // z will be 90
Try it Yourself »
var x = "100";
var y = "10";
var z = x + y; // z will not be 110 (It will be 10010)
Try it Yourself »
In the last example JavaScript uses the + operator to concatenate the strings.
NaN - Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal
number.
Example
var x = 100 / "Apple"; // x will be NaN (Not a Number)
Try it Yourself »
However, if the string contains a numeric value , the result will be a number:
Example
var x = 100 / "10"; // x will be 10
Try it Yourself »
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
Try it Yourself »
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
Try it Yourself »
Example
var x = NaN;
var y = "5";
var z = x + y; // z will be NaN5
Try it Yourself »
Example
typeof NaN; // returns "number"
Try it Yourself »
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;
}
Try it yourself »
Try it Yourself »
Example
typeof Infinity; // returns "number"
Try it Yourself »
Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded by
0x.
Example
var x = 0xFF; // x will be 255
Try it Yourself »
But you can use the toString() method to output numbers from base 2 to base
36.
Hexadecimal is base 16. Decimal is base 10. Octal is base 8. Binary is base
2.
Example
var myNumber = 32;
myNumber.toString(10); // returns 32
myNumber.toString(32); // returns 10
myNumber.toString(16); // returns 20
myNumber.toString(8); // returns 40
myNumber.toString(2); // returns 100000
Try it Yourself »
var x = 123;
But numbers can also be defined as objects with the keyword new:
Example
var x = 123;
var y = new Number(123);
Try it yourself »
Try it Yourself »
When using the === 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);
Try it Yourself »
Example
var x = new Number(500);
var y = new Number(500);
Try it Yourself »
But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.
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
Try it Yourself »
The toExponential() Method
toExponential() returns a string, with a number rounded and written using
exponential notation.
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
Try it yourself »
The parameter is optional. If you don't specify it, JavaScript will not round the
number.
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
Try it yourself »
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
Try it Yourself »
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
Try it Yourself »
These methods are not number methods, but global JavaScript methods.
These are the most relevant methods, when working with numbers:
Method Description
Example
Number(true); // returns 1
Number(false); // returns 0
Number("10"); // returns 10
Number(" 10"); // returns 10
Number("10 "); // returns 10
Number(" 10 "); // returns 10
Number("10.33"); // returns 10.33
Number("10,33"); // returns NaN
Number("10 33"); // returns NaN
Number("John"); // returns NaN
Try it Yourself »
Example
Number(new Date("2017-09-30")); // returns 1506729600000
Try it Yourself »
The Number() method above returns the number of milliseconds since 1.1.1970.
Try it yourself »
Example
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
Try it yourself »
Number Properties
Property Description
MAX_VALUE Returns the largest number possible in JavaScript
Example
var x = Number.MAX_VALUE;
Try it yourself »
Example
var x = Number.MIN_VALUE;
Try it yourself »
JavaScript POSITIVE_INFINITY
Example
var x = Number.POSITIVE_INFINITY;
Try it yourself »
Example
var x = 1 / 0;
Try it yourself »
JavaScript NEGATIVE_INFINITY
Example
var x = Number.NEGATIVE_INFINITY;
Try it yourself »
Example
var x = -1 / 0;
Try it yourself »
Try it yourself »
Example
var x = 100 / "Apple"; // x will be NaN (Not a Number)
Try it Yourself »
Example
var x = 6;
var y = x.MAX_VALUE; // y becomes undefined
Try it yourself »
JavaScript Arrays
❮ PreviousNext ❯
Example
var cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
Example
var cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
var cars = [
"Saab",
"Volvo",
"BMW"
];
Try it Yourself »
Putting a comma after the last element (like "BMW",) is inconsistent across
browsers.
Example
var cars = new Array("Saab", "Volvo", "BMW");
Try it Yourself »
The two examples above do exactly the same. There is no need to use new
Array().
For simplicity, readability and execution speed, use the first one (the array
literal method).
Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
Try it Yourself »
cars[0] = "Opel";
Example
var cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars[0];
Try it Yourself »
Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:
Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Try it Yourself »
Arrays use numbers to access its "elements". In this example, person[0] returns
John:
Array:
var person = ["John", "Doe", 46];
Try it Yourself »
Object:
var person = {firstName:"John", lastName:"Doe", age:46};
Try it Yourself »
Array Elements Can Be Objects
JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can
have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Examples
var x = cars.length; // The length property returns the number of
elements
var y = cars.sort(); // The sort() method sorts arrays
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4
Try it Yourself »
The length property is always one more than the highest array index.
Try it Yourself »
Try it Yourself »
Example
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
Try it Yourself »
Example
var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
function myFunction(value) {
text += "<li>" + value + "</li>";
}
Try it Yourself »
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
Try it Yourself »
New element can also be added to an array using the length property:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to
fruits
Try it Yourself »
WARNING !
Adding elements with high indexes can create undefined "holes" in an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; // adds a new element (Lemon) to fruits
Try it Yourself »
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
Example
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return 3
var y = person[0]; // person[0] will return "John"
Try it Yourself »
WARNING !!
If you use named indexes, JavaScript will redefine the array to a standard
object.
After that, some array methods and properties will produce incorrect results.
Example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined
Try it Yourself »
Use [] instead.
These two different statements both create a new empty array named points:
These two different statements both create a new array containing 6 numbers:
Try it Yourself »
The new keyword only complicates the code. It can also produce some
unexpected results:
var points = new Array(40, 100); // Creates an array with two elements
(40 and 100)
Try it Yourself »
Try it Yourself »
The typeof operator returns object because a JavaScript array is an object.
Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():
Try it Yourself »
The problem with this solution is that ECMAScript 5 is not supported in older
browsers.
Solution 2:
To solve this problem you can create your own isArray() function:
function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
Try it Yourself »
Or more precisely: it returns true if the object prototype contains the word
"Array".
Solution 3:
The instanceof operator returns true if an object is created by a given
constructor:
Try it Yourself »
JavaScript Array Methods
❮ PreviousNext ❯
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
Banana,Orange,Apple,Mango
Try it Yourself »
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:
Try it Yourself »
Popping and Pushing
When you work with arrays, it is easy to remove elements and add new
elements.
Popping
The pop() method removes the last element from an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from
fruits
Try it Yourself »
The pop() method returns the value that was "popped out":
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop(); // the value of x is "Mango"
Try it Yourself »
Pushing
The push() method adds a new element to an array (at the end):
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
Try it Yourself »
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi"); // the value of x is 5
Try it Yourself »
Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the
last.
The shift() method removes the first array element and "shifts" all other
elements to a lower index.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from
fruits
Try it Yourself »
The shift() method returns the string that was "shifted out":
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.shift(); // the value of x is "Banana"
Try it Yourself »
The unshift() method adds a new element to an array (at the beginning), and
"unshifts" older elements:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
Try it Yourself »
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Returns 5
Try it Yourself »
Changing Elements
Array elements are accessed using their index number:
Array indexes start with 0. [0] is the first array element, [1] is the second, [2]
is the third ...
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi"; // Changes the first element of fruits to
"Kiwi"
Try it Yourself »
The length property provides an easy way to append a new element to an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruits
Try it Yourself »
Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the
JavaScript operator delete:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits
to undefined
Try it Yourself »
Using delete may leave undefined holes in the array. Use pop() or shift()
instead.
Splicing an Array
The splice() method can be used to add new items to an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
Try it Yourself »
The first parameter (2) defines the position where new elements should
be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to
be added.
The splice() method returns an array with the deleted items:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
Try it Yourself »
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruits
Try it Yourself »
The first parameter (0) defines the position where new elements should
be added (spliced in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters are omitted. No new elements will be added.
Try it Yourself »
The concat() method does not change the existing arrays. It always returns a
new array.
Try it Yourself »
Try it Yourself »
Slicing an Array
The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1
("Orange"):
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
Try it Yourself »
The slice() method creates a new array. It does not remove any elements from
the source array.
This example slices out a part of an array starting from array element 3
("Apple"):
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(3);
Try it Yourself »
The slice() method can take two arguments like slice(1, 3).
The method then selects elements from the start argument, and up to (but not
including) the end argument.
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
Try it Yourself »
If the end argument is omitted, like in the first examples, the slice() method
slices out the rest of the array.
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(2);
Try it Yourself »
Automatic toString()
JavaScript automatically converts an array to a comma separated string when a
primitive value is expected.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Try it Yourself »
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
Try it Yourself »
You will learn how you solve this problem in the next chapter of this tutorial.
Sorting Arrays
Sorting arrays are covered in the next chapter of this tutorial.
JavaScript Date Objects
❮ PreviousNext ❯
Example
var d = new Date();
Try it Yourself »
You will learn much more about how to display dates, later in this tutorial.
new Date()
new Date() creates a new date object with the current date and time:
Example
var d = new Date();
Try it Yourself »
Date objects are static. The computer time is ticking, but date objects are not.
7 numbers specify year, month, day, hour, minute, second, and millisecond (in
that order):
Example
var d = new Date(2018, 11, 24, 10, 33, 30, 0);
Try it Yourself »
Try it Yourself »
Example
var d = new Date(2018, 11, 24, 10, 33);
Try it Yourself »
Example
var d = new Date(2018, 11, 24, 10);
Try it Yourself »
Example
var d = new Date(2018, 11, 24);
Try it Yourself »
Example
var d = new Date(2018, 11);
Try it Yourself »
You cannot omit month. If you supply only one parameter it will be treated as
milliseconds.
Example
var d = new Date(2018);
Try it Yourself »
Previous Century
One and two digit years will be interpreted as 19xx:
Example
var d = new Date(99, 11, 24);
Try it Yourself »
Example
var d = new Date(9, 11, 24);
Try it Yourself »
new Date(dateString)
new Date(dateString) creates a new date object from a date string:
Example
var d = new Date("October 13, 2014 11:13:00");
Try it Yourself »
Date strings are described in the next chapter.
Now the time is: 1578197844090 milliseconds past January 01, 1970
new Date(milliseconds)
new Date(milliseconds) creates a new date object as zero time plus
milliseconds:
Example
var d = new Date(0);
Try it Yourself »
01 January 1970 plus 100 000 000 000 milliseconds is approximately 03 March
1973:
Example
var d = new Date(100000000000);
Try it Yourself »
January 01 1970 minus 100 000 000 000 milliseconds is approximately October
31 1966:
Example
var d = new Date(-100000000000);
Try it Yourself »
Example
var d = new Date(86400000);
Try it Yourself »
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 date objects, using either local time or UTC
(universal, or GMT) time.
Date methods and time zones are covered in the next chapters.
Displaying Dates
JavaScript will (by default) output dates in full text string format:
Try it Yourself »
Same as:
d = new Date();
document.getElementById("demo").innerHTML = d.toString();
Try it Yourself »
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
Try it Yourself »
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.toDateString();
Try it Yourself »
JavaScript Date Formats
❮ PreviousNext ❯
Type Example
The other formats are not so well defined and might be browser specific.
The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date
format:
Try it Yourself »
Example
var d = new Date("2015-03");
Try it Yourself »
Time zones will vary the result above between February 28 and March 01.
ISO Dates (Only Year)
ISO dates can be written without month and day (YYYY):
Example
var d = new Date("2015");
Try it Yourself »
Time zones will vary the result above between December 31 2014 and January
01 2015.
Example
var d = new Date("2015-03-25T12:00:00Z");
Try it Yourself »
If you want to modify the time relative to UTC, remove the Z and add +HH:MM
or -HH:MM instead:
Example
var d = new Date("2015-03-25T12:00:00-06:30");
Try it Yourself »
UTC (Universal Time Coordinated) is the same as GMT (Greenwich Mean Time).
Omitting T or Z in a date-time string can give different results in different
browsers.
Time Zones
When setting a date, without specifying the time zone, JavaScript will use the
browser's time zone.
When getting a date, without specifying the time zone, the result is converted
to the browser's time zone.
Example
var d = new Date("03/25/2015");
Try it Yourself »
WARNINGS !
In some browsers, months or days with no leading zeroes may produce an
error:
Example
var d = new Date("Mar 25 2015");
Try it Yourself »
Example
var d = new Date("25 Mar 2015");
Try it Yourself »
Example
var d = new Date("January 25 2015");
Try it Yourself »
Example
var d = new Date("Jan 25 2015");
Try it Yourself »
Try it Yourself »
Date.parse() returns the number of milliseconds between the date and January 1,
1970:
Example
var msec = Date.parse("March 21, 2012");
document.getElementById("demo").innerHTML = msec;
Try it Yourself »
You can then use the number of milliseconds to convert it to a date object:
Example
var msec = Date.parse("March 21, 2012");
var d = new Date(msec);
document.getElementById("demo").innerHTML = d;
Try it Yourself »
avaScript Get Date Methods
❮ PreviousNext ❯
These methods can be used for getting information from a date object:
Method Description
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
Try it Yourself »
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
Try it Yourself »
The getMonth() Method
The getMonth() method returns the month of a date as a number (0-11):
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getMonth();
Try it Yourself »
You can use an array of names, and getMonth() to return the month as a
name:
Example
var d = new Date();
var months =
["January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"];
document.getElementById("demo").innerHTML = months[d.getMonth()];
Try it Yourself »
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getDate();
Try it Yourself »
The getHours() Method
The getHours() method returns the hours of a date as a number (0-23):
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getHours();
Try it Yourself »
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getMinutes();
Try it Yourself »
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getSeconds();
Try it Yourself »
The getMilliseconds() Method
The getMilliseconds() method returns the milliseconds of a date as a number
(0-999):
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getMilliseconds();
Try it Yourself »
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
Try it Yourself »
In JavaScript, the first day of the week (0) means "Sunday", even if some
countries in the world consider the first day of the week to be "Monday"
You can use an array of names, and getDay() to return the weekday as a
name:
Example
var d = new Date();
var days =
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturd
ay"];
document.getElementById("demo").innerHTML = days[d.getDay()];
Try it Yourself »
Method Description
Set Date methods let you set date values (years, months, days, hours,
minutes, seconds, milliseconds) for a Date Object.
Method Description
Example
<script>
var d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Example
<script>
var d = new Date();
d.setFullYear(2020, 11, 3);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
The setMonth() Method
The setMonth() method sets the month of a date object (0-11):
Example
<script>
var d = new Date();
d.setMonth(11);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Example
<script>
var d = new Date();
d.setDate(15);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Example
<script>
var d = new Date();
d.setDate(d.getDate() + 50);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
If adding days shifts the month or year, the changes are handled automatically
by the Date object.
Example
<script>
var d = new Date();
d.setHours(22);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Example
<script>
var d = new Date();
d.setMinutes(30);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
The setSeconds() Method
The setSeconds() method sets the seconds of a date object (0-59):
Example
<script>
var d = new Date();
d.setSeconds(30);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself »
Compare Dates
Dates can easily be compared.
The following example compares today's date with January 14, 2100:
Example
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);
Try it Yourself »
Test Yourself With Exeses