DEV Community

Cover image for JavaScript Cheatsheet from beginners to advance..
Anmol Raj
Anmol Raj

Posted on • Updated on

JavaScript Cheatsheet from beginners to advance..

Hi. I've tried to some up javascript cheatsheet in one article. Hope you like it.

JavaScript Basics

Set of JavaScript basic syntax to add, execute and write basic programming paradigms in Javascript

On Page Script

Adding internal JavaScript to HTML

<script type="module"> //JS code goes here </script> 
Enter fullscreen mode Exit fullscreen mode

External JS File

Adding external JavaScript to HTML

<script src="filename.js"></script>
Enter fullscreen mode Exit fullscreen mode

Functions

JavaScript Function syntax

function nameOfFunction () {
// function body 
} 
Enter fullscreen mode Exit fullscreen mode

DOM Element

Changing content of a DOM Element

document.getElementById("elementID").innerHTML = "Hello 
World!";
Enter fullscreen mode Exit fullscreen mode

Output

This will print the value of a in JavaScript console

console.log(a);
Enter fullscreen mode Exit fullscreen mode

Conditional Statements

Conditional statements are used to perform operations based on some conditions.

If Statement

The block of code to be executed, when the condition specified is true.

if (condition) {
// block of code to be executed if the condition is true
}

Enter fullscreen mode Exit fullscreen mode

If-else Statement

If the condition for the if block is false, then the else block will be executed.

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Enter fullscreen mode Exit fullscreen mode

Else-if Statement

A basic if-else ladder

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Enter fullscreen mode Exit fullscreen mode

Switch Statement

Switch case statement in JavaScript

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Enter fullscreen mode Exit fullscreen mode

Iterative Statements (Loops)

Iterative statement facilitates programmer to execute any block of code lines repeatedly and can be controlled as per conditions added by the programmer.

For Loop

For loop syntax in javascript

for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Enter fullscreen mode Exit fullscreen mode

While Loop

Runs the code till the specified condition is true

while (condition) {
// code block to be executed
}

Enter fullscreen mode Exit fullscreen mode

Do While Loop

A do while loop is executed at least once despite the condition being true or false

do {
// run this code in block
i++;
} while (condition);

Enter fullscreen mode Exit fullscreen mode

Strings

The string is a sequence of characters that is used for storing and managing text data.

charAt method

Returns the character from the specified index.

str.charAt(3)

Enter fullscreen mode Exit fullscreen mode

concat method

Joins two or more strings together.

str1.concat(str2)
Enter fullscreen mode Exit fullscreen mode

index of method

Returns the index of the first occurrence of the specified character from the string else -1 if not found.

str.indexOf('substr')

Enter fullscreen mode Exit fullscreen mode

match method

Searches a string for a match against a regular expression.

str.match(/(chapter \d+(\.\d)*)/i;)
Enter fullscreen mode Exit fullscreen mode

replace method

Searches a string for a match against a specified string or char and returns a new string by replacing the specified values.

str1.replace(str2)

Enter fullscreen mode Exit fullscreen mode

search method

Searches a string against a specified value.

str.search('term')

Enter fullscreen mode Exit fullscreen mode

split method

Splits a string into an array consisting of substrings.

str.split('\n')

Enter fullscreen mode Exit fullscreen mode

substring method

Returns a substring of a string containing characters from the specified indices.

str.substring(0,5)

Enter fullscreen mode Exit fullscreen mode

Arrays

The array is a collection of data items of the same type. In simple terms, it is a variable that contains multiple values.

variable

Containers for storing data.

var fruit = ["element1", "element2", "element3"];

Enter fullscreen mode Exit fullscreen mode

concat method

Joins two or more arrays together.

concat()
Enter fullscreen mode Exit fullscreen mode

indexOf method

Returns the index of the specified item from the array.

indexOf()

Enter fullscreen mode Exit fullscreen mode

join method

Converts the array elements to a string.

join()

Enter fullscreen mode Exit fullscreen mode

pop method

Deletes the last element of the array.

pop()

Enter fullscreen mode Exit fullscreen mode

