Photo of a man holding up a post it note with the word code in the middle.

JavaScript Cheat Sheet

All of the basics of JavaScript tucked away in a nice little cheat sheet.

  1. Home
  2. Desde mi escritorio
  3. JavaScript Cheat Sheet
This cheat sheet can serve as a list of recipes for the problems that you need to solve when coding through JavaScript projects, bootcamps, interviews, and final exams. This is straight from a Senior Engineers brain. These are my own simplified explanations with code examples and comments.

So what is the first thing I need to know?


  • Just about everything in JavaScript is an object
  • JavaScript is not type-safe, which means a string could become a number and vice versa
  • JavaScript files end in .js
  • You do not need to use semicolons – its all about personal preference
  • JavaScript class names are always CapitalizedLIkeThis
  • JavaScript functions are always camelCaseLikeThis
  • Node is just one way to run a JavaScript file and is a language written for running JavaScript code. You can also run JavaScript in the browser and mobile devices.

Technical Jargon


Using function, const, var, and let

  • function - function is the word you put in front of the code in which you want to execute as a function. It is usually written like "function functionName(){}".
  • const - const means that the variable that we created will never be reassigned to something else. It locks in the value. If you try to change it, the code will crash. It is usually written like "const someVariableName"
  • let - let means that JavaScript will "let" you can change the variable value. It is usually written like "let someVariableThatINeedToChangeLater"
  • var - var means we can change the variable value. In practice, const and let are preferred over the use of var. So do not use var unless you are instructed to. You can use it like this "var forShame".
  • async - JavaScript that runs along side of or behind the currently running process. For example – a watch has a second, minute, and hour hand. All three parts run at different intervals. The second hand is always running, the minute hand ticks every 60 seconds, and the hour hand ticks every 60 minutes. These three parts of the watch are working asynchronously because they are working on their own process along side the main process of telling us the time.
  • callback - a function that will be fired by JavaScript when another process is completed or by calling functions specified in its parameters.
  • concatenate - Combine one or more items into one item. For example "'test' + ' this'" would be "'test this'"

Scope

In human terms - if I had you in my scope, that means I can see you. Scope is the code all around the line of code you are currently reading. Anything below the current line of code that is being read is not in scope. Let's look at a basic example.
const imAtTheTopSoImInScope = "in scope" function inScopeExampleFunction(){ if(imAtTheTopSoImInScope) return imAtTheTopSoImInScope else return imAtTheBottomSoImOutOfScope const imAtTheBottomSoImOutOfScope = "This is out of scope" } inScopeExampleFunction()
In the example above we have 2 constants. If I were to run the "inScopeExampleFunction", the code would crash because "imAtTheBottomSoImOutOfScope" is out of scope. We are using the value of the "imAtTheBottomSoImOutOfScope" before we defined it and the code will crash. In order to fix the scope error, we can move the "imAtTheBottomSoImOutOfScope" variable to line 2.

Hoisting

JavaScript will hoist functions and variables to the top of the scope once you start to use a function within the scope. See the example below.
function inScopeExampleFunction(){ return variablesCanBeHoistedToo } const variablesCanBeHoistedToo = true inScopeExampleFunction()
In the example above, we create a function called "inScopeExampleFunction". JavaScript will automatically hoist anything that is around the scope of the line that was created. So to JavaScript the above code looks more like the below example by the time it gets to the function call.
const variablesCanBeHoistedToo = true function inScopeExampleFunction(){ return variablesCanBeHoistedToo } inScopeExampleFunction()

Code Snippets


Functions

