MyPage is a personalized page based on your interests.The page is customized to help you to find content that matters you the most.


I'm not curious

Programmer tips: 10 tips on JavaScript you may not know

Published on 14 May 15
3
3
Programmer tips: 10 tips on JavaScript you may not know - Image 1
Calling all JavaScript programmers, you can now apply this important yet simple to use JavaScript tips that would be most beneficial for your web purposes.
1) First thing first, use === instead of ==
JavaScript utilizes two different kinds of equality operators: === ( or !==) and == ( or !=). Our tip is that you should use the former set of codes. To elaborate, if the 2 operands are of the same type and value, the === code produces true results while the !== code produces false results. If you apply the == ( or !=) code, you will run into issues when working with different operand types whereby the == ( or !=) will try a futile attempt to force the values when it executes an automatic type conversion.
On the other hand, the === (or !==) operator will not convert but instead balance the value and the type of operands which would be way faster than == ( or !=).
[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
2) Use strict!
With regards to web browser support, applying the 'Use strict' command is under ECMAScript 5 and is supported by Safari 5.1+, Chrome 13+ and IE10. By entering 'Use strict', the browser is able to remove an error when you make mistakes in your coding such as: making a global variable or accessing arguments.callee or arguments.caller. This would allow programmers to easily monitor bugs and glitches if the application encounters a malfunction. 'Use Strict' can be applied to the scope of a function or an entire file.
For example:
1. (function(){
2. x = 1;
3. console.log(a);
4. })();
5.
6. (function(){
7. "use strict";
8.
9. y = 2;
10. })();
You will then achieve this.
1. > 1
2. > ReferenceError: b is not defined
3) Quick method in building a String
Instead of using the "for" statement when you need to loop through an array or object, you may try this series of codes for a quicker job.

"Using native methods (like join()), regardless of what's going on behind the abstraction layer, is usually much faster than any non-native alternative."
- James Padolsey, james.padolsey.com
1 var arr = ['item a', 'item b', 'item c', ...];
2 var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';
4) Prevent yourself from using try-catch-finally inside a loop
Reason is that the try-catch-finally command produces a new variable in that particular scope whenever the catch clause is applied. This will cause the caught exception object to be assigned to a variable.
Instead of using this:
var object = ['foo', 'bar'], i;
for (k = 0, len = object.length; k <len; k++) {
try {
// do something that throws an exception
}
catch (e) {
// handle exception
}
}

You can try this out:
var object = ['foo', 'bar'], i;
try {
for (p = 0, len = object.length; p <len; p++) {
// do something that throws an exception
}
}
catch (e) {
// handle exception
}
The very essential Immediately Invoked Function Expressions (IIFE)
IIFE works by having a pair of parenthesis to encapsulate the anonymous function which forms a function expression or a variable expression. You will then possess an unnamed function expression that will provide you with beneficial uses.
5) Use of IIFE to prevent your Global Scope from being contaminated
With this technique you can definitely avoid stating variables in the global scope. Such a technique is commonly used among JavaScript libraries, JavaScript professionals and jQuery developers. It is also recommended to use IIFE in top-level applications such as main.js as well.
How to apply it? By using IFFE in the global scope, it keep all variables local to the anonymous function, the variables outside of the global scope will be able to block other defined variables with the exact name.
// All the code is wrapped in the IIFE

(function () {
var firstName = "James";

function init () {
doStuff (firstName);
// code to start the application

}

function doStuff () {

// Do stuff here

}

function doMoreStuff () {

// Do more stuff here

}

// Start the application

init ();
}) ();
You can also pass jQuery or any other object or variable via the parameter (the last 2 parentheses)
6) Use of IIFE to execute complex logic
A rather powerful too as you can execute complex logic without having a setup and call a named function. Do pay special attention to the 2 anonymous functions in the conditional statement
r unnamedDocs = [], namedDocs = ["one_republic", "counting_stars"];

