Java Script 2
Java Script 2
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
Example
var x = 9.656;
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns 9.656000e+0
The parameter is optional. If you don't specify it, JavaScript will not round the
number.
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
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
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
Example
Number(new Date("2017-09-30")); // returns 1506729600000
Example
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN
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
Number Properties
Property Description
JavaScript POSITIVE_INFINITY
Example
var x = Number.POSITIVE_INFINITY;
Example
var x = 1 / 0;
JavaScript NEGATIVE_INFINITY
Example
var x = Number.NEGATIVE_INFINITY;
Example
var x = -1 / 0;
Example
var x = 100 / "Apple"; // x will be NaN (Not a Number)
Array.forEach()
The forEach() method calls a function (a callback function) once for each array
element.
Example
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
The example above uses only the value parameter. The example can be
rewritten to:
Example
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value) {
txt = txt + value + "<br>";
}
Array.forEach() is supported in all browsers except Internet Explorer 8 or
earlier:
Array.map()
The map() method creates a new array by performing a function on each array
element.
The map() method does not execute the function for array elements without
values.
Example
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
When a callback function uses only the value parameter, the index and array
parameters can be omitted:
Example
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2;
}
This example creates a new array from elements with a value larger than 18:
Example
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
In the example above, the callback function does not use the index and array
parameters, so they can be omitted:
Example
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
function myFunction(value) {
return value > 18;
}
Array.reduce()
The reduce() method runs a function on each array element to produce (reduce
it to) a single value.
The reduce() method works from left-to-right in the array. See also
reduceRight().
The reduce() method does not reduce the original array.
Example
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
The example above does not use the index and array parameters. It can be
rewritten to:
Example
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
Example
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction, 100);
The reduceRight() works from right-to-left in the array. See also reduce().
Example
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
The example above does not use the index and array parameters. It can be
rewritten to:
Example
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
This example check if all array values are larger than 18:
Example
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);
When a callback function uses the first parameter only (value), the other
parameters can be omitted:
Example
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);
function myFunction(value) {
return value > 18;
}
Array.some()
The some() method check if some array values pass a test.
This example check if some array values are larger than 18:
Example
var numbers = [45, 4, 9, 16, 25];
var someOver18 = numbers.some(myFunction);
Array.indexOf()
Search an array for an element value and returns its position.
Note: The first item has position 0, the second item has position 1, and so on.
Example
Search an array for the item "Apple":
Syntax
array.indexOf(item, start)
If the item is present more than once, it returns the position of the first
occurrence.
Array.lastIndexOf()
Array.lastIndexOf() is the same as Array.indexOf(), but searches from the end
of the array.
Example
Search an array for the item "Apple":
Syntax
array.lastIndexOf(item, start)
start Optional. Where to start the search. Negative values will start at the given pos
end, and search to the beginning
Array.find()
The find() method returns the value of the first array element that passes a test
function.
This example finds (returns the value of ) the first element that is larger than
18:
Example
var numbers = [4, 9, 16, 25, 29];
var first = numbers.find(myFunction);
Array.find() is not supported in older browsers. The first browser versions with
full support is listed below.
Array.findIndex()
The findIndex() method returns the index of the first array element that passes
a test function.
This example finds the index of the first element that is larger than 18:
Example
var numbers = [4, 9, 16, 25, 29];
var first = numbers.findIndex(myFunction);
Example
var d = new Date();
You will learn much more about how to display dates, later in this tutorial.
new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)
new Date()
new Date() creates a new date object with the current date and time:
Example
var d = new Date();
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);
Example
var d = new Date(2018, 11, 24, 10, 33, 30);
Example
var d = new Date(2018, 11, 24, 10, 33);
Example
var d = new Date(2018, 11, 24, 10);
Example
var d = new Date(2018, 11, 24);
Example
var d = new Date(2018, 11);
You cannot omit month. If you supply only one parameter it will be treated as
milliseconds.
Example
var d = new Date(2018);
Previous Century
One and two digit years will be interpreted as 19xx:
Example
var d = new Date(99, 11, 24);
Example
var d = new Date(9, 11, 24);
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");
Now the time is: 1546595889712 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);
01 January 1970 plus 100 000 000 000 milliseconds is approximately 03 March
1973:
Example
var d = new Date(100000000000);
January 01 1970 minus 100 000 000 000 milliseconds is approximately October
31 1966:
Example
var d = new Date(-100000000000);
Example
var d = new Date(86400000);
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:
Example
d = new Date();
document.getElementById("demo").innerHTML = d;
Same as:
d = new Date();
document.getElementById("demo").innerHTML = d.toString();
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.toDateString();
Method Description
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
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();
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", "S
eptember", "October", "November", "December"];
document.getElementById("demo").innerHTML = months[d.getMonth()];
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getDate();
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getHours();
The getMinutes() Method
The getMinutes() method returns the minutes of a date as a number (0-59):
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getMinutes();
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getSeconds();
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getMilliseconds();
Example
var d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
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", "Saturday"
];
document.getElementById("demo").innerHTML = days[d.getDay()];
Method Description
Example
<script>
var d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>
Example
<script>
var d = new Date();
d.setFullYear(2020, 11, 3);
document.getElementById("demo").innerHTML = d;
</script>
Example
<script>
var d = new Date();
d.setMonth(11);
document.getElementById("demo").innerHTML = d;
</script>
Example
<script>
var d = new Date();
d.setDate(20);
document.getElementById("demo").innerHTML = d;
</script>
Example
<script>
var d = new Date();
d.setDate(d.getDate() + 50);
document.getElementById("demo").innerHTML = d;
</script>
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>
The setMinutes() Method
The setMinutes() method sets the minutes of a date object (0-59):
Example
<script>
var d = new Date();
d.setMinutes(30);
document.getElementById("demo").innerHTML = d;
</script>
Example
<script>
var d = new Date();
d.setSeconds(30);
document.getElementById("demo").innerHTML = d;
</script>
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);
Example
Math.PI; // returns 3.141592653589793
Math.round()
Math.round(x) returns the value of x rounded to its nearest integer:
Example
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Math.pow()
Math.pow(x, y) returns the value of x to the power of y:
Example
Math.pow(8, 2); // returns 64
Math.sqrt()
Math.sqrt(x) returns the square root of x:
Example
Math.sqrt(64); // returns 8
Math.abs()
Math.abs(x) returns the absolute (positive) value of x:
Example
Math.abs(-4.7); // returns 4.7
Math.ceil()
Math.ceil(x) returns the value of x rounded up to its nearest integer:
Example
Math.ceil(4.4); // returns 5
Math.floor()
Math.floor(x) returns the value of x rounded down to its nearest integer:
Example
Math.floor(4.7); // returns 4
Math.sin()
Math.sin(x) returns the sine (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:
Example
Math.sin(90 * Math.PI / 180); // returns 1 (the sine of 90 degrees)
Math.cos()
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:
Example
Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0 degrees)
Example
Math.min(0, 150, 30, 20, -8, -200); // returns -200
Example
Math.max(0, 150, 30, 20, -8, -200); // returns 150
Math.random()
Math.random() returns a random number between 0 (inclusive), and 1
(exclusive):
Example
Math.random(); // returns a random number
Example
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Math Constructor
Unlike other global objects, the Math object has no constructor. Methods and
properties are static.
All methods and properties (constants) can be used without creating a Math
object first.
Method Description
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
atan2(y, x) Returns the arctangent of the quotient of its arguments