JavaScript Classes
Last updated:
Classes
A JavaScript class is a template for creating objects, which defines a set of properties and methods that the objects will have, providing a way to organize code into reusable components, making it easier to maintain and extend applications.
Life before classes (pre-ES6)
Via constructor functions:
function Car(colour) {
this.colour = colour;
}
Car.prototype.honk = function() {
console.log("Honk");
};
const myCar = new Car('red');
myCar.honk(); // Outputs: "Honk"
console.log(myCar.colour); // Outputs: "red"
Define a class
class Car {
constructor(colour) {
this.colour = colour;
}
honk() {
console.log("Honk");
}
}
const myCar = new Car('red');
myCar.honk();
console.log(myCar.colour); // Outputs: "red"
Inheritance
A mechanism that allows a class to inherit properties and methods from another class, using the extends
keyword:
class Car {
constructor(colour) {
this.colour = colour;
}
}
class F1Car extends Car {
constructor(number, colour) {
super(colour);
this.number = number;
}
}
let bestCar = new F1Car(32, "red");
console.log(bestCar); // prints: Object { colour: "red", number: 32 }
Objects
Objects are a fundamental data type that represent a collection of properties. A property is a key-value pair, where the key is a string (or symbol), and the value can be any data type.
Creating Objects
There are 4 ways to create objects:
-
Object literal notation
let person = { name: 'Paul', website: 'pardel.dev' };
-
Constructor function
function Person(name, website) { this.name = name; this.website = website; }; let person = new Person('Paul', 'pardel.dev');
-
Object.create()
const personPrototype = { sayHello: function() { console.log(`Hello ${this.name}`); } }; let person = Object.create(personPrototype, { name: { value: 'Paul' }, website: { value: 'pardel.dev' } }); person.sayHello(); // Outputs: Hello Paul
-
Class Notation
class Person { constructor(name, website) { this.name = name; this.website = website; } } let person = new Person('Paul', 'pardel.dev');
Accessing Properties
You can access an object’s properties using dot notation or bracket notation:
let person = {
name: 'Paul',
website: 'pardel.dev',
address: {
city: 'London'
}
};
console.log(person.name); // Outputs: Paul
console.log(person.address.city); // Outputs: London
console.log(person['website']); // Outputs: 'pardel.dev'
Modifying Properties
let person = {
name: 'Paul',
website: pardel.dev
};
person.website = pardel.dev;
console.log(person.website); // Outputs: 'pardel.dev'
Adding Object Properties
let person = {
name: 'Paul'
};
person.website = 'pardel.dev';
console.log(person.website); // Outputs: pardel.dev
Built-in Objects
JavaScript has several built-in objects that provide functionality to perform various tasks - they are essential to the language and can be used to make development easier and faster.
1. Object
Base object for all JavaScript objects and provides generic methods for creating and manipulating objects:
var person = new Object();
// Add properties to the object
person.name = "Charlie";
person.location = "Rome";
// Access the properties using dot notation
console.log(person.name); // prints: "Charlie"
console.log(person.location); // prints: "Rome"
// Use the Object.keys() method to get an array of property names
var propertyNames = Object.keys(person);
console.log(propertyNames); // prints: ["name", "location"]
// Use the Object.values() method to get an array of property values
var propertyValues = Object.values(person);
console.log(propertyValues); // Output: ["Charlie", "Rome"]
// Use the Object.entries() method to get an array of [key, value] pairs
var entries = Object.entries(person);
console.log(entries); // Output: [["name", "Charlie"], ["location", "Rome"]]
2. Array
const myArray = new Array('a', 42, 3.14);
See Arrays notes.
3. String
const firstName = new String("Charlie");
See String notes.
###4. Number
const theAnswer = new Number(42);
See Number notes.
5. Boolean
const wasPublished = new Boolean(true);
See Boolean notes.
6. Date
The Date object is used to represent and manipulate dates and times and also provides methods for getting and setting dates, formatting dates, etc:
var currentDate = new Date();
console.log(currentDate.getFullYear()); // prints: 2023
console.log(currentDate.getMonth()); // prints: 0 (January, as months are zero-indexed)
console.log(currentDate.getDate()); // prints: 16
console.log(currentDate.getDay()); // prints: 1
// days are also zero-indexed, with Sunday being 0
console.log(currentDate.getHours()); // prints: current hour in 24-hour format
console.log(currentDate.getMinutes()); // prints: current minute
console.log(currentDate.getSeconds()); // prints: current second
console.log(currentDate.getMilliseconds()); // prints: current millisecond
console.log(currentDate.getTime()); // prints: number of milliseconds since January 1, 1970
// parse a string into a Date object
var dateString = "2023-01-16T07:30:00.000Z";
var parsedDate = new Date(Date.parse(dateString));
console.log(parsedDate); // prints: "Date Mon Jan 16 2023 07:30:00 GMT+0000 (Greenwich Mean Time) ..."
7. Math
The Math object provides mathematical constants and functions, such as trigonometric functions, logarithms, and more:
// get the value of pi
var pi = Math.PI;
console.log(pi); // prints: 3.141592653589793
// round down to the nearest integer
var roundedDown = Math.floor(3.8);
console.log(roundedDown); // prints: 3
// round up to the nearest integer
var roundedUp = Math.ceil(3.2);
console.log(roundedUp); // prints: 4
// round to the nearest integer
var rounded = Math.round(3.5);
console.log(rounded); // prints: 4
// find the maximum value in a list of numbers
var max = Math.max(3, 5, 7, 2, 8);
console.log(max); // prints: 8
// find the minimum value in a list of numbers
var min = Math.min(3, 5, 7, 2, 8);
console.log(min); // prints: 2
// to generate a random number between 0 and 1
var random = Math.random();
console.log(random); // prints: a random number between 0 and 1
8. RegExp
The RegExp object is used to represent regular expressions, which are used to search for and replace text patterns.
// Create a regular expression to match phone numbers
// using the format XX-XXXX-XXXXXX
var phoneRegex = /^\d{2}-\d{4}-\d{6}$/;
// test if a string matches the regular expression
var phoneNumber = "44-7700-900123";
var isPhoneNumber = phoneRegex.test(phoneNumber);
console.log(isPhoneNumber); // prints: true
var invalidPhoneNumber = "123-456-789";
var isInvalidPhoneNumber = phoneRegex.test(invalidPhoneNumber);
console.log(isInvalidPhoneNumber); // prints: false
9. Function
const sum = new Function("a", "b", "return a + b;");
See Function notes.
10. Error
The Error object is used to represent runtime errors in JavaScript and provides information about the error and a stack trace for debugging purposes.
var anError = new Error("Something went wrong");
See Error Objects notes.
11. JSON
JSON (JavaScript Object Notation) is a lightweight data format used to exchange data between the client and the server. The JSON object in JavaScript is a built-in object that has methods for converting JavaScript objects to and from JSON format:
const person = {
"name": "Charlie"
};
const personJSON = JSON.stringify(person);
const backToPersonAgain = JSON.parse(personJSON);
12. Promise
Promise is an object that represents the eventual completion (success or failure) of an asynchronous operation and its resulting value:
const myPromise = new Promise((resolve, reject) => {
const result = someAction();
if (result) {
resolve(result);
} else {
reject(new Error('Something went wrong'));
}
});
myPromise.then((result) => {
// success
console.log(result);
}).catch((error) => {
// failure
console.error(error);
});
See Promises notes.
13. Set & WeakSet
const mathConstants = new Set();
const mathConstants = new WeakSet();
See Set & WeakSet notes.
14. Map & WeakMap
const myMap = new Map();
const myMap = new WeakMap();
See Map & WeakMap notes.
15. Symbol
let mySymbol = Symbol();
See Symbol notes.
16. BigInt
const anotherBig = BigInt('1234567890123456789012345678901234567890')
See BigInt notes.
17. ArrayBuffer
Represents a fixed-length raw binary data buffer and is used to store binary data in a specific format and size. Here is how to create an ArrayBuffer object with a length of 16 bytes:
const buffer = new ArrayBuffer(16);
18. DataView
A low-level interface for reading and writing binary data - allows you to read and write data in different byte orders and allows you to specify the byte offset of the data you want to access. In the example below, buffer in an ArrayBuffer object:
new DataView(buffer [, byteOffset [, byteLength]]);