Some Useful JavaScript Tips,Tricks and Best Practices
As you know, JavaScript is the top 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 many other implementations. It’s also the starting point for many new developers to the world of programming, as it can be used to display a simple alert in the web browser but also to control a robot (using nodebot, or nodruino). The developers who master JavaScript and write organized and performant code have become the most sought after in the job market.
In this article, I’ll share a set of JavaScript tips, tricks and best practices that should be known by all JavaScript developers regardless of their browser/engine or the SSJS (Server Side JavaScript) interpreter.
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.
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
undefined, null, 0, false, NaN, '' (empty string) are all falsy.
Use Semicolons for line termination
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. For more details about why you should use semi-colons.
Create an object constructor
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
var Khalid = new Person("Khalid", "Ansari");
Be careful when using typeof, instanceof and constructor.
typeof: a JavaScript unary operator used to return a string that represents the primitive type of a variable, don’t forget that typeof null will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”.
constructor: is a property of the internal prototype property, which could be overridden by code.
instanceof: is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it’s found and false if not.
var arr = ["a", "b", "c"];
typeof arr; // return "object"
arr instanceof Array // true
arr.constructor(); //[]
Define a Self-calling Function
This is often called a Self-Invoked Anonymous Function or Immediately Invoked Function Expression (IIFE). It is a function that executes automatically when you create it, If you want to use this function you can write in the following way:
(function(){
// some private code that will be executed automatically
A better option could be to implement a random sort order by code (e.g. : Fisher-Yates shuffle), than using the native sort JavaScript function
A string trim function
The classic trim function of Java, C#, PHP and many other language that remove whitespace from a string doesn’t exist in JavaScript, so we could add it to the String object.
myArray.length = 0; // myArray will be equal to [].
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.
This is an old but effective pattern, which tries to simulate named parameters in JavaScript. The function calling looks fine. On the other hand, the config object handling logic is unnecessarily verbose. With ES2015 object destructuring, you can circumvent this downside:
function doSomething({ foo = 'Hello', bar = 'Toogit!', baz = 13 }) { // ...}
And if you need to make the config object optional, it’s very simple, too:
function doSomething({ foo = 'Hello', bar = 'Toogit!', baz = 13 } = {}) { // ...}
Object destructuring for array items
Assign array items to individual variables with object destructuring:
What is the difference between Java and JavaScript?
These are two different programming languages.
Javascript is a language that has gained tremendous popularity as a language on the web browsers to create dynamic and interactive web pages.
Java is a language that has got a similar popularity when you build a “backend” system, which is a fancy word for “almost anything”.
Despite the common prefix, they are not related; there creators are different and so are their origin stories (as highlighted by other answers).
- JavaScript is a genius marketing scam that polluted the world of browsers exceptionally well. The browser reads JavaScript’s code line by line and executes it.
- Java is a general purpose language that is used almost everywhere, from Android mobile apps and cryptography to OS and cloud computing. Java’s code is stored in bytecoded format and then gets JIT compiled before the actual execution. In other words, it translates the bytecode to machine code.
- Java is class based. JS is prototype based. All objects, like Array or Function inherit from the Object.prototype which remains on top of the chain.
- JavaScript uses dynamic type checking (checks the variables while the code executes), unlike Java’s static checking system (variables are verified at compile time), which is more bug free.
- The word “Script.” It’s a joke, in case you didn’t get it.
Top Recommended Freelancers
More than 1,000,000 freelancers ready to tackle any kind of project
I am a techie at heart and love to explore new technologies. I have helped various companies evaluate their technology stack and help them improve. My responsibilities include "Platform selection and technical design", "Provide options", "Grow technical leader"and "Own the development methodology"
Removing elements from a JavaScript array is a common programming paradigm that developers often run into. As with a lot of things JavaScript, this isn’t as simple as it probably should be. There are actually several ways to remove one or more elements from an...
YouTube is currently world’s most popular video sharing web site. Over 1 billion hours of videos are watched every day and over 300 hours of video content is uploaded every minute. It also provides offline facility in which you can watch video offline once you...