function createDoc(documentTitle) {

var docName = documentTitle

?

(function (theName) {
var newDocName = theName.toLocaleLowerCase().replace(" ", "_");
namedDocs.push(newDocName);

return newDocName;
})(documentTitle)


:


(function () {
var newUnnamedDoc = "untitled_" + Number(namedDocs.length + 1);
unnamedDocs.push(newUnnamedDoc);
return newUnnamedDoc;
})();


return docName;
}
createDoc("MyTechLogy_is_great"); // over_the rainbow

createDoc(); // untitled_4

7) Use of IIFE to avoid any fold over.
By using IIFE, you can stop the common bugs which will prevent close over in for loops. The bug side effects can be eradicated by:
function actorIDCreator (theActor) {
var i;
var uniqueID = 100;
for (i = 0; i < theActor.length; i++) {
theActor[i]["id"] = function (j) { // the j parametric variable is the i passed in on invocation of this IIFE

return function () {
return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array

}
} (i); // immediately invoke the function passing the i variable as a parameter

}

return theActor;
}

var actionActor = [{name:"Statham", id:0}, {name:"Berry", id:0}, {name:"Fox", id:0}];

var createIdForActionActor = actorIDCreator (actionActor);

var stathamID = createIdForActionActor [0];

console.log(stathamID.id()); // 100


var flightID = createIdForActionActor [1];console.log(flightID.id()); // 101
8) Be wary when using typeof, instanceof and constructor
typeof : a JavaScript unary operator is made to recur a string that constitutes an old type of variable. Be reminded that typeof null will return object, and like most object types (such as Array), it will return object.
var arr = ["x", "y", "z"];
typeof arr; // return "object"
constructor: Part of the internal prototype property, it can be quashed by code.
arr.constructor(); //[]
instanceof: A JavaScript operator that scrutinizes all the prototypes chain. The constructor it returns is true if its found and false if not.
arr instanceof Array // true
9) A good habit to comment on your code
It may be an inconvenience to some, but it is a very good practice to comment on your code as much as possible. For instance, while returning back to your coding developments after a prolonged period, and to your horror, you'll find out that you can't easily remember what your coding was about! . Hence, it is a fundamental habit to comment on your code.
1)// Cycle through array and echo out each name.
2)for(var p = 0, len = array.length; p < len; p++) {
3)console.log(array[p]);
4)}
10) Lastly, don't use the 'with' statement
It may seem that "With" statements could probably be a good idea. The idea is that they coders will be able to use a shortcut for accessing intricate objects. For example
1) With (being.vehicle.car.bodyparts) {
2) doors = true;
3) tyres = true;
4) }
instead of
1)being.vehicle.car.bodyparts.doors = true;
2)being.vehicle.car.bodyparts.tyres = true;
However, what will happen is that the codes will be very messy when setting new members. My advice would be to use var instead.
var i = being.vehicle.car.bodyparts;
i.doors = true;
i.tyres = true;
Well that's that! These are the top 10 tips you should adopt when using JavaScript. If you like to challenge the recommendations given or share your own piece of advice, do leave a comment below!
Programmer tips: 10 tips on JavaScript you may not know - Image 2
This blog is listed under Development & Implementations Community

Related Posts:
View Comments (3)
Post a Comment

Please notify me the replies via email.

Important:
  • We hope the conversations that take place on MyTechLogy.com will be constructive and thought-provoking.
  • To ensure the quality of the discussion, our moderators may review/edit the comments for clarity and relevance.
  • Comments that are promotional, mean-spirited, or off-topic may be deleted per the moderators' judgment.
  1. 08 February 18
    0

    Nice article about Javascript

  2. 18 July 16
    0

    very good article thanks

  3. 16 October 15
    0

    Useful information, Thank you so much

You may also be interested in
 
Awards & Accolades for MyTechLogy
Winner of
REDHERRING
Top 100 Asia
Finalist at SiTF Awards 2014 under the category Best Social & Community Product
Finalist at HR Vendor of the Year 2015 Awards under the category Best Learning Management System
Finalist at HR Vendor of the Year 2015 Awards under the category Best Talent Management Software
Hidden Image Url

Back to Top