DEV Community

Cover image for Ultimate JavaScript CheatSheet
Rahul
Rahul

Posted on • Edited on

Ultimate JavaScript CheatSheet

Cheat Sheets our something developers need always for reference. So here I have compiled many JavaScript reference codes. See the classification and find it. This post is helpful for learners and developers.


600+ Free Design resources

Image description

Resources. Freebies. Learn.
We're making things easier on Internet.

Visit - 600+ free design resources



JavaScript Number Method Cheat Sheet

  • toExponential() : Returns a string representing the Number object in exponential notation
  function expo(x, f) {
      return 
      Number.parseFloat(x).toExponential(f);
  }

  console.log(expo(123456, 2)); 
  // -> 1.23e+5
Enter fullscreen mode Exit fullscreen mode
  • toFixed() : formats a number using fixed-point notation
  function financial(x) {
      return Number.parseFloat(x).toFixed(2); 
  }

  console.log(financial(123.456)); 
  // -> 123.46
Enter fullscreen mode Exit fullscreen mode
  • toPrecision() : returns a string representing the Number object to the specified precision
  function precise(x) {
      return
      Number.parseFloat(x).toPrecision(4); 
  }

  console.log(precise(123.456)); 
  // -> 123.5
Enter fullscreen mode Exit fullscreen mode
  • toString() : returns a string representing the specifies Number object
  function hexColour(c) {
      if (c < 256) {
          return Math.abs(c).toString(16); 
      }
      return 0; 
  }

  console.log(hexColour(233)); 
  // -> e9
Enter fullscreen mode Exit fullscreen mode
  • valueOf() : returns the wrapped primitive value of a number object
  const numObj = new Number(42); 
  console.log(typeof numObj); 
  // -> object

  const num = numObj.valueOf(); 
  console.log(num); 
  // -> 42

  console.log(typeof num); 
  // -> number

Enter fullscreen mode Exit fullscreen mode

JavaScript Loops Cheat Sheets

  • For Loop
  for (var i = 0; < 10; i++) {
      console.log(i + ": " + i * 3 + "<br />"); 
  }
  // -> 0: 0<br />
  // -> 1: 3<br />
  // -> ...

  let a = [1, 2, 3]; 
  var sum = 0; 
  for (var i - 0; i <a.length; i++) {
      sum += a[i]; 
  } // pasing an array
  console.log(sum); 
  // -> 6
Enter fullscreen mode Exit fullscreen mode
  • While Loop
  var i = 1;                  // initialize
  while (i < 100) {          // enters the cycle if statement is true
      i *= 2;                 // increment to avoid infinte loop 
      console.log(i + ", "); // output
  } 
  // 2, 
  // 4, 
  // ...
  // 128, 
Enter fullscreen mode Exit fullscreen mode
  • Do While Loop
  var i = 1;                  // initialize
  while (i < 100) {          // enters the cycle asleast once
      i *= 2;                 // increment to avoid infinte loop 
      console.log(i + ", "); // output
  } while (1 < 100); // repeats cycle if statement is true at the end
  // 2, 
  // 4, 
  // ...
  // 128,
Enter fullscreen mode Exit fullscreen mode
  • Break
  for (var i = 0; i < 10; i++) {
      if (i == 5 ) { break; } // stops and exits the cycle
      console.log(i + ", ");  // Lat output number is 4
  }
  // -> 0, 
  // -> 1, 
  // ...
  // -> 4, 
Enter fullscreen mode Exit fullscreen mode
  • Continue
  for (var i = 0; i < 10; i++) {
      if (i == 5 ) { continue; } // skips the rest of the cycle
      console.log(i + ", ");  // skips 5
  }
  // -> 0, 
  // -> 1, 
  // ...
  // -> 9,
Enter fullscreen mode Exit fullscreen mode

JavaScript String Methods Cheat Sheet

  • charAt() : Returns the character at the specified index
  const sentence = "Jeff bezos is now the second richest."; 

  const index = 4; 

  console.log(`The character at index ${index} is ${sentence.charAt(index)}`); 
  // The character at index 4 is f
Enter fullscreen mode Exit fullscreen mode
  • concat() : Joins two or more strings, and returns a copy of the joined strings
  const str1 = "Hello"; 
  cosnt str2 = "World"; 

  console.log(str1.concat(" ", str2)); 
  // -> Hello World

  console.log(str2.concat(", ", str1)); 
  // -> World, Hello
Enter fullscreen mode Exit fullscreen mode
  • replace() : Searches for a match between a substring (or regex) and a string and replaces the matched substring with a new substring
  const p = "Talk is cheap. Show me the work. - Someone"; 

  console.log(p.replace("work", "code")); 
  // -> Talk is cheap. Show me the code. - Someone
