JavaScript Methods #
Specific methods.
Getters #
Get and return properties of objects.
Use the get keyword within an object, followed by a method.
const someObj = {
...;
get someMethod() {
...;
}
}
To access a getter, don’t use parenthesis. It’ll look like acceessing a property.
console.log(someObj.someMethod);
Math #
For more details
.floor() #
Rounds down to whole number
console.log(Math.floor(Math.random())) // a little bit of encapsulation
.random() #
get a random number between 0 and 1:
console.log(Math.random())
Setters #
Related to getters. Reassigns values of existing properties within objects.
const someObj = {
_someValue = ...;
set newValue(new_value) {
if (typeof new_value == 'string') {
this._someValue = new_value;
} else {
console.log('blah blah nothing changes');
}
}
}
// invoke with the following
someObj.newValue = 'a new string!';
console.log(someObj._someValue); // this should now log `a new string!`
^ like getters, invocation doesn’t require parenthesis.
Note: name of getter and setter method can be the same. Depending on invocation, it can get or set.
Strings #
-
.trim() -
.toUpperCase()
Built-in #
Bunch built-in methods available to all objects.
Get keys #
Object.keys(someObject);