JavaScript

Anh-Thi Dinh
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 Ent.

ES6

  • "ES" = "ECMAScript" ~ "Javascript".
  • Most of browsers use ES6 but not all.
  • ES6 = ES2015
  • New features: Arrow functions, Classes, Modules, Promises, Generators, let and const.

Concise things

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

Getters and setters

1class Book {
2  constructor(author) {
3    this._author = author;
4  }
5  // getter
6  get writer() {
7    return this._author;
8  }
9  // setter
10  set writer(updatedAuthor) {
11    this._author = updatedAuthor;
12  }
13}
14const lol = new Book('anonymous');
15console.log(lol.writer);  // anonymous
16lol.writer = 'wut';
17console.log(lol.writer);  // wut

Export/Import to share code blocks

1// file ./math_funcs.js
2const add = (x, y) => {return x + y};
3const subtract = (x, y) => {return x - y};
4export { add, subtract }; // can be imported in other scripts
5
6// file ./math_default.js only has 1 export
7export default function(x, y) { // without name
8  return x + y;
9}
1// main.js
2import {add, subtract } from './math_funcs.js';
3import * as myMathModule from "./math_functions.js"; // everything
4
5import anything from './math_default.js'; // from export default

Declare variables & Scopes

1var varName; // global scope
2let varName; // ES6, block scope (inside {} or function,...)
3const varName; // ES6, can't be changed
1function funcName(){
2  oopsGlobal = 5;  // without `var`, it's a global variable
3}
4oppsGlobal; // returns 5
Difference between var, let and const
1var a = 1;
2var a = 2; // ok, a=2 now
3a = 5; // a=5 now
1let c = 1;
2let c = 2; // error
3c = 3; // c=3 now
1const b = 1;
2const b = 2; // error
3b = 2 // error
1const s = [1, 2, 3];
2s = [1, 2, 4]; // error
3s[2] = 4; // OK
var is "function" scope whereas log and const are "block" scope.
1function someFn() {
2  if (true) {
3    var localVar=1000
4    console.log(localVar)      //ok
5  }
6  console.log(localVar)        //ok
7  function nested() {
8    console.log(localVar)      //ok
9  }
10}
11console.log(localVar)      //error
1function someFn() {
2  if (true) {
3    let localVar=1000
4    console.log(localVar)      //ok
5  }
6  console.log(localVar)        //error
7  function nested() {
8    console.log(localVar)      //error
9  }
10}
11console.log(localVar)      //error

Output

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

Basic operators

1i = i + 1; // i++; // i += 1;
2i = i - 1; // i--; // i -= 1;
3i = i * 3; // i *= 3;
4i = i / 2; // i /= 2;
5
611 % 3 // = 2, remainder
1Math.random(); // give a random number between 0 and 1
2Math.floor(); // round to its nearest whole number
3
4parseInt("007a"); // give number 7
5parseInt("11", 2); // give number 3, "2" is radix

Statements

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.
1if (true){
2  // commands
3}
4
5if (true){
6  // commands
7} else if (true){
8  // commands
9} else{
10  // commands
11}
1let var = 'papaya';
2switch (var) {
3  case 'val1':
4    // commands
5    break;
6  case 'val2':
7    // commands
8    break;
9  default:
10    // commands
11    break;
12}
You can remove break; to apply the same result for multiple cases.

Iterate with while / for / do..while loops

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

Try...catch

1try {
2  // statements to try
3} catch (err) {
4  // catch statements to handle err
5} finally {
6  // statements performed even there is err
7}
Nested? 👉 Read these clear examples on MDN.

Functions

1// ES6 way
2const rectangleArea = (width=10, height=5) => {
3  let area = width * height;
4  return area;
5};
1// if there is no parameter
2const <func> = () => {};
3
4// if there is only one parameter
5const <func> = <para> => {};
6
7// single line: no need "{}"
8const sumNumbers = number => number + number;
Older ways (ES5),
1function <funcName>(<para>){
2  // commands
3}
Rest parameter (ES6)
1const last_element = (...args) => {
2  return args[-1];
3}
4last_element(1,2,3); // 3
5
Spread Operator (ES6)
1const arr = [6, 89, 3, 45];
2const maximus = Math.max(...arr); // 89

Strings

1var a = 'Anh-Thi' + 'Dinh'; // plus the strings
2a.length; // length of the string
3a[0]; // first letter of the string
4a[3]; // 4th letter
5a[a.length - 1]; // last letter
6
7a[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

1var arrName = ['a', 1, 'c'];
2var nestedArr = [[1, 2], [3, 4]];
3
4arrName[0] = 2; // 1st element is changed (different from string!)
5nestedArr[1]; // gives [3, 4]
6
7arrName.push(5); // add 5 at the END of an array
8arrName.unshift(6); // add 6 at the BEGINNING of an array
9
10popedElement = arrName.pop() // remove the LAST element of an array
11shiftedElement = arrName.shift() // remove the FIRST element of an array

Objects

1var myObj = {
2  top: "hat",
3  "bottom": "pants"
4};
5
6// CHECK PROPERTIES
7myObj.hasOwnProperty("top");    // true
8myObj.hasOwnProperty("middle"); // false
1// Accessing Object Properties
2myObj.top; // dot
3myObj["bottom"]; // bracket
4
5var pos = "top";
6myObj[pos]; // via a variable
1myObj.top = "T-shirt"; // Update object properties
2myObj.middle = "New shoe"; // Add new properties
3delete myObj.middle; // Delete a property
We can use object for lookups instead of using if..else or switch
1var alpha = {1:"A", 2:"B", 3:"C"};
2value = 2;
3alpha[value]; // instead of using if value==2 or switch value...
We can create a nested object inside an object.
Prevent object mutation,
1let obj = {
2  name:"FreeCodeCamp",
3  review:"Awesome"
4};
5Object.freeze(obj); // obj can't be changed

Destructuring Assignment (ES6)

Extract values from object,
1const user = {name: "Thi", age: 30};
2const {name, age} = user; // name="Thi", age=30
Assign variable from object,
1const {name: uName, age: uAge} = user; // uName="Thi", uAge=30
Assign Variables from Nested Objects,
1const user = {
2  anhThi: {
3    age: 30,
4    email: '[email protected]'
5  }
6};
7const {anhThi: {age, email}} = user;
8const {anhThi: {age: userAge, email: userEmail}} = user;
Assign Variables from Arrays,
1const [a, b] = [1, 2, 3, 4, 5, 6];
2console.log(a, b); // 1, 2
1const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
2console.log(a, b, c); // 1, 2, 5
Assignment with the Rest Parameter to Reassign Array Elements,
1const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
2console.log(a, b); // 1, 2
3console.log(arr); // [3, 4, 5, 7]
Pass an Object as a Function's Parameters,
1const profileUpdate = ({ name, age, nationality, location }) => {
2  // do something with these fields
3}

JSON

JavaScript Object Notation or JSON is a related data interchange format used to store data,
1var ourMusic = [
2  {
3    "artist": "Daft Punk",
4    "title": "Homework",
5    "release_year": 1997,
6    "formats": [
7      "CD",
8      "Cassette",
9      "LP"
10    ],
11    "gold": true
12  }, // first artist
13  {
14  ...
15  } // second artist
16];
To access "CD": ourMusic[0].formats[0].

References

Loading comments...