There are several types of functions in JavaScript. Let's look at the basic function example below.
function aFunctionOfMine(){} aFunctionOfMine()
The function above is a normal function called "aFunctionOfMine". When executed, it will do nothing and return undefined. Let's look at another type of function.
const aFunctionOfMine = () => {} aFunctionOfMine()
The function above is called an arrow function. It makes your code readable, and less buggy because arrow functions bind the scope in which it they were created. Normal functions are bound to the scope in which they are called. So if you are having trouble with "this" - switch to arrow functions or use ".bind". See the example below:
class Example { constructor(){ this.aFunctionOfMine = this.aFunctionOfMine.bind(this) } automaticallyBoundBecauseItsAnArrowFunction = () => { this.aFunctionOfMine() } aFunctionOfMine(){} } new Example()
The constructor is a class method. A method is the same thing as a function, but it can be written differently because we are inside of a class. We don't use the normal "function" or "var, const, let" declarations in classes.
Another type of function is called an anonymous function. Which means, it has no name, and it goes into memory collection as soon as it is done running. Take a look at the example below.
document.addEventListener("click", (event) => console.log(event.target))
In the example above, we passed in an anonymous function after "click", that will return the event target when we call it. Click on any part of the output frame to test the code.

Promises

Promises are a type of class that allows a snippet of code to run asynchronously. You can create your own promise, or you can use functional promises like "window.fetch". We can see an example showing how to create a promise below.
const myPromise = new Promise((onResolve, onReject) => { const whateverIwantToResolveInTheBackground = 123 if(Math.random() > 0.5) { onReject("We don't like numbers greater than 0.5") } else { onResolve(whateverIwantToResolveInTheBackground) } }) myPromise .then(resolutionResult => console.log("Yay!" + resolutionResult)) .catch(errorMessage => console.log("Boo! " + errorMessage))
We can then use the promise by calling the ".then" and ".catch" functions like the last 2 lines in the example above. The ".then" and ".catch" are functions that take a callback function as a parameter. When we call onReject on line 5 above, ".then" will not be called, but ".catch" will and vice versa.
If our promise does not have a rejection ".then" will be called with our resolution value. If our promise does have a rejection, ".catch" will be called with our error message.
The Async/Await syntax requires async to be declared before the currently executing function. Use await on any line that is a promise. The code will pause execution of the remainder of the function until the promise is resolved. If we do not use await (like on line 2), then the promise will execute in the background.
async function myAsyncFunction(){ const response = await fetch("/api") const data = await response.json() return data } myAsyncFunction()
Async functions automatically make the function return a promise. Which means, that when "const response = myAsyncFunction()" is called, "response" will be a promise.

Arrays

In JavaScript an array always starts and ends with square brackets [ ]. The stuff inside of the array can be anything (that is defined). See below for some examples of an array in JavaScript.
let thisIsAnArray = [] thisIsAnArray = new Array() thisIsAnArray = [1, {}, null, false] thisIsAnArray = JSON.parse("[]") // let thisIsNotAnArray = "[]" // thisIsNotAnArray = {} // thisIsNotAnArray = 1, 2, 3, 4

Array.push

Add an item to the end of the array by calling the push array method. This changes the array when it gets called.
const example = [1, 2, 3] example.push(4) console.info(example)

Array.pop

Remove the last item in the array. This changes the array when it gets called and returns the removed item in the array.
const example = [1, 2, 3, 4] example.pop() console.info( example)

Array.filter

Create a new array with values based on if the return value of the callback function is true or false. It does not mutate the array, so you will need to assign the output to a variable.
const example = [1, 2, 3] const filteredExample = example.filter((item) => item > 1) console.info(filteredExample)

Array.reduce

Combine the next item in the index with the previous value that was calculated in the loop and return a single value. The first parameter is a callback function that will fire for each item in the array. The second parameter is your default start value. In the example below, we are computing the sum of all the numbers in the "example" array.
const example = [1, 2, 3, 4] example.reduce((combinedValues, itemAtIndex) => { return combinedValues + itemAtIndex }, 0)
The callback on line three will fire with two parameters for each item in the "example" array. The first parameter called "combinedValues" starts as the number 0 because we set 0 as the default in the reducer function ending on line five. The second parameter called "itemAtIndex" is the object from the current index of the loop. In the example above "itemAtIndex" will be 1, then 2, then 3, then 4 and will exit the loop. Which means "combinedValues" will be 0, then 0 + 1, then 1 + 2, then 3 + 3, 6 + 4 and then it will exit returning the final computed value, which will be 10.

Array.map

Create a new array for each item in an array. This does not change the original array, instead it returns a new array with potentially different values that are based on the original value in the array.
const example = [1, 2, 3, 4] example.map((itemAtIndex, index) => { return index === 1 ? false : itemAtIndex })

