Kush's Blog

Kush's Blog

Useful Javascript Tricks and Tips

Useful Javascript Tricks and Tips

JavaScript is an object-oriented programming language can used on server as well on host computer, to make the web pages provided from server side to be interactively displayed on host computer browser by using animations, clickable buttons.

JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set of language elements such as operators, control structures, and statements

Javascript has a distinct comparison over a class based languages. In a class-based programming language usually designed for fast execution and type safety, like Java, in which all objects are divided into classes and instances, subdivided into the class hierarchy, and cannot have properties or methods added dynamically, means it cannot be changed during the code execution. Such tightly coupled object hierarchies make Java programming more complex.

On the other hand JavaScript is a bit slow, a scripting language which follows most of the Java expressions syntax, naming conventions and basic control-flows and in addition it offers simple programming tool to through its easier syntax, specialized built-in functionality, and minimal requirements for object creation, but with some limitations such as it cannot easily access database on hard disk directly, does a task through file operations.

Some Tricks

Multiple conditions

We can store multiple values in the array and we can use the array includes method.

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}

Generate an array of numbers with numbers from 0 to max

var numbersArray = [] , max = 100;

for( var i=1; numbersArray.push(i++) < max;);  // numbers = [1,2,3 ... 100]

Sum all the values from an array

var numbers = [2, 12, 22, 34];
var sum = numbers.reduce((x, y) => x + y);
console.log(sum); // returns 70

Swap values with array destructuring

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

let a = 10, b = 5
[a, b] = [b, a]
console.log(a) // -> 5
console.log(b) // -> 10

An HTML escaper function

function escapeHTML(text) {  
    var replacements= {"<": "&lt;", ">": "&gt;","&": "&amp;", """: "&quot;"};                      
    return text.replace(/[<>&"]/g, function(character) {  
        return replacements[character];  
    }); 
}

Check the properties of an object when using a for-in loop

for (var name in object) {  
    if (object.hasOwnProperty(name)) { 
        // do something with name                    
    }  
}

Empty an array

var myArray = [221, 222, 223, 224, 225, 226   ];  
myArray.length = 0;      // myArray will be equal to [].

Transform the arguments object into an array

var argArray = Array.prototype.slice.call(arguments);

Null, Undefined, Empty Checks

// long format
if (first !== null || first !== undefined || first !== '') {
    let second = first;
}
// instead use this
let second = first|| '';

Create an object constructor

function Person(firstName, lastName){
    this.firstName =  firstName;
    this.lastName = lastName;        
}  

var Elon = new Person("Elon", "Musk");

Use logical AND/ OR for conditions

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

Avoid using for-in loop for arrays

//Instead of using…
var sum = 0;  
for (var i in arrayNumbers) {  
    sum += arrayNumbers[i];  
}
//use this
var sum = 0;  
for (var i = 0, len = arrayNumbers.length; i < len; i++) {  
    sum += arrayNumbers[i];  
}

Rounding number to N decimal place

var num = 6.243242342;
num = num.toFixed(4);  // num will be equal to 6.2432

Verify that a given argument is a number

function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}

Get a random number in a specific range

var x = Math.floor(Math.random() * (max - min + 1)) + min;

Interested in reading more such articles from Kushagra Sharma?

Support the author by donating an amount of your choice.