Here’s a summary of pitfalls that I have met in learning JavaScript.
10. Accessing object’s properties
Assessing object’s properties has two options, dot notation and bracket notation.
However, if the property name is a variable, dot notation method will look at the string value rather than variable value.
For property names like “accept-language”, we also need to use bracket notation, like User[name].
Mind that we can use square brackets in an object literal, when creating an object. That’s called computed properties.
9. Array’s sort() method
arr.sort([compareFunction])
If compareFunction is omitted, the array elements will be converted to strings, then sorted according to each character’s Unicode code point value.
A simple way to compare numbers is
arr.sort(function(a, b) { return a - b; });
8. toLowerCase()
let newArr = arr.map(function(s) { return s.toLowerCase(); });
7. instanceof
6. getOwnPropertyNames VS keys
5. Floating point numbers
4. Type conversion
""
+
1
+
0
""
-
1
+
0
true + false = 1
"4px"- 2 = NaN
- needs to convert "4px" to numbers NaN. Nan - 2 = NaN.
null + 1 = 1
null becomes 0 after the numeric conversion.
undefined + 1 = NaN
undefined becomes NaN after the numeric conversion.
3. Function
If we have such function definition.
let sayHi = function (){ alert("Hello!")};
And we have the following code.
alert (sayHi);
The function code will be showed.
alert (sayHi());
This one will run the function.
A Function Expression is created when the execution reaches it and is usable only from that moment.
A Function Declaration can be called earlier than it is defined.
2. Const
const user ={name : “John”};
user = {name: “Peter”}; Error!
user.name=”Peter”; Correct!
The const
fixes the value of user
, but not its contents.
1. Object.assign()
Object.assign(object1, object2, object3,...)
It will merge object2, object3,… into object1. This means it’s mutable.
However, sometimes, we don’t want to change object1. What should we do?
return Object.assign({},object1, object2,...)