神刀安全网

10 Useful Beginners JavaScript / jQuery tips and tricks

10 Useful Beginners JavaScript / jQuery tips and tricks 10 Useful Beginners JavaScript / jQuery tips and tricks 10 Useful Beginners JavaScript / jQuery tips and tricks 10 Useful Beginners JavaScript / jQuery tips and tricks 10 Useful Beginners JavaScript / jQuery tips and tricks 10 Useful Beginners JavaScript / jQuery tips and tricks

I consider myself as a advanced when it comes to coding in JavaScript or jQuery however recently I played a bit more with this language and stumbled upon a number of random things i assumed were worth sharing. As you know, JavaScript is the best programming language in the world, the language of the web, of mobile hybrid apps (like PhoneGap or Appcelerator ), of the server side (like NodeJS or Wakanda ) and has several other implementations. So, if you are new to JavaScript or simply don’t understand it as well as you’d like, I hope you find this article helpful.

10 Useful Beginners JavaScript / jQuery tips and tricks

1. 0 == “0”, because 0 means false and “0” is value

At first sight, this is very odd, but once you browse more regarding the comparison operators this make sense. To avoid misunderstandings like this one, be sure to always use the strictly equal operator (===) to try and do this type of comparison.

console.log(0 == "0"); // true console.log(0 === "0"); // false 

2. Use === instead of ==

The == (or != ) operator performs an automatic type conversion if needed. The === (or !== ) operator will not perform any conversion. It compares the value and the type, which could be considered faster than == .

[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 

3. 1+2+”3” != “1”+”2”+3

JavaScript is quite tolerant when it’s about strings and numbers, just think about the “+” operator, which both adds and concatenates. Unlike other programming languages that would shout at you when encountering the line above, JavaScript actually tries to solve this by assuming, at a time, that numbers are strings too.

1+2+"3" != "1"+"2"+3;  // 3+"3" != "12"+3 // 33 !=123

4. JavaScript hoists variable and function declarations

The following code piece will run simply because the JavaScript permits you to use the function before the purpose at which it was declared.

sayHello(); //Call the function before its declaration function sayHello() {     console.log("Hello!"); }

However, watch out for functions expressions and variable declarations! Although their declarations are hoisted also, the function’s definition and respectively the variable’s initialization are not. If you want to scan more, Jeffrey Way and James Allardice wrote some nice articles on variable and function hoisting in JavaScript.

5. Don’t forget var keyword when assigning a variable’s value for the first time

Assignment to an undeclared variable automatically results in a global variable being created. Avoid global variables. The “var” keyword means a variable and optionally initializing it to a value. But, when you omit it, the code still works and the JavaScript interpreter displays no error. That happens because the respective variable will be created in the global scope and not in the local scope youdefined it in. This kind of behavior is commonly described as a JavaScript pitfall and it’s extremely recommended to avoid it as it can create unexpected results.

var myFunction = function() {       var foo = 'Hello'; // Declares and initialize foo, scoped to myFunction     bar = 'World!';     // This works too, but the scope is global };

6. Use Semicolons for line termination only

The use of semi-colons for line termination is a good practice. You won’t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser. You can go crazy and write JavaScript statements without caring about adding semicolons at the end. But there’s a catch. Even though JavaScript automatically inserts semicolons at the end of each line, in some cases, especially if you’re an Allman style indentation fan, problems may appear.

// OK return {   'ok': false };  // not OK return {   'ok': false };

Douglas Crockford gave the best example on this matter, and why should always use semicolons in the JavaScript code. At first sight, the above code pieces look like they do the same: return an object. In reality, the second one will fail because the returned value is undefined , due the automatic semicolon injection.

return; // returns undefined  // code block that does nothing {    'ok': false }

Also, if you didn’t already, you should try to adopt Douglas Crockford’s JavaScript code convention .

7. Don’t use delete to remove an item from array

Use splice instead of using delete to delete an item from an array. Using delete replaces the item with undefined instead of the removing it from the 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]   */

The delete method should be used to delete an object property.

8. The console is your friend

You already know the “Google is your friend” phrase, with that in mind I’d say “The console is your friend” applies best in this case. The console object has some interesting methods you can use to debug your JavaScript code, the log() being by far the most known.

I think the console.log() doesn’t need any introduction anymore, its non-blocking behavior and nice formatting was a big plus comparing with alert() . The issue here is that, even though the console.log was implemented in IE8 and IE9, the console object somehow is not created until you toggle the Developer Tools .

So, found out on my own skin that if you let any console.log calls in your code, it will break your code on browsers likeIE8 and IE9. After browsing for a solution, I found the following as a good and simple solution. Basically, if the window object does not have access to browser’s debugging console, just override the console.log with a dummy function that does nothing at all.

if (!window.console) {    console.log = function(){}; }

Colorful log messages

But if logging methods like log , info , error & warn are not enough to to distinguish your messages, you can try adding your own styling to the log messages.

var consoleStyling = 'background: #0f0; color: #fff; font-weight: bold;'; console.log('%c A colorful message', consoleStyling);

Debugging with console.table()

Again, if using console.log() feels too mainstream, you could try some advanced JavaScript debugging with console.table() . A very nice feature of console.table() is that it also works with objects.

var browsers = {     chrome: { name: "Chrome", engine: "WebKit" },     firefox: { name: "Firefox", engine: "Gecko" } };  console.table(browsers);

9. Use logical AND/ OR for conditions

var foo = 10;   foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();  foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();

The logical OR could also be used to set a default value for function argument.

function doSomething(arg1){      arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set }

10. Don’t forget to use a code beautifier when coding. Use JSLint and minification ( JSMin ) before going live.

Conclusion

When reading more about how JavaScript actually works, the following question will inevitably pop up in your head: Why does JavaScript have so many different ways to do the same thing? Maybe the answer is so we can choose our own way, with the best practices in mind.

I know that there are many other tips, tricks and best practices, so if you have any ones to add or if you have any feedback or corrections to the ones that I have shared, please add a comment.

References

In this article I have used my own code snippets. Some of the snippets are inspired from other articles and forums.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » 10 Useful Beginners JavaScript / jQuery tips and tricks

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址