Sign in
Log inSign up

Top 10 Tips to be a Professional JavaScript Developer in 3 Minutes

Jay Chow's photo
Jay Chow
·Jun 7, 2020

We have heard the word "data binding" more often in the programming. The key to "data binding" is to monitor the changes of data, but for such an object: let obj = {value: 1}, how should we know that obj had Changed?

1. defineProperty

ES5 provides the Object.defineProperty method, which can define a new property on an object, or modify an existing property of an object, and return the object.

obj: an object
prop: attributes of the object
descriptor: the description of the permission of the object
let obj = {}
Object.defineProperty(obj, "money", {
    value : 100, // Updated value, the default value is undefine.
    writable : true, // The property can only be changed by the assignment operator if and only if the property's writable is true. The default is false.
    enumerable : true, // This attribute can appear in the enumerated attribute of an object if and only if the enumerable of this attribute is true. The default is false.
    configurable : true // The property descriptor can be changed and deleted if and only if the property's configurable is true. The default is false.
    get: () => value; // Get current value 
    set: (newVal) => newVal; // Set current value
});

2. Prototype Inheritance

The simple way to inherit from the parent class, just define the prototype of child class and create a new constant in order to get the parent's value.

function Car() {
    this.brand = 'bmw';
}

Car.prototype.getBrand = () => console.log(this.brand)

function ElectricCar() {}

ElectricCar.prototype = new Car();

const eleCar = new ElectricCar();

console.log(eleCar.getBrand()); 

// bmw

However, there is also a classical way to maintain the pure inheritance from a parent if you need to reuse the child some other places. See e.g.

function Car() {
    this.brand = ['bmw', 'audi'];
}

function ElectricCar() {
    Car.call(this);
}

const carA = new ElectricCar();

carA.brand.push('toyota');

console.log(carA.brand); // ["bmw","audi","toyota"]

const carB = new ElectricCar();

console.log(carB.brand); // ['bmw', 'audi']

3. Call / Apply

Call method calls a function with a given this value and arguments provided individually. See the example below.


const food = {
    value: 'apple'
}

function fruit() {
     console.log(this.value);
}

fruit.call(food); // apple

The same usage of call, apply can achieve the same result.


Function.prototype.apply = (info, arr) => {
      let info = Object(info) || window; 
      info.fn = this;

      const result;
      if(!arr) { result = info.fn(); }
      else {
        var args = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            args.push('arr[' + i + ']');
        }
        result = eval('info.fn(' + args + ')')
    }

    delete info.fn
    return result;
}

4. Memoize Function

Programs often waste time calling functions that recalculate the same results over and over again. This is particularly true with recursive and mathematical functions. A perfect example of this is the Fibonacci number generator. The Fibonacci sequence is a series of integers, beginning with zero and one, in which each value is the sum of the previous two numbers in the series.

function memorize(func) {
  var memo = {};
  var slice = Array.prototype.slice;

  return function() {
    var args = slice.call(arguments);

    if (args in memo)
      return memo[args];
    else
      return (memo[args] = func.apply(this, args));

  }
}
var count = function(a, b, c) {
  return a + b + c
}

var memoizedCount = memorize(count)

console.time('use memorize function')
for(var i = 0; i < 100000; i++) {
    memoizedCount(1, 2, 3)
}
console.timeEnd('use memorize function')

console.time('without memorize function')
for(var i = 0; i < 100000; i++) {
    count(1, 2, 3)
}
console.timeEnd('without memorize function')

5. Symbol

Symbol value can be used to the label or the attribute name of the object, and it promised the same property name

var mySymbol = Symbol();

// FIRST
var a = {};
a[mySymbol] = 'Hello!';

// SECOND
var a = {
  [mySymbol]: 'Hello!'
};

// THIRD
var a = {};
Object.defineProperty(a, mySymbol, { value: 'Hello!' });

// All of them have the same result but they never equal to each other.
console.log(a[mySymbol]); // "Hello!"
var s1 = Symbol.for("foo");
console.log(Symbol.keyFor(s1)); // "foo"

var s2 = Symbol("foo");
console.log(Symbol.keyFor(s2) ); // undefined

6. Array.from()

From ES6, the [...arguments] has been used rapidly. and how does it come from an array? See. e.g.