Enter fullscreen mode Exit fullscreen mode
  • search() : Searches for a match between a regex and a string, and returns the position of the match
  const paragraph = "The quick brown fox jumps over the lazy dog."; 

  // any character that is not a word character or whitespace
  const regex = /[^\w\s]/g;

  console.log(paragraph.search(regex)); 
  // -> 43
Enter fullscreen mode Exit fullscreen mode
  • slice() : Extracts a part of a string and returns a new string
  const str = "The quick brown fox jumps over the lazy dog."; 

  consolelog(str.slice(31)); 
  // -> the lazy dog

  console.log(str.slice(4, 19)); 
  // -> quick brown fox
Enter fullscreen mode Exit fullscreen mode
  • trim() : Removes whitespace from both ends of a string
  const greeting = "  Hello world!   "; 

  console.log(greeting); 
  // -> Hello world!

  console.log(greeting.trim()); 
  // -> Hello world!
Enter fullscreen mode Exit fullscreen mode
  • substr() : Extracts the character from a string, beginning at a specified start position, and through the specified number of character
  const str = "Mozilla"; 

  console.log(str.substr(1, 2)); 
  // -> oz

  console.log(stre.substr(2)); 
  // -> zilla
Enter fullscreen mode Exit fullscreen mode
  • toLowerCase() : Converts a string to lowercase letters
  const sentence = "Elon became the richest last night."; 

  console.log(sentence.toLowerCase()); 
  // -> elon became the richest last night.
Enter fullscreen mode Exit fullscreen mode

JavaScript Array Method Cheet sheet

  • concat() : Joins two or more arrays, and returns a copy of the joined array
  let array1 = ["a", "b", "c"]; 
  let array2 = ["d", "e", "f"]; 
  let array3 = array1.concat(array2); 

  console.log(array3); 
  // -> Array(6) ["a", "b", "c", "d", "e", "f" ]
Enter fullscreen mode Exit fullscreen mode
  • indexOf() : Search the array for an element and returns its position
  let beasts = ["ant", "bison", "camel", "duck", "bison"]; 

  console.log(beasts.indexOf("bison")); 
  // -> 1

  // start from index 2
  console.log(beasts.indexOf("bison", 2)); 
  // -> 4
Enter fullscreen mode Exit fullscreen mode
  • join() : Joins all elements of an array into a string
  let elements = ["Fire", "Air", "Water"]; 

  console.log(elements.join()); 
  // -> Fire,Air,Water

  console.log(elements.join(" ")); 
  // -> Fire Air Water
Enter fullscreen mode Exit fullscreen mode
  • pop() : Removes the last element of an array, and returns that element
  let plants = ["broccoli", "cauliflower", "cabbage", "kale", "tomato"]; 

  console.log(plants.pop()); 
  // -> tomato

  console.log(plants); 
  // -> Array(4) ["brocxoli", "cauliflower", "cabbage", "kale"]
Enter fullscreen mode Exit fullscreen mode
  • reverse() : Reverses the order of the elements in an array
  let array1 = ["one", "two", "three"]; 
  console.log("array1:", array1); 
  // -> array1: Array(3) [ "one", "two", "three" ]

  let reversed = array1.reverse(); 
  console.log("reversed", reversed); 
  // -> reversed: Array(3) [ "three", "two", "one" ]
Enter fullscreen mode Exit fullscreen mode
  • shift() : Removes the first element of an array, and returns that element
  let array1 = [1, 2, 3]; 

  let firstElement = array1.shift(); 

  console.log(array1); 
  // -> Array [ 2, 3 ]
Enter fullscreen mode Exit fullscreen mode
  • sort() : Sorts the element of an array
  let months = ["March", "Jan", "Feb", "Dec"]; 
  months.sort(); 

  console.log(months); 
  // -> Array(4) [ "Dec", "Feb", "Jan", "March" ]
Enter fullscreen mode Exit fullscreen mode
  • toString() : Converts an array to string, and returns the result
  const array1 = [1, 2, "a", "1a"]; 

  console.log(array1.toString()); 
  // -> 1,2,a,1a
Enter fullscreen mode Exit fullscreen mode

JavaScript Datatypes Cheat Sheet

var age = 18; // Number

var name = "Rahul"; // string

var name = {first:"Rahul", last:"Singh"}; // object

var truth = false; // boolean

var sheets = ["HTML", "CSS", "JS"]; // array

var a; typeof a; // undefined 

var a = null; // value null
Enter fullscreen mode Exit fullscreen mode

JavaScript Operators Cheat Sheet

a = b + c - d; // addition, substraction

a = b * (c / d); // multiplication, division

x = 100 % 48; // modulo. 100 / 48 remainder = 4

a++; b--; // postfix increment and decrement
Enter fullscreen mode Exit fullscreen mode

