In the vast world of programming, JavaScript stands out as one of the most versatile and widely used languages. Whether you’re a seasoned developer or just starting your coding journey, having a comprehensive cheatsheet for JavaScript can be invaluable. This webpage aims to provide you with a detailed JavaScript cheatsheet, covering essential concepts, syntax, and tips to enhance your coding experience.

Comments

// this is a comment 
/* or this is a comment */

This code will be ignored. Comments are generally a bad idea, your code should be explicit enough as it is. More Info

Variables

Variable creation

let school = "SheCodes";
let fullPackage = "SheCodes Pro";
let projects = 4;
let awesome = true;

More Info

Variable operations

let x = 2;
let y = 3;
let z = x + y; // 5

let city = "Lisbon";
let country = "Portugal";
let place = city + " " + country; //Lisbon Portugal

Variable data Types

let age = 23; // Number
let name = "Julie"; // String
let canCode = true; // Boolean, could also be false

More Info

Structure structure types

let students = ["Kate", "Julie", "Mariana"]; // Array

let kate = {
  firstName: "Kate",
  lastName: "Johnson",
  age: 23,
  canCode: true,
}; // Object

More Info

Alerts & Prompts

Alert

alert("Olá");

let name = "Angela";
alert(name);

More Info

Prompt

let firstName = prompt("What is your first name");
let lastName = prompt("What is your last name");
let fullName = firstName + " " + lastName;
alert(fullName);

More Info

If else

if statement

let country = prompt("What country are you from?");

if (country === "Portugal") {
  alert("You are cool");
}

if (country !== "Portugal") {
  alert("Too bad for you");
}

More Info

if else statement

let age = prompt("How old are you?");

if (age < 18) {
  alert("You cannot apply");
} else {
  alert("You can apply");
}

More Info

Nested if else statements

if (age < 18) {
  alert("you can't apply");
} else {
  if (age > 120) {
    alert("you can't apply");
  } else {
    alert("you can apply");
  }
}

More Info

Logical Or

if (age < 18 || gender === "male") {
  alert("You can't vote in India");
}

The code will be executed if one statement is true.

More Info

Logical And

if (continent === "Europe" && language === "Portuguese") {
  alert("You are from Portugal 🇵🇹");
} else {
  alert("You are not from Portugal");
}

The code will be executed if both statements are true.

More Info

Comparison and Logical Operators

2 > 3 // false 
2 < 3 // true 
2 <= 2 // true
3 >= 2 // true
2 === 5 // false 
2 !== 3 // true 
1 + 2 === 4 // false

More Info

Strings

Creating a string

let name = "SheCodes"; // "SheCodes"

More Info

String concatenation

let firstName = "Julie";
let lastName = "Johnson";
let fullName = firstName + " " + lastName; // "Julie Johnson"

//or
let fullName = `${firstName} ${lastName}`;

Trim

let city = " Montreal  ";
city = city.trim(); // "Montreal"

More Info

Replace

let city = "Montreal";
city = city.replace("e", "é"); // "Montréal"

More Info

toLowerCase

let city = "Montreal";
city = city.toLowerCase(); // "montreal"

More Info

toUpperCase

let city = "Montreal";
city = city.toUpperCase(); // "MONTREAL"

More Info

Template literals

let city = "Denver";
let sentence = `Kate is from ${city}`; // Kate is from Denver

More Info

Arrays

Array declaration

let myList = [];
let fruits = ["apples", "oranges", "bananas"];
myList = ['banana', 3, go, ['John', 'Doe'], {'firstName': 'John', 'lastName': 'Smith'}]

More Info

Access an Array

fruits
fruits[0]
fruits[1]
fruits[2]
fruits[3]

More Info

Update an Array item

fruits[1] = "Mango";
fruits[1] = 3;

More Info

while loop

let times = 0;
while (times < 10) {
  console.log(times);
  times = times + 1;
}

More Info

forEach loop

let fruits = ['apples', 'oranges', 'bananas'];
fruits.forEach(function(fruit) {
  alert("I have " + fruit + " in my shopping bag");
});

More Info

do while loop

let times = 0;
do {
  console.log(times);
  times = times + 1;
} while(times < 10)

More Info

for loop

for (let i = 0; i < 10; i++) {
  console.log("i is " + i);
}

for (let i = 0; i < myList.length; i++) {
  alert("I have " + myList[i] + " in my shopping bag");
}

More info

Remove first item

fruits.shift()

More Info

Dates

Get current time

let now = new Date();

More Info

Create a date

let date = Date.parse("01 Jan 2025 00:00:00 GMT");

More Info

Get date data

let now = new Date();
now.getMinutes(); // 0,1,2, 12
now.getHours(); //1, 2, 3, 4
now.getDate(); //1, 2, 3, 4
now.getDay(); // 0, 1, 2
now.getMonth(); // 0, 1, 2
now.getFullYear(); // 2021

More Info

Numbers

Round

Math.round(4.7) // 5

More Info

Floor

Math.floor(4.7) // 4

More Info

Ceil

Math.ceil(4.7) // 5

More Info

Min

Math.min(2, 5, 1) // 1

More Info

Max

Math.max(2, 5, 1); // 5

More Info

Random

Math.random(); // 0.47231881595639025

More Info

Objects

Creating a new object

let fruit = new Object(); // "object constructor" syntax

let user = {}; // "object literal" syntax

let student = {
  firsName: "Julie",
  lastName: "Johnson",
};

let anotherStudent = {
  firstName: "Kate",
  lastName: "Robinson",
  female: true,
  greet: function () {
    alert("Hey");
  },
};