reverse method

This method reverses the order of the array elements.

reverse()

Enter fullscreen mode Exit fullscreen mode

sort method

Sorts the array elements in a specified manner.

sort()
Enter fullscreen mode Exit fullscreen mode

toString method

Converts the array elements to a string.

toString()
Enter fullscreen mode Exit fullscreen mode

valueOf method

returns the relevant Number Object holding the value of the argument passed

valueOf()
Enter fullscreen mode Exit fullscreen mode

Number Methods

JS math and number objects provide several constant and methods to perform mathematical operations.

toExponential method

Converts a number to its exponential form.

toExponential()

Enter fullscreen mode Exit fullscreen mode

toPrecision method

Formats a number into a specified length.

toPrecision()
Enter fullscreen mode Exit fullscreen mode

toString method

Converts an object to a string

toString()
Enter fullscreen mode Exit fullscreen mode

valueOf method

Returns the primitive value of a number.

valueOf()
Enter fullscreen mode Exit fullscreen mode

Maths Methods

ceil method
Rounds a number upwards to the nearest integer, and returns the result

ceil(x)

Enter fullscreen mode Exit fullscreen mode

exp method

Returns the value of E^x.

exp(x)
Enter fullscreen mode Exit fullscreen mode

log method

Returns the logarithmic value of x.

log(x)
Enter fullscreen mode Exit fullscreen mode

pow method

Returns the value of x to the power y.

pow(x,y)
Enter fullscreen mode Exit fullscreen mode

random method

Returns a random number between 0 and 1.

random()
Enter fullscreen mode Exit fullscreen mode

sqrt method

Returns the square root of a number x

sqrt(x)

Enter fullscreen mode Exit fullscreen mode

Dates

Date object is used to get the year, month and day. It has methods to get and set day, month, year, hour, minute, and seconds.

Pulling Date from the Date object
Returns the date from the date object

getDate()

Enter fullscreen mode Exit fullscreen mode

Pulling Day from the Date object
Returns the day from the date object

getDay()
Enter fullscreen mode Exit fullscreen mode

Pulling Hours from the Date object
Returns the hours from the date object

getHours()
Enter fullscreen mode Exit fullscreen mode

Pulling Minutes from the Date object
Returns the minutes from the date object

getMinutes()
Enter fullscreen mode Exit fullscreen mode

Pulling Seconds from the Date object
Returns the seconds from the date object

getSeconds()
Enter fullscreen mode Exit fullscreen mode

Pulling Time from the Date object
Returns the time from the date object

getTime()
Enter fullscreen mode Exit fullscreen mode

Mouse Events

Any change in the state of an object is referred to as an Event. With the help of JS, you can handle events, i.e., how any specific HTML tag will work when the user does something.

click

Fired when an element is clicked

element.addEventListener('click', ()=>{
// Code to be executed when the event is fired
});
Enter fullscreen mode Exit fullscreen mode

oncontextmenu

Fired when an element is right-clicked

element.addEventListener('contextmenu', ()=>{
// Code to be executed when the event is fired
});
Enter fullscreen mode Exit fullscreen mode

dblclick

Fired when an element is double-clicked

element.addEventListener('dblclick', ()=>{
// Code to be executed when the event is fired
});
Enter fullscreen mode Exit fullscreen mode

mouseenter

Fired when an element is entered by the mouse arrow

element.addEventListener('mouseenter', ()=>{
// Code to be executed when the event is fired
});
Enter fullscreen mode Exit fullscreen mode

mouseleave

Fired when an element is exited by the mouse arrow

element.addEventListener('mouseleave', ()=>{
// Code to be executed when the event is fired
});
Enter fullscreen mode Exit fullscreen mode

mousemove

Fired when the mouse is moved inside the element

element.addEventListener('mousemove', ()=>{
// Code to be executed when the event is fired
});
Enter fullscreen mode Exit fullscreen mode

Keyboard Events

keydown

Fired when the user is pressing a key on the keyboard

element.addEventListener('keydown', ()=>{
// Code to be executed when the event is fired
});
Enter fullscreen mode Exit fullscreen mode

