7 JavaScript Tips
-
Khi code javascript hay nodejs, một số lưu ý nhỏ bên dưới sẽ giúp các bạn tránh khỏi một số lỗi cơ bản rất dễ gặp phải.
Bạn nào có những lưu ý gì hay gặp trong quá trình làm việc có thể share với anh em luôn nha1 Don’t forget var keyword when assigning a variable’s value for the first time
2 In compare clause, use === instead of ==[10] === 10 // is false [10] == 10 // is true '10' == 10 // is true '10' === 10 // is false [] == 0 // is true [] === 0 // is false '' == false // is true but true == "a" is false '' === false // is false
- Copy object not reference
-
Instead of…:
var obj = {a: 25, b: 50,
75};
var A = obj;
var B = obj;
A.a = 30;
B.a = 40;alert(obj.a + ” ” + A.a + ” ” + B.a); // 40 40 40
-
Use:
var obj = {a: 25, b: 50,
75};
var A = Object.create(obj);
var B = Object.create(obj);
A.a = 30;
B.a = 40;alert(obj.a + ” ” + A.a + ” ” + B.a); // 25 30 40
-
Get the max or the min in an array of numbers
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers); -
Don’t use delete to remove an item from array
-
Instead of…
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
delete items[3]; // return true
items.length; // return 11
/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */ -
Use…
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
items.splice(3,1) ;
items.length; // return 10
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
-
Truncate an array using length
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124]. -
Floating point problems
-
Instead of…
0.1 + 0.2 === 0.3 // is true/false ? why?
-
Use …
Math.round((0.1+0.2)*100)/100 === 0.3
-
JavaScript compare: call apply and bind
var obj = { num: 2 };
var functionName = function(arg1, arg2, arg3){}
functionName.call(obj, (arg1, arg2, arg3);
functionName.apply(obj, [arg1, arg2, arg3]);
var bound = functionName.bind(obj);
bound(arg1, arg2, arg3);
-
Hi bạn nên cho vào code block và nếu được thì vết bằng tiếng việt. Nếu bạn share resources vui lòng copyrigh rs ở đâu nhé.
Cheer ! -
Cũng muốn đưa vào code block mà tìm trên trình soạn thảo ko có, bạn có thể giúp mình chổ này?
-
Ở đây hỗ trợ Markdown nhé, bạn có thể search, code thì bỏ vào
```
( 3 dấu huyền ) -
@CodeConCat Thanks
-
Cảm ơn bạn đã chia sẻ.