Muchang Bahng

JavaScript


Contents
  1. Basic Topics
  2. Intermediate Topics
JavaScript is a dynamically-typed, object-oriented language that is run on your browser through the V8 Engine, developed by the Chromium project for Google Chrome and Chromium web browsers. We can think of V8 as a compiler built within the browser. JavaScript was meant to be compiled and run within a browser, but with the help of Node.js, we can run it within a local environment. It's official name is ECMAScript, with versions being abbreviated to ES1, ES2, ..., ES6. Since 2016, new versions are named by year: ES2016, 2017, 2018.

Basic Topics

[Hide]

With Node.js, we can actually run JavaScript in the command line by typing node.
Declaring Variables, Basic Types
There are three ways to declare variables:
  • The var keyword is used to declare a global variable, which you can mutate.
        var myThing = "Hello World" 
        
  • The const keyword is used to declare a variable that is immutable.
  • The let keyword is used to declare a local variable that is limited to the scope of a block statement (e.g. within functions, loop statements, etc.).
We can also instantiate a variable but not assign a value to it.
var myThing;      // Variable instantiated, but not assigned to any value 
// ... 
// Lines of code 
// ... 
myThing = 4.5     // Assign value 
The equivalent of a print statement is console.log().
> console.log("Hello World")
Hello World
Now we list some data types:
  1. Strings are pretty self-explanatory. Some basic methods. We can use the backslash \ to write multiple-line strings.
        > var str1 = "Hello "
        > var str2 = "World"
        > var combined = str1 + str2              // String concatenation
        > console.log(combined)
        Hello World
        > combined.length                         // String length
        11
        > combined.substring(3, 7)                // Substring
        'lo W'
        > combined.charAt(combined.length-1)      // Character
        'd'
        > combined.indexOf("W")                   // Find index of first "W"
        6
        > const multLineText = "Here is, \ 
        a multiple line \ 
        string. "
        
  2. The Number type is in a 64-bit binary format and does not partition into int and float values. You can use the constants Number.MAX_VALUE and Number.MIN_VALUE for the largest and smallest available values. Furthermore, the number type has three symbolic values: +Infinity, -Infinity, and NaN (Not-A-Number).
        > num1 = 3
        3
        > num2 = 4.56
        4.56
        > num3 = 452e2
        45200
        > Number.MAX_VALUE
        1.7976931348623157e+308
        > Number.MIN_VALUE
        5e-324
        > num4 = Infinity
        Infinity
        > num5 = -Infinity
        -Infinity
        > 0 * num4
        NaN
        
    JavaScript can store numbers with limited accuracy (16 digits?). The BigInt type can be used to represent integers with arbitrary precision. You can safely store and operate on large integers even beyond the safe integer limit. It is created by appending n to the end of an integer literal.
        > const myBigInt = 9769812589124905871239n;
        > const myBigInt2 = BigInt(9320487589023467589023); 
        
  3. Booleans are pretty self explanatory. The following values are considered false when converted into a Boolean: 0, -0, null, false, NaN, undefined, empty string "".
  4. Arrays can be declared simply with square brackets, with the new Array keyword, or by initializing an empty array and assigning values.
        > const cars = ["Saab", "Volvo", "BMW"]; 
        > const Tech = new Array("AAPL", "MSFT", "META");
        > const pens = [];
        undefined
        > pens[0] = "Lamy";
        'Lamy'
        > pens[1] = "Twisbi";
        'Twisbi'
        > pens[2] = "Mont Blanc";
        'Mont Blanc'
        > pens
        [ 'Lamy', 'Twisbi', 'Mont Blanc' ]
        
    However, there is no array type; arrays are of type object.
        > typeof(pens)
        'object'
        
  5. null is not a type; it is a value that represents the intentional absense of any object value. The undefined type is used when a variable has been called but not assigned to a value. A function returns undefined in a value was not returned. The difference between these two is that a null variable is explicitly declared as empty but undefined has just not been assigned a value an is implicitly empty.
        > nVal = null
        null
        > typeof(nVal)
        'object'
        > var idk
        undefined
        > typeof(idk)
        'undefined'
        > idk = 4.5
        4.5
        > typeof(idk)
        'number'
        
  6. An object type is basically a type that can hold a lot of values (of possibly different types). We can think of it as an object in Python, with its own attributes and methods. They are declared using curly braces (conventionally with const), which hold name-value (aka key-value) pairs that can be accessed using the dot or square bracket syntax.
        > const person = {firstName: "Muchang", lastName: "Bahng", age: 20, eyeColor: "Brown"};
        > person.firstName
        'Muchang'
        > person["lastName"]
        'Bahng'
        
    This is similar to a dictionary in Python. We can also store functions as the values, allowing the object to have methods. The this keyword refers to the object, similar to the self keyword in Python.
        > const myself = {
          ... fullName: "Muchang Bahng",
          ... age: 20,
          ... grow: function() {
          ..... this.age = this.age + 1;
          ..... return this.age;
          ..... }
          ... };
          undefined
          > myself.age
          20
          > myself.grow()
          21
          > myself.age
          21
        
Conditionals, Loops, Switch, Break
The if, else if, and else statements are used with the curly-braces syntax.
var hour = 12; 
var greeting; 

