Advanced JavaScript

Junghoo Cho

cho@cs.ucla.edu

Variable Scope (Global vs Local)

Scope Example

let a = "a"; // global vs local?
b = "b"; // global vs local?

function f()
{
    c = "c"; // global vs local?
    let d = "d"; // global vs local?
}

let vs var

var Example

var a = 10;  // global vs local?
function f() {
    b = 10;  // global vs local?
    console.log(b);
    var b;   
}
f();
console.log(b);

Function Object

Function Object Example

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

function myfunc(x, func) {
    return func(x);
}

myfunc(10, square); 
myfunc(10, function (x) { return x * 2; }); // anonymous function

myfunc.a = 20;

Nested Function

Variable Scope in Nested Function

Nested Function and Closure (1)

Nested Function and Closure (2)

Nested Function and Closure (3)

Nested Function and Closure (4)

Arrow Function (1)

Arrow Function (2)

Object-Oriented Programming (OOP)

Class in ECMAScript 2015

Class Inheritance

class Rectangle extends Shape {
    constructor(color, x, y) {
        super(color);  // super refers to the parent class
        this.x = x;
        this.y = y;
    }
    info() {
        return `${super.info()}, x: ${this.x}, y: ${this.y}`;
    }
};
let r = new Rectangle("red", 2, 3);
r.whoami();

Optional Chaining (ECMAScript 2020)

Keyword this

this in Event Handling Call

this in Other Places

Arrow Function and this Binding

Tricky Example of this

x = 10;

function_printx = function() { console.log(this.x); };
arrow_printx = () => { console.log(this.x); };

o = { x: 20 };
o.printx_f = function_printx;
o.printx_a = arrow_printx;

// What will be printed?
console.log(this.x); 
function_printx();   
arrow_printx();      
o.printx_f();        
o.printx_a();        

Notes on this

Array Manipulation

Array Manipulation Example (1)

let a = [1, 2, 3, 4];
let b = a;
console.log(b);
a[1] = 5;
console.log(b);
a = [1, 2, 3];
console.log(b);

Array Manipulation Example (2)

let a = [1, 2, 3];
let b = a.reverse();       // reverse is a mutator
console.log(b);
a[1] = 6;
console.log(b);

a = [1, 2, 3];
b = a.concat([4, 5]);  // concat is an accessor
console.log(b);
a[1] = 6;
console.log(b);

Destructuring Assignment

let o = { userid: 10, password: "secret" };
const { userid, password, email = "default_email" } = o;
// userid = 10, password = "secret", email = "default_email"

let a = [1, 2, 3, 4];
let [a1, a2, ...rest] = a;
// a1 = 1, a2 = 2, rest = [3, 4]

ES Module

(Multiple) Named Export

//------ lib.js ------
export function square(x) {
    return x * x;
}
export function dist(x, y) {
    return Math.sqrt(square(x) + square(y));
}

//------ main.js ------
import { square } from './lib.js';
square(11);  

//----- main2.js ------
import * as mylib from './lib.js';
mylib.dist(4, 3); 

(Single) Default Export

//------ lib.js ------
export default function () { ... }

//------ main1.js ------
import myFunc from './lib.js';
myFunc();

References