Array.includes

Return true if a value is included in the array.
const example = [1, 2, 3, 4] example.includes(1)

Array.find

Find an item in the array. Return the first item that returns a true value in the callback function.
const example = [1, 2, 3, 4] example.find((itemAtIndex) => { return itemAtIndex === 3 })

Array.some

Returns true if there is at least 1 item returned with a true value from the callback function.
const example = [1, 2, 3, 4] example.some((itemAtIndex) => { return itemAtIndex === 1 })

Array.concat

Combine two or more arrays and return a new array. This does not change the original array.
const example = [1, 2, 3, 4] const example2 = [4, 3] example.concat(example2)

Array.slice

Create a new array from a portion of an array. The first parameter is the start index, and the second parameter is the end index. Negative values go in the opposite direction of the index.
const example = [1, 2, 3, 4] example.slice(0, 2)

Array.sort

Sort an array and return a new array with the sorted results. By default, the function will sort an array alphanumerically. It does not change the original array.
const example = [3, 1, 4, 2] example.sort()
Optionally, we can send in a custom sort callback function. This allows us to create a custom sort algorithm. See the example below. It uses a custom callback function to sort the results in reverse order.
const example = [1, 2, 3, 4] example.sort((item1, item2) => { return item2 - item1 })

Array.indexOf

Find the index of a value in an array. This will return the index if one is there, otherwise it will return -1 if nothing is found. We can't have a negative index in an array, so -1 is invalid.
const example = [1, 2, 3, 4] example.indexOf(3) //try with 6 to see what happens when no item in array

Array.join

Combine the array values into a string, optionally specifying a custom delimiter.
const example = [1, 2, 3, 4] example.join(".")

Array.reverse

Reverse the items in the array so that the array is in the opposite order. This does not change the original array. It returns a new array with the items in reverse order.
const example = [1, 2, 3, 4] example.reverse()

Array.length

Get the size of an array. Returns a number with the number of items in the array.
const example = [1, 2, 3, 4] example.length

Array.forEach

Loop through all of the items in the array. The method accepts a callback function that will pass the item for that index as the first parameter and the current index of the loop as the second argument. This does not return anything, and doesn't change the original array.
const example = [1, 2, 3, 4] console.log('Loop started!') example.forEach((item, index) => { if(index < 2) { console.log('Index is ' + index) } else { console.log('Item is ' + item) } }) console.info('Loop completed!')
The example above is calling "forEach" on the example array and looping through each item. We pass in a callback function on line two that has the item and the index in the loop. On line four, we check to see if the index is less than 2, and if it is then we log "Index is 0", and then "Index is 1". Then when the loop gets to the 2nd index, it will hit the else statement and log "Item is 3", and then "Item is 4". Then the code will exit the loop.

Array.unshift

Add an item to the start of the array. This is the opposite of "Array.push". This changes the original array.
const example = [1, 2, 3, 4] example.unshift(100) console.info(example)

Numbers

  • * – the asterisk means to multiply
  • / – the slash means to divide
  • % – the remainder operator. Find the remainder "2 % 4 = 0".
  • + – add 2 numbers
  • - – subtract 2 numbers
  • () – do the math in the parenthesis first.
// will be 3 console.log(1 + 2) // will be 4 console.log(2 * 2) // will be 6 console.log(2 * 2 + (1 + 1)) // will be 1 console.log(3 % 2) // will be 1 2 / 2

Number.isNaN

Determine if a number is a non number. NaN Stands for Not a Number. This can happen if you add a non number to a number.
const numberOfApples = 2 const numberOfMonkeys = undefined console.info(`${numberOfApples + numberOfMonkeys}`)

Strings

Strings are objects with characters wrapped in quotation marks or back-ticks (``, "", '').
// These are strings
[
new String(),
"This is a string",
`This is a string`,
'This is a string'
] // These are not strings
const This = null
const is = null
const not = null
const a = null
const string = null This
is
not
a
string console.info('Can you remove all of the bad strings?')

Template Strings

