Last modified on 01 Oct 2021.

Quick references for fundamental things in JavaScript.

Miscellaneous

  • Using // for 1 line comment, /* */ for multi-line comment.
  • End of each command by ;.
  • Variables and function name are case sensitive.
  • Variables / functions should be named in the form of nameOfVariable.
    • Naming a constant: const FAV_PET = 'Cat';.
    • UpperCamelCase should be used by convention for ES6 class names.
  • Using \ for special characters, for example, \" for a " inside a "".
  • '' can be used inside a "" and vice versa.

Practice directly on the browser

Open the browser (I use Chrome), press F12 to open the Inspect window, then choose tab Console. Now, you can practice on this console window, for example, try with 1+1 and press Enter.

ES6

Concise things

// Concise Object Literal Declarations
const getMousePosition = (x, y) => ({ x, y });
// Concise Declarative Functions
const person = {
  name: "Taylor",
  sayHello() {
    return `Hello! My name is ${this.name}.`;
  }
};

Getters and setters

class Book {
  constructor(author) {
    this._author = author;
  }
  // getter
  get writer() {
    return this._author;
  }
  // setter
  set writer(updatedAuthor) {
    this._author = updatedAuthor;
  }
}
const lol = new Book('anonymous');
console.log(lol.writer);  // anonymous
lol.writer = 'wut';
console.log(lol.writer);  // wut

Export/Import to share code blocks

// file ./math_funcs.js
const add = (x, y) => {return x + y};
const subtract = (x, y) => {return x - y};
export { add, subtract }; // can be imported in other scripts

// file ./math_default.js only has 1 export
export default function(x, y) { // without name
  return x + y;
}
// main.js
import {add, subtract } from './math_funcs.js';
import * as myMathModule from "./math_functions.js"; // everything

import anything from './math_default.js'; // from export default

Declare variables & Scopes

var varName; // global scope
let varName; // ES6, block scope (inside {} or function,...)
const varName; // ES6, can't be changed
function funcName(){
  oopsGlobal = 5;  // without `var`, it's a global variable
}
oppsGlobal; // returns 5

Difference between var, let and const,

var a = 1;
var a = 2; // ok, a=2 now
a = 5; // a=5 now
let c = 1;
let c = 2; // error
c = 3; // c=3 now
const b = 1;
const b = 2; // error
b = 2 // error
const s = [1, 2, 3];
s = [1, 2, 4]; // error
s[2] = 4; // OK

Output

myName = "Thi"
console.log("I'm " + myName + ".");
console.log(`I'm ${myName}.`); // ES6

Basic operators

Check more operators & more operators with Math.

i = i + 1; // i++; // i += 1;
i = i - 1; // i--; // i -= 1;
i = i * 3; // i *= 3;
i = i / 2; // i /= 2;

11 % 3 // = 2, remainder
Math.random(); // give a random number between 0 and 1
Math.floor(); // round to its nearest whole number

parseInt("007a"); // give number 7
parseInt("11", 2); // give number 3, "2" is radix

Conditional statements if / switch

  • Comparison Operators: <, ==, === (strict equality), >, >=, <=, !=, !== (strict inequality).
    • Difference between == and ===: 3=='3' (true), 3==='3' (false).
    • Difference between != and !==: 3!='3' (false), 3!=='3' (true).
  • Logical operators: &&, ||, !.
  • Short-circuit evaluation: let a = b || 'Thi'; (if b isn’t defined yet, a takes value 'Thi')
  • Ternary Operator: isNightTime ? console.log('Yes!') : console.log('No!');. We can use multiple nested ternary.
if (true){
  // commands
}

if (true){
  // commands
} else if (true){
  // commands
} else{
  // commands
}
let var = 'papaya';
switch (var) {
  case 'val1':
    // commands
    break;
  case 'val2':
    // commands
    break;
  default:
    // commands
    break;
}

You can remove break; to apply the same result for multiple cases.

Functions