keypress

Fired when the user presses the key on the keyboard

element.addEventListener('keypress', ()=>{
// Code to be executed when the event is fired
});
Enter fullscreen mode Exit fullscreen mode

keyup

Fired when the user releases a key on the keyboard

element.addEventListener('keyup', ()=>{
// Code to be executed when the event is fired
});
Enter fullscreen mode Exit fullscreen mode

Errors

Errors are thrown by the compiler or interpreter whenever they find any fault in the code, and it can be of any type like syntax error, run-time error, logical error, etc. JS provides some functions to handle the errors.

try and catch

Try the code block and execute catch when err is thrown

try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
Enter fullscreen mode Exit fullscreen mode

Window Methods

Methods that are available from the window object

alert method

Used to alert something on the screen

alert()
Enter fullscreen mode Exit fullscreen mode

blur method

The blur() method removes focus from the current window.

blur()
Enter fullscreen mode Exit fullscreen mode

setInterval

Keeps executing code at a certain interval

setInterval(() => {
// Code to be executed
}, 1000);
Enter fullscreen mode Exit fullscreen mode

setTimeout

Executes the code after a certain interval of time

setTimeout(() => {
// Code to be executed
}, 1000);
Enter fullscreen mode Exit fullscreen mode

close

The Window. close() method closes the current window

window.close()
Enter fullscreen mode Exit fullscreen mode

confirm

The window.confirm() instructs the browser to display a dialog with an optional message, and to wait until the user either confirms or cancels

window.confirm('Are you sure?')
Enter fullscreen mode Exit fullscreen mode

open
Opens a new window

window.open("https://www.anmolraj.com");
Enter fullscreen mode Exit fullscreen mode

prompt

Prompts the user with a text and takes a value. Second parameter is the default value

var name = prompt("What is your name?", "Anmol");
Enter fullscreen mode Exit fullscreen mode

scrollBy

window.scrollBy(100, 0); // Scroll 100px to the right
Enter fullscreen mode Exit fullscreen mode

scrollTo

Scrolls the document to the specified coordinates.

window.scrollTo(500, 0); // Scroll to horizontal position 500
Enter fullscreen mode Exit fullscreen mode

clearInterval

Clears the setInterval. var is the value returned by setInterval call

clearInterval(var)
Enter fullscreen mode Exit fullscreen mode

clearTimeout

Clears the setTimeout. var is the value returned by setTimeout call

clearTimeout(var)
Enter fullscreen mode Exit fullscreen mode

stop

Stops the further resource loading

stop()
Enter fullscreen mode Exit fullscreen mode

Query/Get Elements

The browser creates a DOM (Document Object Model) whenever a web page is loaded, and with the help of HTML DOM, one can access and modify all the elements of the HTML document.

querySelector
Selector to select first matching element

document.querySelector('css-selectors')
Enter fullscreen mode Exit fullscreen mode

querySelectorAll

A selector to select all matching elements

document.querySelectorAll('css-selectors', ...)
Enter fullscreen mode Exit fullscreen mode

getElementsByTagName

Select elements by tag name

document.getElementsByTagName('element-name')
Enter fullscreen mode Exit fullscreen mode

getElementsByClassName

Select elements by class name

document.getElementsByClassName('class-name')
Enter fullscreen mode Exit fullscreen mode

Get Element by Id

Select an element by its id

document.getElementById('id')
Enter fullscreen mode Exit fullscreen mode

Creating Elements

Create new elements in the DOM

createElement
Create a new element

document.createElement('div')
Enter fullscreen mode Exit fullscreen mode

createTextNode
Create a new text node

document.createTextNode('some text here')
Enter fullscreen mode Exit fullscreen mode

Hi friends if you like it then please like , Share & follow for more. I tried to add most of them. if i forgot something kindly add more in comments.Thank you πŸ™

Discussion (16)

Collapse
lukeshiru profile image
LUKESHIRU • Edited