Template strings are strings that are formatted with indents, variables, and new lines. If we wanted to add variables into our string we would use the dollar sign "$" and curly brackets "{}" and then write our variable into the curly brackets. See the example below.
const helloMessage = "How are you?" const letterString = `
Hello,
${helloMessage}
Thank you,
John Doe
`
console.log(letterString) console.info("Output above this line")

String.trim

This function will remove any extra white space from the string. It doesn't change the original string, and returns the new value without any extra white space.
" This string has way too much white space. ".trim()

String.length

Get the length of a string. This returns the number of characters in a string, including white space.
const example = "H e l l o !" example.length

String.replace

Replace a set of characters in a string. This does not change the original string. This will return the new string with the replaced characters. The method takes 2 parameters. The first parameter can either be a regular expression or a string, and the second parameter is what you would like to replace any matches with. See the example below.
const helloBlank = "Hello _____!" helloBlank.replace('_____', "world")
The below example shows how to do the same thing with regular expressions. The regex in the example is "/_____/g". This means find all instance of "_____ " because the g means global. See the regex section for more info.
const helloBlank = "Hello _____!" helloBlank.replace(/_____/g, "world")

String.search

Returns the index of the found set of characters. Returns -1 if there is not a match. The method takes one parameter. The first parameter is the string that you want to find inside of your string. See the example below.
const bigString = "This is a really big string" bigString.search("big")

String.toLowerCase

Lowercase all of the characters in a string. This does not change the original string and will return a string with all of the characters lowercase.
const example = "AHHHH" example.toLowerCase()

String.toUpperCase

Capitalize all of the characters in a string. This does not change the original string and will return a string with all of the characters capitalized.
const example = "ahhhh" example.toUpperCase()

String.includes

Determine if a string includes another string. Returns true if a string exists in the string.
const example = "Hello world" example.includes("Hello")

String.split

Split a string by returning an array of values split by the delimiter you specify. If no delimiter is specified in the first parameter of the method, then nothing gets split. A delimiter is a flag to create a new item in the array when there is a match. The delimiters in are removed from the string if there is a match. See the example below.
const example = "Roe. Josh. John. Ally" example.split(".")
If we pass in an empty string into the first parameter, all of the characters will be separated in to their own item in the array. See the example below.
const example = "Roe. Josh. John. Ally" example.split("")

Regex

Regex is a set of regular expressions that can be used to parse different parts of a string. With regex, we can determine if we have or don't have a match. This is used for things like email validation to check that we have a valid email in the format of a@b.com. There is an unbelievable amount to learn about regex and this can be used across many different language. I'm only going to talk about the regex I use often.
  • / - start and end of regex. All inline-regex must have 2 slashes. One a the start of the regex and one at the end.
  • g - stands for globally. If we add this to the end of our regex after the "/" then regex will key off of all possible matches in the string. Otherwise it will look for 1 match.
  • i - stands for case insensitive. By default regex is case sensitive. This will insure regex looks for all characters with a match even though the character might be upper/lower case.
  • gi - stands for global and case insensitive. So regex will find all matches regardless of capitalization.
  • * - stands for everything
  • w - stands for whitespace
  • d - stands for digit
  • s - stands for letters
  • + - stands for in addition to
  • . - stands for from here
And there are many more that deserve to be in a some massive book about regex or something.
Below is a basic set of regex examples.
  • /.*/ - find everything
  • /stuff/g - find the word "stuff" globally
  • /stuff/gi - find the word "stuff" globally regardless of casing
Optionally, we can use the RegExp class JavaScript provides to dynamically create regex expressions. See the example below.
new RegExp("cat", "g")
The class RegExp takes 2 arguments. The first argument is a string representing the regex expression. The second argument specifies how regex should do the search (g for global and so on). This essentially creates "/cat/g".

Regex.test

Validate that a string matches the regex.
/this/.test("this is valid")

Objects

Almost everything in JavaScript is an object. An object is a group of data separated by key and value pairs. If we type a dot symbol "." after something like "console" in "console.log", you are calling "log" from the "console" object. When creating an object write empty curly brackets. An object looks like the examples below.
{} // curly brackets = object const userObject = {user: true, "user-type": 1} // user-type needs quotes around it because of the dash userObject['type'] = 'admin' // can also key like an array userObject.loggedIn = true // add new key called logged in and assign it to true console.info(userObject)