// ES6 way
const rectangleArea = (width=10, height=5) => {
  let area = width * height;
  return area;
};
// if there is no parameter
const <func> = () => {};

// if there is only one parameter
const <func> = <para> => {};

// single line: no need "{}"
const sumNumbers = number => number + number;

Older ways (ES5),

function <funcName>(<para>){
  // commands
}

Rest parameter (ES6)

const last_element = (...args) => {
  return args[-1];
}
last_element(1,2,3); // 3

Spread Operator (ES6)

const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // 89

Strings

Check more methods.

var a = 'Anh-Thi' + 'Dinh'; // plus the strings
a.length; // length of the string
a[0]; // first letter of the string
a[3]; // 4th letter
a[a.length - 1]; // last letter

a[0] = 'D'; // !!! CAN'T change an individual word

Special characters: \' (single quote), \" (double quote), \\(backslash), \n (newline), \r (carriage return), \t (tab), \b (word boundary), \f (form feed).

Arrays

Check more methods.

var arrName = ['a', 1, 'c'];
var nestedArr = [[1, 2], [3, 4]];

arrName[0] = 2; // 1st element is changed (different from string!)
nestedArr[1]; // gives [3, 4]

arrName.push(5); // add 5 at the END of an array
arrName.unshift(6); // add 6 at the BEGINNING of an array

popedElement = arrName.pop() // remove the LAST element of an array
shiftedElement = arrName.shift() // remove the FIRST element of an array

Objects

var myObj = {
  top: "hat",
  "bottom": "pants"
};

// CHECK PROPERTIES
myObj.hasOwnProperty("top");    // true
myObj.hasOwnProperty("middle"); // false
// Accessing Object Properties
myObj.top; // dot
myObj["bottom"]; // bracket

var pos = "top";
myObj[pos]; // via a variable
myObj.top = "T-shirt"; // Update object properties
myObj.middle = "New shoe"; // Add new properties
delete myObj.middle; // Delete a property

We can use object for lookups instead of using if..else or switch,

var alpha = {1:"A", 2:"B", 3:"C"};
value = 2;
alpha[value]; // instead of using if value==2 or switch value...

We can create a nested object inside an object.

Prevent object mutation,

let obj = {
  name:"FreeCodeCamp",
  review:"Awesome"
};
Object.freeze(obj); // obj can't be changed

Destructuring Assignment (ES6)

Extract values from object,

const user = {name: "Thi", age: 30};
const {name, age} = user; // name="Thi", age=30

Assign variable from object,

const {name: uName, age: uAge} = user; // uName="Thi", uAge=30

Assign Variables from Nested Objects,

const user = {
  anhThi: { 
    age: 30,
    email: '[email protected]'
  }
};
const {anhThi: {age, email}} = user;
const {anhThi: {age: userAge, email: userEmail}} = user;

Assign Variables from Arrays,

const [a, b] = [1, 2, 3, 4, 5, 6];
console.log(a, b); // 1, 2
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c); // 1, 2, 5

Assignment with the Rest Parameter to Reassign Array Elements,

const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
console.log(a, b); // 1, 2
console.log(arr); // [3, 4, 5, 7]

Pass an Object as a Function’s Parameters,

const profileUpdate = ({ name, age, nationality, location }) => {
  // do something with these fields
}

JSON

JavaScript Object Notation or JSON is a related data interchange format used to store data,

var ourMusic = [
  {
    "artist": "Daft Punk",
    "title": "Homework",
    "release_year": 1997,
    "formats": [ 
      "CD", 
      "Cassette", 
      "LP"
    ],
    "gold": true
  }, // first artist
  {
  ...
  } // second artist
];

To access "CD": ourMusic[0].formats[0].

Iterate with while / for / do..while loops

Check more statements.

while (<conditions>){
  // commands
}
do{
  // commands
} while (<conditions>);
for (var i=0; i<5; i++){
  // commands
}
// Iterate odd numbers
for (var i=0; i<5; i+=2){
  // commands
}
// Count backwards
for (var i=10; i?5; i-=2){
  // commands
}

References