Common Objects in JavaScript
JavaScript is an object - based scripting language. It has classes and objects, but it doesn't strictly implement encapsulation, inheritance, or polymorphism like traditoinal object - oriented programming languages. Browsers natively support several built - in objects, such as Array, String, Math, Number, and Date.
String Object (Similar to Java’s String, with Key Methods)
The String object in JavaScript is similar to Java's String in some way and has many useful methods.
<html>
<head>
<meta charset="UTF-8">
<title>String Object Demo</title>
<script>
// Get character by index
/*const str = "hello js";
const char = str.charAt(6);
console.log(char);*/
// Concatenate strings
const partA = "hi";
const partB = "good";
const partC = "China";
const combined = partC.concat(partA, partB);
console.log(combined);
// Repeat a string
const base = "adsf";
const repeated = base.repeat(3);
console.log(repeated);
// Substring operations
const text = "helloJhon";
// Substr: start index, count of characters
const substrResult = text.substr(1, 5);
console.log(substrResult);
// Substring: start (inclusive) to end (exclusive)
const subStrResult = text.substring(1, 7);
console.log(subStrResult);
// Get length
console.log(text.length); // length is a property
// Evaluate string as JavaScript code (special function: eval)
// Parses and executes the string as JS code
const codeStr = "let num = 10;";
eval(codeStr);
console.log(num);
</script>
</head>
<body></body>
</html>
Number Object (Wrapper Class with Properties/Methods)
The Number object (a wrapper class) has useful properties and methods for numeric operations.
<html>
<head>
<meta charset="UTF-8">
<title>Number Object Demo</title>
<script>
// Number properties (max/min values, safe integers)
console.log(Number.MAX_VALUE);
console.log(Number.MIN_VALUE);
console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MIN_SAFE_INTEGER);
// Parse and convert strings to numbers
console.log(Number.parseFloat("10.123") + 20);
console.log(Number.parseInt("30") + 20);
// Special numeric operations
const remainder = 10 % 0;
const division = 10 / 0;
console.log(remainder);
console.log(division);
// Check numeric validity
console.log(Number.isNaN(remainder)); // Is Not a Number?
console.log(Number.isFinite(division));
console.log(Number.isSafeInteger(Number.MAX_VALUE));
console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER));
</script>
</head>
<body></body>
</html>
Math Object
The Math object provides utility methods for mathematical operations.
<html>
<head>
<meta charset="UTF-8">
<title>Math Object Demo</title>
<script>
// Rounding and comparison
console.log(Math.round(3.64)); // Round to nearest integer
console.log(Math.floor(3.14)); // Round down
console.log(Math.ceil(3.01)); // Round up
console.log(Math.max(1, 2, 3, 5.6)); // Max value
console.log(Math.min(1, 2, 3, 5.6)); // Min value
console.log(Math.random()); // Random [0,1)
console.log(Math.sqrt(16)); // Square root
// Property: PI
console.log(Math.PI);
// Generate random number in [start, end]
const rangeStart = 10;
const rangeEnd = 16;
const randomInRange = Math.floor(Math.random() * (rangeEnd - rangeStart + 1) + rangeStart);
console.log(randomInRange);
</script>
</head>
<body></body>
</html>
Date Object (For Handling Dates and Times)
The Date object is used to work with dates and times.
Creating a Date Object
You can creeate a Date object in multiple ways:
// Four common ways to instantiate a Date:
const date1 = new Date();
const date2 = new Date(1630000000000); // milliseconds since Unix epoch
const date3 = new Date("September 1, 2021");
const date4 = new Date(2021, 8, 1, 12, 30, 0, 0); // year, month (0 - 11), day, hours, ...
Date Methods (Demo)
<html>
<head>
<meta charset="UTF-8">
<title>Date Object Demo</title>
<script>
// Note: Months are 0 - indexed (January = 0, December = 11)
const today = new Date();
const historical = new Date("October 13, 1975 11:13:00");
const shortYear = new Date(79, 5, 24); // Represents 1979 - 06 - 24
const withTime = new Date(79, 5, 24, 11, 33, 0);
console.log(historical);
console.log(shortYear);
console.log(withTime);
const future = new Date(2048, 0, 13, 16, 51, 20, 123); // 2048 - 01 - 13...
console.log(future);
// Retrieve date components
console.log(future.getYear()); // Years since 1900 (legacy method)
console.log(future.getFullYear()); // Full 4 - digit year
console.log(future.getMonth()); // 0 - based month index
console.log(future.getDate()); // Day of the month
console.log(future.getHours()); // Hours (0 - 23)
console.log(future.getMinutes()); // Minutes
console.log(future.getSeconds()); // Seconds
console.log(future.getMilliseconds()); // Milliseconds
const later = new Date(2048, 0, 13, 16, 51, 20, 456);
console.log(future < later); // Compare two dates
// Date formatting (Extend Date prototype)
Date.prototype.format = function (formatStr) {
const formatObj = {
"M+": this.getMonth() + 1, // Month (1 - 12)
"d+": this.getDate(), // Day of month
"h+": this.getHours(), // Hour
"m+": this.getMinutes(), // Minute
"s+": this.getSeconds(), // Second
"q+": Math.floor((this.getMonth() + 3) / 3), // Quarter
"S": this.getMilliseconds() // Millisecond
};
if (/y+/.test(formatStr)) {
formatStr = formatStr.replace(
RegExp.$1,
(this.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
for (const key in formatObj) {
if (new RegExp(`(${key})`).test(formatStr)) {
formatStr = formatStr.replace(
RegExp.$1,
RegExp.$1.length === 1
? formatObj[key]
: ("00" + formatObj[key]).substr(("" + formatObj[key]).length)
);
}
}
return formatStr;
};
const formatted = future.format("yyyy - MM - dd hh:mm:ss");
console.log(formatted);
</script>
</head>
<body></body>
</html>