1. Use === Instead of ==
JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing. However, when working with == and !=, you’ll run into issues when
working with different types. In these cases, they’ll try to coerce the values, unsuccessfully.
2. Eval = Evil
For those unfamiliar, the “eval” function gives us access to JavaScript’s compiler. Essentially, we can execute a string’s result by passing it as a parameter of “eval”.
eval("alert('Hi!')");
There are a couple reasons why the eval function should be avoided. First, it is significantly slower than design time code. Second, it is a security risk. When code is acquired and executed at runtime, it opens a potential threat vector for malicious programmers to exploit.
3. Always comment your code.
4. Use Explicit Blocks
Avoid writing statements without curly braces.
Bad example:
1. if(someVariableExists)
2. x = false
Good example:
1. if(someVariableExists) {
2. x = false;
3. }
With braces statements are more readable.
5. Variable naming
When declaring variables or functions always use camelCase
1. var userId;
2. var slidingPanel;
3. var wrappingElement = function ()
{};
When declaring constructors always use Pascal case
1. function Car(make, model, year) {
2. this.make = make;
3. this.model = model;
4. this.year = year;
5. }
6. var myCar = new Car("Eagle", "Talon TSi", 1993);
Use all upper case when you are defining any constant
1. var PAGE_SIZE = 10;
6. Long List of Variables? Omit the “Var” Keyword and Use Commas Instead.
Bad example:
1. var someItem = 'some string';
2. var anotherItem = 'another string';
3. var oneMoreItem = 'one more string';
Good example:
1. var someItem = 'some string',
2. anotherItem = 'another string',
3. oneMoreItem = 'one more string';
7. Do not create any object using new Object or new Array etc. Instead use literal syntax.
1. var obj = {},
2. arr = [],
3. str = "";
8. Always use semicolon.
Technically, Javascript allows us to get away with omitting semi-colons. But this may lead to issues that can be harder to find.
9. Try to have at max one global variable and use it as your namespace. For example:
1. App: {
2. name: "My App",
3. .
4. .
5. .
6. other properties,
7. init: function () {
8. //Initializations
9. },
10. start: function () {
11. //Start App
12. }
13. }
10. Use decimals cautiously
In javascript, 0.1 + 0.2 comes out to be something like 0.30000000000000004. The reason for this is because
JavaScript uses Binary Floating Point numbers. To get around this issue, you can multiply your numbers to remove the decimal portion. For instance, if you were to be adding up the cost of two items, you could multiply each price by 100 and then divide the sum by 100. Here is an example:
1. var hamburger = 8.20;
2. var fries = 2.10;
3. var total = hamburger + fries;
4. console.log(total); //Outputs 10.299999999999999
5. hamburger = hamburger * 100;
6. fries = fries * 100;
7. total = hamburger + fries;
8. total = total / 100;
9. console.log(total); //Outputs 10.3
11. Start Blocks on the Same Line
Most developers that write software in other C-family programming languages use the Allman style of formatting for block quotes.
Bad example:
1. if(myState === 'testing')
2. {
3. console.log('You are in testing');
4. }
5. else
6. {
7. console.log('You are in
production');
8. }
This will work most of the time. However, JavaScript is designed in such a way that following the K&R style of formatting for blocks is a better idea. This format starts the opening curly brace on the same line as the preceding line of code. It looks like this:
Good example:
1. if(myState === 'testing') {
2. console.log('You are in testing');
3. } else {
4. console.log('You are in
production');
5. }
While this may only seem like a stylistic difference, there can be times when there is a impact on your code if you use the Allman style. One fairly serious issue with this is on return statements. Let’s look at an example:
Bad example:
1. return
2. {
3. age: 15,
4. name:Jon
5. }
We would assume that the object would be returned but instead the return value will be undefined. The reason for this is because the browser has inserted a semicolon after the word return, assuming that one is missing.
Good example:
1. return {
2. age: 15,
3. name:Jon
4. }
12. Be Careful Using typeof
Normally, typeof returns the string representation of the value type (‘number’, ‘string’, etc.) The problem comes in when evaluating NaN (‘number’), null (‘object’), and other odd cases. For example, here are a couple of comparisons that might be unexpected:
1. var i = 10;
2. i = i - 'taxi'; //Here i becomes NaN
3. if (typeof(i) === 'number') {
4. console.log('i is a number');
5. } else {
6. console.log('You subtracted a bad value from
i');
7. }
The resulting alert message would be “i is a number”, even though clearly it is NaN (or “Not a Number”). To avoid this what you can do is check if ‘i’ is valid as shown here:
1. if (i && typeof(i) === 'number') {
2. console.log('i is a number');
3. } else {
4. console.log('You subtracted a bad value from
i');
5. }
13. Always pass radix parameter to parseInt
1. parseInt("56"); //Returns 56
2. parseInt("Joe"); //ReturnsNaN
3. parseInt("Joe56"); //ReturnsNaN
4. parseInt("56Joe"); //Returns 56
5. parseInt("21.95"); //Returns 21
parseInt returns all of the number characters it finds until it hits a non-numeric character.
1. parseInt("08"); //Returns 8 - used to return 0 (base 8)
2. parseInt("0x12"); //Returns 18 - assumes hexadecimal
3. parseInt("12", 16); //Returns 18, since base 16 is specified
The second pitfall is in the interpretation of the number.
a. A string with a leading zero was determined to be a number in octal format. Ecmascript 5 removed this functionality. Now most numbers will default to base 10.
b. The one exception is a string that starts with “0x”. This type of string will be assumed to be a hexadecimal number (base 16).
NOTE: We can also use + operator to parse a string number to a number. Example:
1. +"142" returns 142
2. +"142.854" returns
142.854
14. Avoid Reserved / Special Words
15. Types available in JS
a. Numbers
b. Strings
c. Booleans
d. Functions
e. Objects
f. undefined
16. + Operator
The + operator also does string concatenation:
1. "hello" + " world" returns "hello world"
If you add a string to a number (or other value) everything is converted in to a string first.
1. "3" + 4 + 5 returns"345"
2. 3 + 4 + "5" returns "75"
17. Use JSON
When storing data structures as plain text or sending/retrieving data structures via Ajax, use JSON instead of XMLwhen possible. JSON (JavaScript Object Notation) is a more compact and efficient data format, and is language neutral.
JSON is an intrinsic object that provides functions to convert JavaScript values to and from the JSON
format. The JSON.stringify function serializes a JavaScript value to JSON text. The JSON.parse function deserializes JSON text to produce a JavaScript value.
18. Prefer using Dot Notation
Objects properties in javascript can be accessed primarily in two ways: Dot notation and Square bracket notation.
Dot notation:
1. MyObject.property
Square bracket notation:
1. MyObject["property"]
Using dot notation brings consistency and prevent us from using reserved keywords as our properties. On the other hand, with bracket notation, the property name is a string which is evaluated to resolve the property name. The string can be hard-coded, or a variable, or even a function call which returns a string property name. Square notation should be used only in two cases; first, when we have properties that will be evaluated at runtime, and second when we having any property which is a keyword in Javascript.
NOTE: We should never have any property which is reserved keyword in Javascript.
19. Feature-Detect Rather Than Browser-Detect
Some code is written to detect browser versions and to take different action based on the user agent being used. This, in general, is a very bad practice. Any code which even looks at the global “navigator” object is suspect. The better approach is to use feature detection. That is, before using any advanced feature that an older browser may not support, check to see if the function or property exists first, then use it. e.g:
1. if (document.getElementsByClassName) {
2. var element = document.getElementsByClassName('highlight');
3. } else {
4. alert('Your browser lacks the capabilities required to run this
script!');
5. }
20. Use “strict mode” at the top of your javascript code.
Strict mode is a way to introduce better error-checking into your code. When you use strict mode, you cannot, for example, use implicitly declared variables, or assign a value to a read-only property, or add a property to an object that is not extensible.
21. Assign methods to the prototype instead of overwriting the prototype with a new object.
For example:
Bad example:
1. Jedi.prototype = {
2. fight: function fight() {
3.console.log('fighting');
4. },
5. block: function block() {
6.console.log('blocking');
7. }
8. };
Good example:
1. Jedi.prototype.fight = function fight() {
2. console.log('fighting');
3. };
4. Jedi.prototype.block = function block() {
5. console.log('blocking');
6. };
0 comments:
Post a Comment