Variables cheat sheet

  • var : The most common variable. Can be reassigned but only accessed within a function. Variables defined with var move to the top when code is executed.
  • const : Cannot be reassigned and not accessible before they appear within the code
  • let : Similar to const, however, let variable can be reassigned but not re-declared
var a;            // variable
var b = "init";   // string
var c = "Hi" + "" + "Rahul"; // "Hi Rahul"
var d = 1 + 2 + "3";   // "33"
var e = [2,3,5,8];   // array
var f = false;       // boolean
var g = /()/; // RegEx
var h = function(){};   // function object
const PI = 3.14;        // constant
var a = 1, b = 2, c = a + b;    // one line
let z = 'zzz';        // block scope local variable
Enter fullscreen mode Exit fullscreen mode

Get Date Methods Cheet Sheet

  • getFullYear() : Returns the year of the specified date according to local time
  const moonLanding = new Date("January 08, 69 00:20:10"); 

  console.log(moonLanding.getFullYear()); 
  // -> 1969

Enter fullscreen mode Exit fullscreen mode
  • getMonth() : Returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).
  const moonLanding = new Date("January 08, 69 00:20:10"); 

  console.log(moonLanding.getMonth()); // (January gives 0)
  // -> 6
Enter fullscreen mode Exit fullscreen mode
  • getDate() : Returns the day of the month for the specified date according to local time
  const birthday = new Date("June 16, 2004 23:14:00"); 
  const date1 = birthday.getDate(); 

  console.log(date1); 
  // -> 19
Enter fullscreen mode Exit fullscreen mode
  • getHours() : Returns the hour for the specified date, according to local time
  const birthday = new Date("June 16, 04 4:20"); 

  console.log(birthday.getHours()); 
  // -> 4
Enter fullscreen mode Exit fullscreen mode
  • getMinutes() : Returns the minutes in the specified date according to local time
  const birthday = new Date("June 16, 04 04:10"); 

  console.log(birthday.getMinutes());
  // -> 20
Enter fullscreen mode Exit fullscreen mode
  • getSeconds() Returns the seconds in the specified date according to local time
  const moonLanding = newDate("June 16, 69 00:23:11"); 

  console.log(moonLanding.getSeconds()); 
  // -> 18
Enter fullscreen mode Exit fullscreen mode

Hey Guy's subscribe to my weekly newsletter and getting every post link on your mail in the weekend. No daily mails and spamming.

Please subscribe -> Subscribe to RAHULISM


😎Thanks For Reading | Happy Coding⚡

Get weekly newsletter of amazing articles i posted this week and some offers or announcement. Subscribe from Here

Top comments (15)

Collapse
 
knufle profile image
Marcel

Hey, great article! Just one thing the "charAt()" example actually returns an empty space " ", not a "f"

Collapse
 
rahxuls profile image
Rahul

Agreed.

Thank for reading i am happy i have someone to read too.

Collapse
 
gwmccull profile image
Garrett McCullough

your toExponential and toPrecision examples are broken. If a return statement is on a line by itself, it will just return undefined.

Collapse
 
therealokoro profile image
Okoro Redemption

Beautiful Post.

Check out this Utility JavaScript Library I made that is sure to ease your workflow.
It contains methods and functions that manipulates the DOM, Strings, Numbers, Objects and even Mathematical operations, and other utility functions

Its called ToolJS and can be found on Github and NPM

npm install @redeakaa/tooljs
Enter fullscreen mode Exit fullscreen mode

You can check out this series I posted here on dev.to

Introduction to ToolJS. A JavaScript Utility Library

Collapse
 
kwiat1990 profile image
Info Comment hidden by post author - thread only accessible via permalink
Mateusz Kwiatkowski

It seems like the whole "the 2021" part of the article is missing. I don't want to be rude but all here is like fundamentals of JS and not some bright new features, which could help one in 2021. For that reason I would say the article's title is misleading at best and a clickbait at worst.

Collapse
 
centanomics profile image
Cent

Hi. Just wanted to say that the example for getMonth() is using getFullYear().

Thanks for the useful article!

Collapse
 
learnbyexample profile image
Sundeep
Collapse
 
eladc profile image
Elad Cohen

Great, thanks!
You have a mistake on your Do While Loop.

Collapse
 
matteodem profile image
Matteo De Micheli

Awesome blog post, I already really like the new includes method for Strings and Arrays 🎉

Collapse
 
eecolor profile image
EECOLOR

I think this is more complete as a reference: developer.mozilla.org/en-US/docs/W...

Collapse
 
tiiunder profile image
Felix G

I will steal some of those snippets for my personal cheat sheet ;-) Thank you!

Some comments have been hidden by the post's author - find out more