What’s the difference between hasOwnProperty method and “in” operator

Key point

For inherited properties, in will return true and hasOwnProperty will return false.

Example

const obj = {};
console.log('constructor' in obj);  // true
console.log(obj.hasOwnProperty('constructor'));  // false

Reference

What’s the difference between Object.assign and just assign

Key Point

For single property, direct assignment is good. For multiple properties, Object.assign is nicer.

Reference

How does the second parameter of parseInt method works

Key point

  • When using parseInt, the second parameter should be explicitly declaring for some reasons
  • parseInt() will use the second parameter as the radix(base) to parse a string to integer
  • The first parameter(default parameter) should be a string, or it will be transformed into a string by toString method
  • The second parameter should be between 2 and 36 as a valid radix, otherwise the method will return NaN if the second parameter is number but out of valid scope([2,36]) or it will be ignored if not a number
  • The method will return NaN if parsing fails

Example

All examples below will get the answer 15.

parseInt("0xF", 16);  // Because the string starts with "0x" and "F" is valid hexadecimal number, so it will be parsed into integer with the radix 16
parseInt("F", 16);  // Because the second parameter is a valid hexadecimal number and the first parameter is a valid hexadecimal string, it works
parseInt("17", 8);  // "17" is parsed into integer with 8 as radix -> 8 + 7 = 15
parseInt(021, 8); // (This maybe confused) Because the first parameter is a number rather than a string, it will be transformed into a string first using toString method. (021).toString() -> 2 * 8 + 1 = 17 => "17", then it is the same to the last example
parseInt("015", 10);  // Because the second parameter is 10, the first character "0" will be ignored
parseInt(15.99, 10);  // 15.99 will be transformed into valid string "15.99", then the parsing process will terminate when meeting the first invalid string, the dicimal point(".")
parseInt("15,123", 10); // The parsing process will terminate when meeting the invalid character, the comma
parseInt("FXX123", 16);  // (This maybe confused) Because the second parameter is a valid radix(16), the parsing process will proceed correctly until meeting the first invalid character("X") then terminate
parseInt("1111", 2);  // 2^3 + 2^2 + 2^1 + 1 => 8 + 4 + 2 + 1 => 15
parseInt("15 * 3", 10);  // "15" is a string that can be parsed into a valid number and the spaces will be ignored during parsing process but terminates when meeting the invalid character "*"
parseInt("15e2", 10);  // The same as the above example except the first invalid character is "e"
parseInt("15px", 10);  // The first invalid character is "p"
parseInt("12", 13);  // 13 * 1 + 12 => 15

Reference