A few things I would like to add:

  • If you add js next to the triple backtick in your code snippets, you get syntax highlight, which makes reading those way better.
  • The default for script is text/javascript, so there's actually no need for type="text/javascript". You could instead use type="module" which enables modern JS imports.
  • Functions can be written in a variety of ways:
function nameOfFunction (arg) { return arg; }
const nameOfFunction = function (arg) { return arg; }
const nameOfFunction = arg => { return arg; }
const nameOfFunction = arg => arg;
Enter fullscreen mode Exit fullscreen mode
  • Besides innerHTML you also have textContent (ideal to just update the text content of an element). Generally speaking, you should try to avoid innerHTML which is kinda dangerous.
  • if/else/if can be written with nesting as well, which is a matter of preference, but I prefer this because is clearer about the nesting:
if (condition1) {
    // block of code to be executed if condition1 is true
} else {
    if (condition2) {
        // block of code to be executed if the condition1 is false and condition2 is true
    } else {
        // block of code to be executed if the condition1 is false and condition2 is false
    }
}
Enter fullscreen mode Exit fullscreen mode
  • for has other alternatives, like for..of:
for (const item of array) {}
Enter fullscreen mode Exit fullscreen mode
  • Instead of String.prototype.charAt, you can just string[index].
  • String.prototype.replace needs a second argument with the replacement value.
  • There are other ways to join arrays besides Array.prototype.concat, like using spread: [...array1, ...array2]. Is generally more slow, but worth mentioning.
  • Array.prototype.pop not only removes the last element, it also returns it (not ideal when working with immutable environments).
  • Array.prototype.sort takes a method to set the sorting, if not set it defaults to string sorting, which means it puts 100 before 11.
  • Some of the toString methods can be replaced with just a template literal.
  • When working with Date, ideally you should try to use the getUTC methods (getUTCMinutes, getUTCMonth and so on).
  • There is some talk to remove alert, confirm, prompt and dialogs like that from the browsers, so you might be better creating your own.
  • document.getElementsByClassName("foo") can be replaced with document.querySelectorAll(".foo").
  • document.getElementById("foo") can be replaced with document.querySelector("#foo").

Cheers!

Collapse
klukiyan profile image
Kiril Lukiyan

That moment when a comment has way more useful info than the article 😊

Collapse
iftikhar profile image
iftikhar hussain

yeah absolutely.

Collapse
mrdanielschwarz profile image
Daniel Schwarz

You beat me to it!

However, document.querySelector("#foo") instead of document.querySelectorAll("#foo") should do fine since there shouldn't be duplicates of IDs anyway.

Collapse
mightycoderx profile image
MightyCoderX

Just use getElemenyById('foo') for elements with 'foo' id

Collapse
lukeshiru profile image
LUKESHIRU

Indeed! That's a bad copy/paste of mine.

Collapse
emperor100 profile image
Ravikant

Nice content...
(One typo in 11th bullet, protytype)

Collapse
iftikhar profile image
iftikhar hussain

Awesom, you should post the cheatsheet, thanks

Collapse
anmolraj profile image
Anmol Raj Author

Thanks brother..πŸ’š

Collapse
danwood profile image
Dan Wood

Where's the advance part?

Collapse
madza profile image
Madza
Collapse
imtridevsharma profile image
im-tridevsharma

When you print anything on console you must try other options too.
console.log(value) it's general one to log. Other can be used here like console.warn(), console.info(), console.error() and console.dir() Try it.

Collapse
tonypelliccio profile image
Tony Pellicccio

Thanks. Had to refresh my memory on JS. It's funny the DOM thing I know it MS products but had to look them up for JS. Pretty simple to be honest. And it sort of follows C/C++ formatting so there's that too.

Collapse
eltringhamz profile image
Zoe

Nice! Thank you

Collapse
hiv_ft profile image
ft;hiv

Hi:

String REPLACE is wrong. It misses the SECOND parameter.

cfr.:

developer.mozilla.org/en-US/docs/W...

Regards

Niky

Collapse
hiv_ft profile image
ft;hiv

Hi:

Indicate WHAT is returned is in order; example: string match, search...
Indicate also what is returned if not comply (-1, NUL, etc.).

Regards