Object.keys

Get all of the object's keys as an array.
const example = {first: 1, second: 2} Object.keys(example)

Object.values

Get all of the object's values as an array.
const example = {first: 1, second: 2} Object.values(example)

Object.assign

Merge two or more objects into one object. This will return an object with all of the values from all the provided objects.
const example = {hello: true} const example2 = {world: false} Object.assign(example, example2)

Object.entries

Returns an array of key value arrays based on the key value pairs in an object.
const example = {hello: true, world: false} const entries = Object.entries(example) entries.forEach(([key, value]) => console.log(key, value)) console.info(entries)

Booleans

A bool or boolean is traditionally a true or false. But in JavaScript there is also a concept of truthy and falsy. A truthy statement means that we have a value, while a falsy statement means we do not have a value. We can optionally use the Boolean class to cast a value to a boolean type.
const isTrue = true // truthy const isFalse = false // falsy const isFalseString = '' // falsy const isTrueString = 'is ok' // truthy const isFalseNumber = 0 // falsy const isTrueNumber = 1 //truthy const isTrueFromBoolean = Boolean(1) // truthy when using the Boolean class const isFalseFromBoolean = Boolean(0) // falsy when using the Boolean class const isFalseFromBang = !true // is falsy const isTrueFromBang = !false // truthy

Classes

Classes are containers for a set of functions, objects, and variables. They can be extended from other classes, and incapsulate everything in a scope. Classes in JavaScript are just objects, so we use them like we would use any other object.
If we need to use a class we start with the new keyword followed by the class name and a set of parentheses. We can then pass any arguments into the class inside of the parentheses.
Below is an example of how to write and use a class:
class Example { constructor(animalType) { if(animalType === 'cat') console.log('im a cat') else console.log('its not a cat im a ' + animalType) } } // we can use this like this: new Example('dog') // console will say 'im not cat im a dog' new Example('cat') // console will say 'im a cat'

Class inheritance

Class inheritance is when one class extends from another. Lets take a look at the example below.
class Animal { constructor(animalType) {} speak(word){ alert(word) } } class Cat extends Animal { constructor() { super('cat') } sayMeow() { this.speak('meow!!') } } //use the Cat class const kitty = new Cat() kitty.sayMeow() // will alert saying 'meow!!'
The example above shows a class called Animal with a function called speak. We then create a new class called Cat that extends from the Animal class. This means that everything in the Animal class will be available in the Cat class. So the Cat class has access to the speak function. We then create the constructor in the Cat class and call super.
Super refers to the class in which we extended from. It's the same thing as saying "new Animal('cat')". Instead we say "super('cat')" because we are overriding the parent class constructor method. We call super from Cat.constructor in order to call the parent class constructor method as well.
If we need to access a method from the parent class, we call this.speak from the Cat class.

Classes, this, and bind

Please read the scope section and class section of this document for more context. When we use the keyword "this" in JavaScript, it's referring to the scope. If we call "this" from inside of a button, we would be in the scope of a button. If we called "this" from inside of a class, we are in the scope of our class. JavaScript can get "this" confused if we don't use a bind function. Let's take a look at how it works in a class.
class Animal { constructor(animalType) { // assign variables to this to use them later this.animalName = animalType //use bind to bind the scope so this will always be an instance of Animal this.speak = this.speak.bind(this) } speak(){ alert('Im a ' + this.animalName) // we need to bind to use this } } new Animal('cat').speak()

For loops

A for loop is a way to iterate through an array of values. Lets take a look at a basic example:
const example = [1, 2, 3] for(let i = 0; i < example.length; i++) { console.log(i, example[i]) }

While loops

While loops are a way to do something while something is true. The while loop will continue to execute the function repeatedly until the while condition is true. Look at the example below.
let i = 0; while(i < 3) { console.log(i) i++ }
Última actualización:  06/13/2022 @ 05:06 PM

Dejar un comentario