More Info

Reading an object properties

let user = {
  firstName: "Lady",
  lastName: "Gaga",
  gender: "female",
};

alert(user.firstName); // Lady
alert(user.lastName); // Gaga

// or
alert(user["firstName"]); // Lady
alert(user["lastName"]); // Gaga

More Info

Adding object properties

let user = {
  firstName: "Lady",
  lastName: "Gaga",
  gender: "female",
};

user.profession = "Singer";

More Info

Object Arrays

let users = [
  {
    firstName: "Bradley",
    lastName: "Cooper",
  },
  {
    firstName: "Lady",
    lastName: "Gaga",
  },
];

users.forEach(function (user, index) {
  for (let prop in user) {
    alert(prop + " is " + user[prop]);
  }
});

More Info

Enumerating the properties of an object

let user = {
  firstName: 'Lady',
  lastName: 'Gaga',
  gender: 'female'
}


for(let prop in user) {
  alert(prop); // firstName, lastName, gender
  alert(user[prop]); // 'Lady', 'Gaga', 'female'
}

More Info

Functions – JavaScript Cheatsheet

JS Functions

function sayFact() {
  let name = prompt("What's your name?");

  if (name === "Sofia") {
    alert("Your name comes from the Greek -> Sophia");
  }
}

sayFact();

Note: Piece of code that does one or more actions

More info

JS Functions Parameters

function fullName(firstName, lastName) {
  alert(firstName + " " + lastName);
}

let firstName = prompt("What's your first name?");
let lastName = prompt("What's your last name?");
fullName(firstName, lastName);
fullName("Kate", "Robinson");

More info

JS Functions Return

function add(x, y) {
  return x + y;
}

let result = add(3, 4);
let result2 = add(result, 0);


function getFullName(firstName, lastName) {
  let fullName = firstName + " " + lastName;
  return fullName;
}

let userFullName = getFullName("Kate", "Robinson");
alert(userFullName); // Kate Robinson
alert(getFullName("Julie", "Smith")); // Julie Smith

More info

Closures

function hello() {
  function go(name) {
    alert(name);
  }

  let name = "SheCodes";
  go(name);
}

hello();

More info

Debugging

Console.log

console.log(name);
console.log("Let's code!");

Note: Outputs a message to the web console.

More Info

Selectors

QuerySelector

let li = document.querySelector("li");
let day = document.querySelector(".day");
let paragraph = document.querySelector("ul#list p");

Note: Returns the first element (if any) on the page matching the selector.

More Info

QuerySelectorAll

let lis = document.querySelectorAll("li");
let paragraphs = document.querySelectorAll("li#special p");

Note: Returns all elements (if any) on the page matching the selector.

More Info

Events

Creating an event listener

function sayHi() {
  alert("hi");
}

let element = document.querySelector("#city");
element.addEventListener("click", sayHi);

Note: The sayHi function will be executed each time the city element is clicked. Click is the most common event type but you can also use click | mouseenter | mouseleave | mousedown | mouseup | mousemove | keydown | keyup.

More Info

setTimeout

function sayHello() {
  alert('Hello')
}
setTimeout(sayHello, 3000);

Note: It will only alert Hello after a 3 second delay

More Info

setInterval

function sayHello() {
  alert('Hello')
}
setInterval(sayHello, 3000);

Note: It will say Hello every 3 seconds

More Info

AJAX

AJAX with Fetch

let root = 'https://jsonplaceholder.typicode.com'
let path = 'users/1'

fetch(root + '/' + path)
  .then(response => (
    response.json()
  ))
  .then(json => (
    console.log(json)
  ));

Note: We recommend axios instead

More Info

AJAX with Axios

<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  </head>
  <body>
    <script>
      function showUser(response) {
        alert(`The user name is ${response.data.name}`);
      }

      let url = "https://jsonplaceholder.typicode.com/users/1";
      axios.get(url).then(showUser);
    </script>
  </body>
</html>

More Info

Element manipulation

HTML classes

let li = document.querySelector("li#special");
li.classList.remove("liked");
li.classList.add("something");

Update the element class names

More Info

HTML content

let li = document.querySelector("li")
li.innerHTML = "Hello World";

Update the HTML content of the selected element.

More Info

Forms

<form>
  <input type="text" id="email" />
</form>
<script>

function signUp(event) {
  event.preventDefault();
  let input = document.querySelector("#email");
  console.log(input.value);
}
let form = document.querySelector("form");
form.addEventListener("submit", signUp);
</script>

Note: The event will be triggered by clicking the button or pressing enter.

More info

HTML Attributes Manipulation

let button = document.querySelector("input#button");
button.setAttribute("disabled", "disabled");

let email = document.querySelector("input#email");
email.removeAttribute("required");

Update the element attributes

More info

CSS Styles

let boxElement = document.querySelector("#box");
boxElement.style.backgound = "red";
boxElement.style.padding = "10px 20px";
boxElement.style.marginRight = "10px";

Changes the CSS style of an element.

Note: We recommend using classList instead

More Info

APIs

Geolocation API

function handlePosition(position) {
  console.log(position.coords.latitude);
  console.log(position.coords.longitude);
}

navigator.geolocation.getCurrentPosition(handlePosition)

The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

More Info

Whether you’re a beginner learning the ropes or an experienced developer fine-tuning your skills, mastering JavaScript is an ongoing journey. Use this cheatsheet as a guide, and let it be a tool that empowers you to create robust and efficient web applications.

Happy coding!

Also Check: Bootstrap Cheat Sheet Download PDF

Categorized in: