Javascript cheatsheet.
Methods, functions and events.
Methods, functions and events.
Javascript methods are actions that can be performed on objects. A JavaScript method is a property containing a function definition.
Objects, Strings, RegEx, Arrays, Number & Date
Examples for each to help understand the many types of JS methods available natively.
Credit: Casey Chin
toString
You've got a number, you want to turn it into a string…
var number = 15;
var numberAsString = number.toString();
// I guess you log it out to see what it does. Which is not much. You can see 15, but now it's a 'string' primitive type not a number primitive type.
It does mean that (number + number) no longer equals 30. It equals 1515 because you're concatinating the two strings together, the same as (cat + dog = catdog).
console.log(numberAsString);
toLocaleString
To handle date formatting for all countries you can convert the date from the computed format into locale formats.
// Create a new date & time object - this is a static date.
var worldDate = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// British English uses day-month-year order and 24-hour time without AM/PM
console.log(worldDate.toLocaleString('en-GB', { timeZone: 'UTC' }));
// output: 20/12/2012, 03:00:00
// Korean uses year-month-day order and 12-hour time with AM/PM
console.log(worldDate.toLocaleString('ko-KR', { timeZone: 'UTC' }));
// output: 2012. 12. 20. 오전 3:00:00
// Now, let's create a dynamic one.
const currentDate = new Date();
console.log(currentDate.toLocaleString('ko-KR', { timeZone: 'UTC' }));
// this will output the current date and time in Korean format.
There are a quite few arguments built in so you can customise your format until your heart is content.
valueOf
Return the primitive value of a string object.
var string = 'Here is my goddamn string';
var valueOfString = string.valueOf();
// This will just print the string. Not sure what this really does that the original string doesn't.
console.log(valueOfString);
hasOwnProperty
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). What does this mean?
// Create a new object constant (const)
const object1 = new Object();
// Assign a property to it
object1.property1 = 69;
// Output: true - this is because your object does have a property of, in this case, 'property1'.
console.log(object1.hasOwnProperty('property1'));
// If we log out object1 we get the following:
{property1: 69}
// This is because we created an object which is this {}, and then we assigned a property and value using dot notation.
isPrototypeOf
What do we use this for then?
"The isPrototypeOf() method provides a way to determine if one object is the prototype of another. This technique can be used to determine the class of an object."
function object1() {}
function object2() {}
object1.prototype = Object.create(object2.prototype);
const object3 = new object1();
console.log(object1.prototype.isPrototypeOf(object3));
// output: true
console.log(object2.prototype.isPrototypeOf(object3));
// output: true
propertyIsEnumerable
Enumerable /ɪˈnjuːm(ə)rəb(ə)l/
adjective
able to be counted by one-to-one correspondence with the set of all positive integers.
I'm not sure that helps me understand it. There is a tl;dr explanation and many resources online to get bored of. But below I'll try and demo a simple version of what it means.
// So, because the method contains the word 'is' we're going to returning a boolean of true or false (same with any method that contains 'has').
// Let's create some stuff to test our method
const object = {};
const array = [];
// Now push some data to our object and array
object.propertyOne = 69;
array[0] = 69;
// Let's test whether propertyOne of our object is propertyIsEnumerable
console.log(object.propertyIsEnumerable('propertyOne'));
// output: true
// And this works with decimals - so we don't need whole numbers to return true
object.propertyTwo = 69.5;
console.log(object.propertyIsEnumerable('propertyTwo'));
// output: true
// Other than that I can't really explain what this does or where you would use it
charAt
Find out what character is where in a string. Good for finding out the first or last character of a word / sentence / series of characters.
// Start with a string
const string = 'If you wannabe my lover, you've got to get with my friends';
console.log(string.charAt(0));
// output: 'I'
console.log(string.charAt(7));
// output: 'w'
// Now, to get the last character of the string we want to pass the argument of string.length and then use -1 which is the JS way of getting the last character in a sequence.
console.log(string.charAt(string.length -1));
// output: 's'
// You could use a loop to get a set of characters which could be good for getting certain sections of serial numbers from a dataset. Or printing out spice girls lyrics in a weird acrostic format.
for (let i = 0; i < string.length; i++) {
console.log(string.charAt(i));
}
concat
There are some resources online about efficiency of different techniques to concatinate your code. The new ES6 backtick method has introduced a clear, human-readable, syntax which outshines using concat(). MDN even specifies in the documentation to use other methods to concatinate.
// Let's start with concat()
var string1 = 'Lettuce';
var string2 = 'leaf';
console.log(string1.concat(' ', string2));
// output: 'Lettuce leaf'
// Above is less performant and harder to read than
console.log(string1 + string2);
// And es6 allows for the following (and is even faster)
console.log(`${string1} ${string2}`);
indexOf
Use this to find a match from one item to an item inside an array. I use this a fair amount when trying to find out whether a value is contained in a list of values.
const birdsOfParadise = ["Raggiana", "Ribbon-tailed astrapia", "Victoria's riflebird", "Saxony's bird-of-paradise", "Curl-crested manucode"];
birdsOfParadise.indexOf("Raggiana");
// output: 0
// Use this to find your value match and then 2 values along the array from that - though this does just return the number which you can use as a variable and pass the value
const key = birdsOfParadise.indexOf("Ribbon-tailed astrapia", 2);
key
// output: 4
birdsOfParadise[key];
// output: Saxony’s bird-of-paradise
birdsOfParadise.indexOf("Kookaburra");
// output: -1
lastIndexOf
This gets the starting character number of the string you pass into the lastIndexOf() method.
const string = 'This is the dawning of the age of Aquarius';
const number = string.lastIndexOf('dawning');
number;
// output: 12
match
The match() method retrieves the result of matching a string against a regular expression.
// First, we set out the string we want to test
const string = 'I took a deep breath and listened to the old bray of my heart. I am. I am. I am.';
// Create a Regular Expression which we use to check something. This one below checks for capital letters in a string.
const regex = /[A-Z]/g;
const found = string.match(regex);
found;
// output: Array ["I", "I", "I", "I"]
replace
We can replace strings where we need using this argument, we can also use RegEx to target specific characters or words in a string
// So, let's create our initial string
const originalString = "All your base are belong to us";
const replacementString = "CATS has taken over all of your bases.";
originalString.replace(originalString, replacementString);
// output "CATS has taken over all of your bases."
// Or we can do this per word using a RegEx
const regEx = /base/gi;
originalString.replace(regEx, 'houses');
// output: "All your houses are belong to us"
slice
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
More coming soon...