function mul(a, b) {
    let args = Array.from(arguments); // [4, 5]
    console.log(args.reduce((sum, cur) => sum * cur));
}
mul(4,5); //9

7. Array.prototype.slice.call()

Arguments cannot call array methods by themselves, it is another type of object, but the attributes are ranked from 0, 0, 1, 2 ... and finally the callee and length attributes. We also refer to such objects as array-like.

function mul(a, b) {
    let args = Array.prototype.slice.call(arguments); // [4, 5]
    console.log(args.reduce((sum, cur) => sum * cur));
}
mul(4,5); //20

8. Sort

Sort one array item at a time, and construct the final sorted array in this way. Assuming that the first item is already sorted, then it is compared with the second item. Should the second item stay in place or be inserted before the first item? In this way, the first two items are correctly sorted, and then compared with the third item (whether it should be inserted in the first, second, or third position?), And so on.

Array.prototype.insertionSort = function() {
    let j
    let temp
    for (let i = 1; i < this.length; i++) {
        j = i
        temp = this[i]
        while (j > 0 && this[j - 1] > temp) {
            this[j] = this[j - 1]
            j--
        } 
        this[j] = temp
        console.log(this.join(', '))
    }
    return this
}

9. Async/Await

ES2018 introduces asynchronous iterators, which are like regular iterators, except that the next () method returns a Promise. Therefore, await can be used with for ... of the loop to run asynchronous operations in a serial manner.

async function increase(array) {
    for await (let i of array) {
         // request to api
    }
}

10. Javascript Key Code

Knowing most of the key code in JavaScript may help you improve the user experience of your web application.

let keyCodeMap = {
    8: 'Backspace',
    9: 'Tab',
    13: 'Enter',
    16: 'Shift',
    17: 'Ctrl',
    18: 'Alt',
    19: 'Pause',
    20: 'Caps Lock',
    27: 'Escape',
    32: 'Space',
    33: 'Page Up',
    34: 'Page Down',
    35: 'End',
    36: 'Home',
    37: 'Left',
    38: 'Up',
    39: 'Right',
    40: 'Down',
    42: 'Print Screen',
    45: 'Insert',
    46: 'Delete',

    48: '0',
    49: '1',
    50: '2',
    51: '3',
    52: '4',
    53: '5',
    54: '6',
    55: '7',
    56: '8',
    57: '9',

    65: 'A',
    66: 'B',
    67: 'C',
    68: 'D',
    69: 'E',
    70: 'F',
    71: 'G',
    72: 'H',
    73: 'I',
    74: 'J',
    75: 'K',
    76: 'L',
    77: 'M',
    78: 'N',
    79: 'O',
    80: 'P',
    81: 'Q',
    82: 'R',
    83: 'S',
    84: 'T',
    85: 'U',
    86: 'V',
    87: 'W',
    88: 'X',
    89: 'Y',
    90: 'Z',

    91: 'Windows',
    93: 'Right Click',

    96: 'Numpad 0',
    97: 'Numpad 1',
    98: 'Numpad 2',
    99: 'Numpad 3',
    100: 'Numpad 4',
    101: 'Numpad 5',
    102: 'Numpad 6',
    103: 'Numpad 7',
    104: 'Numpad 8',
    105: 'Numpad 9',
    106: 'Numpad *',
    107: 'Numpad +',
    109: 'Numpad -',
    110: 'Numpad .',
    111: 'Numpad /',

    112: 'F1',
    113: 'F2',
    114: 'F3',
    115: 'F4',
    116: 'F5',
    117: 'F6',
    118: 'F7',
    119: 'F8',
    120: 'F9',
    121: 'F10',
    122: 'F11',
    123: 'F12',

    144: 'Num Lock',
    145: 'Scroll Lock',
    182: 'My Computer',
    183: 'My Calculator',
    186: ';',
    187: '=',
    188: ',',
    189: '-',
    190: '.',
    191: '/',
    192: '`',
    219: '[',
    220: '\\',
    221: ']',
    222: '\''
};

function renderKeyName(keycode) {
    if (keyCodeMap[keycode]) {
        return keyCodeMap[keycode];
    } else {
        console.log('Unknow Key(Key Code:' + keycode + ')');
        return '';
    }
};

Reference:

Memoization Function

Array.prototype.slice

Key Code