JavaScript cheatsheet

Comments

// const a = "a";  for one-line comment

/* const b = "b";
const c = "c";   for multiple lines*/

Variables

Four kind of variable declarations with different scopes:

  1. var, function/global-scope and hoisting

  2. let, represented here

  3. const, no reassignments, block-scope, promotes FP style

  4. global variable without declaration (not recommended!)

let

let counter = 0;                     // can be changed
counter += 1;

const

const studentName = "Teemu Teekkari"; // cannot be changed

Logging

console.log("Hello from console!");

Logging variables:

const studentName = ("Teemu Teekkari");
console.log(studentName); // Teemu Teekkari

Concatenating strings:

  1. Plus sign (+) can be used to concatenate strings

const studentName = ("Teemu Teekkari");
console.log("Hello " + studentName + " from console.log");
  1. Template literals more readable if multiple variables are included

const studentName = ("Teemu Teekkari");
console.log(`Hello ${studentName} from console.log`);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Data types

Primitive data types

string

const studentName = "Teemu Teekkari";
console.log(typeof studentName);      // string

number

const studentAge = 25;
console.log(typeof studentAge);      // number

boolean

const isStudentActive = true;
console.log(typeof isStudentActive); // boolean

undefined

let student;
console.log(student);               // undefined

bigint and symbol

Rarely used (not needed in this course)

Object

key-value pairs: keys are strings, values can be of any type

const student = {
  name: "Teemu Teekkari",
  age: 25,
  major: "Pervasive computing"
};

console.log(typeof student);      // object

const now = new Date();
console.log(typeof now);          // object

Function

const add = (a, b) => a + b;
console.log(typeof add);          // function

function log() {
  console.log("Hello world!");
}
console.log(typeof log);          // function

Operators

Arithmetic

const a = 5;
const b = 10;

console.log(a + b); // 15
console.log(a - b);  // -5
console.log(a * b); // 50
console.log(a / b); // 0.5
console.log(a % b); // 5

let c = 0;
c++;
console.log(c); // 1
c--;
console.log(c); // 0

Comparison

const a = 5;
const b = 10;
const c = "10";

console.log(a == b);  // false
console.log(b == c);  // true
console.log(b === c); // false, Use === and !== instead of == and !=
console.log(b != c);  // false
console.log(b !== c); // true
console.log(a > b);   // false
console.log(a < b);   // true
console.log(b > c);   // false
console.log(b < c);   // false

Logical

const a = true;
const b = false;

console.log(a && b);    // false
console.log(a || b);    // true
console.log(!a);        // false
console.log(!(a && b)); // true

Control structures

If-else

Two if-elses:

// 1. a usual way
const a = true;

if (a) {
  console.log("Condition was true");
} else {
  console.log("Condition was false");
}

// 2. an alternative conditional operator
console.log(`a is ${a?"true":"false"}`);

Multiple and nested if-elses:

const age = 18;

if (age < 18) {
  console.log("Age under 18");
} else if (age === 18) {
  console.log("Age is exactly 18");
} else if (age === 19) {
  console.log("Age is exactly 19");
} else {
  console.log("Age is over 20");
}

Switch

const age = 18;

switch (age) {
  case 18:
    console.log("Age 18");
    break;
  case 19:
    console.log("Age 19");
    break;
  case 20:
    console.log("Age 20");
    break;
  default:  //Remember to include!
    console.log("Age not 18, 19 or 20");
    break;
}

For

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

While

let i = 0;

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

while (i < 10) {
  console.log(i);

  if (i % 2 !== 0) {
    break;
  }
  i++;
}

Do While

let i = 0;

do {
  console.log(i);
  i++;
} while (i < 10);

Functions

1. Traditional function declaration

Slightly longer syntax:

function printHelloWorld() {
  console.log("Hello World!");
}

2. Fat arrow function declaration (ES6)

Shorter syntax. As a one-liner:

const printHelloWorld = () => console.log("Hello World!");

As a multi-liner:

const printTwoTimes = () => {
  console.log("Hello darkness my old friend");
  console.log("I've come to talk with you again");
};

Formal parameters (function parameters)

1. Traditional function

function add(x, y) {
  console.log(x + y);
}

2. Fat arrow function

const add = (x, y) => console.log(x + y);

Actual parameters (arguments)

passed during function call:

add(1, 2); // prints 3 to console

Attention

Compiled languages usually check the existence of necessary parameters beforehand. As a scripting language, JavaScript is not compiled by default, thus a missing parameter will be noticed only during runtime. At that point, it might cause a runtime error if undefined cannot be accepted.

Return values

Traditional and fat arrow functions return values in a different manner; modified add() function exemplifies this:

function add(x, y) {
  return x + y;
}
const three = add(1, 2); // Variable three now has a value of 3

As a one-liner, fat arrow function returns a value implicitly:

const add = (x, y) => x + y;
const three = add(1, 2); // Variable three now has value of 3

..whereas a multi-line, fat arrow function provides no implicit return:

const add = (x, y) => {
  console.log(x);
  console.log(y);
  return x + y;
};
const three = add(1, 2); // Variable three now has value of 3

Arrays

Common functions

const names = ["Teemu Teekkari", "Teppo Testaaja"];
console.log(names[0]);            // Teemu Teekkari
names.reverse();
console.log(names[0]);            // Teppo Testaaja
console.log(names.length);
names.push("Jaakko JavaScript");
console.log(names[2]);            // Jaakko JavaScript
console.log(Array.isArray(names));// true

Printing array content

const names = ["Teemu Teekkari", "Teppo Testaaja", "Jaakko JavaScript"];

for (let i = 0; i < names.length; i++) {
  console.log(names[i]);
}

// Or
names.map(name => console.log(name));

DOM functions

Accessing elements

// element with id of example
const elementWithId = document.getElementById("example");  //#example in CSS

// First div element with class swot
const elementWithClass = document.querySelector("div.swot");

// A collection of all elements that match the selector
const elementsWithClass = document.querySelectorAll("div.swot");

// A collection of all elements with specified class name
const elementsWithClass = document.getElementsByClassName("swot");

Adding elements

const newHeader = document.createElement("h2");
newHeader.innerHTML = `<strong>Nice</strong> work!`;

const parent = document.getElementById("container");
parent.appendChild(newHeader);

Adding text to elements

const newHeader = document.createElement("h2");
newHeader.innerText = "New text";

const parent = document.getElementById("container");
parent.appendChild(newHeader);

Removing elements

const removeThis = document.getElementById("example");

const parent = removeThis.parentNode;
parent.removeChild(removeThis);

Element attributes

const button = document.getElementById("btn");

// Add attribute
button.setAttribute("disabled", "");

// Remove attribute if it exists
if (button.hasAttribute("disabled")) {
  button.removeAttribute("disabled");
}

Element classes

const button = document.getElementById("btn");

button.classList.toggle("cool");
button.classList.contains("cool");
button.classList.add("cool");
button.classList.remove("cool");

Attaching event listeners

Available events

const button = document.getElementById("btn");

const sayHello = () => console.log("Hello world!");
button.addEventListener("click", sayHello);

Input value in event listener

const input = document.getElementById("input");
const printInput = (e) => console.log(e.target.value);

input.addEventListener("input", printInput);