if (hour < 10) {
  greeting = "Good morning"; 
} else if (hour < 20) {
  greeting = "Good day"; 
} else {
  greeting = "Good evening"; 
}
Ternary operators are conditionary operators that take three operands: a condition followed by a question mark ?, then an expression to execute if the condition is truthy, followed by a colon :, and finally the expression to execute if the condition is falsy. It is a more compact alternative to an if else statement. The syntax is:
condition ? exprIfTrue : exprIfFalse
A simple example:
var age = 26; 
var beverage = (age >=21) ? "Beer" : "Juice"; 
cosole.log(beverage);         // Beer 
Javascript has slightly different variations of loops.
  1. A for loop has the following syntax:
        for (statement 1; statement 2; statement 3) {
          // code block to be executed
        }
        
    Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed.
        const pens = ["Lamy Safari", "Lamy 2000", "Platinum Century 3776"]; 
        for (let i = 0; i < pens.length; i++) {
          console.log("I have a " + pens[i]);
        }
        
    Note that it is conventional to set the index i of the loop using let since the scope of this variable is usually only relevant to the loop block. It will not affect global variables of the same name.
        var i = 5; 
    
        for (let i = 0; i < 10; i++) {
          console.log(i);
        }
    
        console.log(i)    // 5
        
    In JS, we have the flexibility to store i as a global variable.
        var i = 5; 
    
        for (var i = 0; i < 10; i++) {
          console.log(i);
        }
    
        console.log(i)    // 10
        
  2. The for-in statement loops through all the keys (not values) of a JavaScript Object (including arrays). This is in contrast to the for-of statement, which loops through all values (similar to a Python for-in loop). It has syntax:
        for (key in object) {
          // stuff
        }
        
    We show two examples, with an object and array.
        const person = {fname: "Muchang", lname: "Bahng", age: 20}; 
    
        for (let x in person) {   // x represents the properties
          console.log(person[x]); 
        }
    
        // Muchang 
        // Bahng 
        // 20 
    
        const numbers = [1, 2, 3, 4, 5];  
    
        for (let x in numbers) {  // x represents indices 0~4
          console.log(numbers[x])
        }
    
        
    Do not use a for-in loop for iterating over an array if index order is important. Rather, use a for loop or a for-of loop.
  3. A for-of statement loops through the values (not the keys) of iterable data structures, such as arrays, strings, maps, nodelists, etc. It has syntax:
        for (let x of iterable) {
          // stuff
        }
        
    The x can also be declared with const or var. Here are some examples over an array and a string.
        const pens = ["Lamy Safari", "Lamy 2000", "Platinum Century 3776"]; 
    
        for (let x of pens) {
          console.log(x); 
        }
    
        const greeting = "Hello World"; 
    
        for (let char of greeting) {
          console.log(char); 
        }
        
  4. The while loop has syntax:
        while (condition) {
          // stuff
        }
        
    Here is an example:
        var i = 4; 
        
        while (i < 10) {
          console.log(i) 
          i++; 
        }
        
  5. The do-while loop executes the block of code once, before checking if the condition is true.
        do { 
          // whatever
        } 
        while (condition); 
        
    Here is an example:
        var i = 4; 
    
        do {
          console.log(i); 
          i++; 
        } 
        while (i < 10); 
        
The break statement jumps out of a loop, and the continue statement jumps over one iteration in the loop.
JS Math, Date Objects
We can access datetime data with the JavaScript Date Object. Calling new Date() just creates a new date object with the current date and time. Date objects are static, meaning that they are just snapshots and do not change.
> const d = new Date();
> console.log(d)
2022-06-20T03:19:07.509Z
> typeof(d)
'object'
We can instantiate a date object at a certain datetime with the following constructors. Note that JS counts months from 0 (January) to 11 (December).
new Date(Y, M, D, H, M, S, MS) 
new Date(Y, M, D, H, M, S)
new Date(Y, M, D, H, M)
new Date(Y, M, D, H)
new Date(Y, M, D) 
new Date(Y, M) 
new Date(MS)
If the parameters go beyond the max value (i.e. 42nd day), then they will overflow into the next biggest unit, e.g. the 14th month of 1992 is interpreted as the 2nd month of 1993.
Functions: Named, Anonymous, Arrow
Functions are created with the following syntax. We can set default parameter values, but we cannot set the type for function parameters. Its syntax is
function funcName() {       // without arguments 
  // Function body
  return value; 
}

function funcName(param1, param2, param3 = 2) {
  // Function body
  return value; 
}
The syntax for anonymous functions is quite similar to that of regular ones. Its syntax is
function() {              // without arguments
  // Function body
}

function(args) {
  // Function body
}
As an example, we store it in a variable:
var greet = function() {
  console.log("Hello World");
}; 

greet();        // Hello World 
This is useful when passing anonymous functions as arguments to other functions.
function Evaluate(func, param) {
  return func(param); 
}; 

const square = function(x) {
  return x * x; 
};

Evaluate(square, 5);    // 25 
A shorter way of declaring anonymous functions are Arrow Functions, which has syntax:
// One-line Anonymous Function 
var greet_person = (name) => console.log("Hello, " + name);

// Multiple-line Anonymous Function
var greet = () => {
  console.log("Hello World");
  return "Done Greeting";
}
Classes and Objects
The ES6 version (2015) introduced JavaScript classes, which act as templates for JavaScript Objects. We simply use the class keyword to create a class, with a constructor method that gets called upon object instantiation followed by any number of methods. Objects are created with the new keyword.
class Car {
  constructor(name, year) {
    this.name = name;         // attribute 1
    this.year = year;         // attribute 2
  }

  age() {     // Get age of car
    let date = new Date()     // Get current datetime 
    return date.getFullYear() - this.year; 
  }

  method2() { ... }

  method3() { ... }
}

let myCar1 = new Car("Ford", 2014); 
let myCar2 = new Car("Audi", 2019); 
Modules: Import and Export

Intermediate Topics

[Hide]