Top 10 Useful JavaScript Tips You Should Know!

Top 10 Useful JavaScript Tips You Should Know!

What 10 Things Should a Serious Javascript Developer Know Right Now? ... Can you contribute productively as a mid-level JavaScript developer .... sense of best practice architecture should be embedded in the code.

1. Converting to Boolean Using the !! Operator

Sometimes, we need to check if a variable exists or if it has a valid value, to consider them as a true value. For this kind of validation, you can use the !! (double-negation operator).

A simple !!variable, which will automatically convert any kind of data to a boolean and this variable will return false only if it has some of these values: 0, null, "", undefined, or NaN, otherwise, it will return true.

To understand it in practice, take a look this simple example:

function Account(cash) {
    this.cash = cash;
    this.hasMoney = !!cash;
}

var account = new Account(100.50);
console.log(account.cash); // 100.50
console.log(account.hasMoney); // true

var emptyAccount = new Account(0);
console.log(emptyAccount.cash); // 0
console.log(emptyAccount.hasMoney); // false

In this case, if an account.cash value is greater than zero, the account.hasMoney will be true.

2. Converting to Number Using the + Operator

This magic is awesome! And it’s very simple to do but it only works with string numbers, otherwise, it will return NaN (Not a Number). Have a look at this example:

function toNumber(strNumber) {
    return +strNumber;
}
console.log(toNumber("1234")); // 1234
console.log(toNumber("ACB")); // NaN
This magic will work with Date too and, in this case, it will return the timestamp number:
console.log(+new Date()) // 1461288164385

3. Short-Circuit Conditionals

If you see a similar code to:

if (connected) {
    login();
}

You can shorten it by using a combination of a variable (which will be verified) and a function using the && (AND operator) between them. For example, the previous code can become smaller in one line:

connected && login();

You can do the same to check if an attribute or function exists in the object. Similar to the below code:

user && user.login();

4. Default Values Using the || Operator

Today, in ES6, there is the default argument feature. To simulate this feature in old browsers, you can use the || (OR operator) by including the default value as a second parameter to be used.

If the first parameter returns false, the second one will be used as a default value. See this example:

function User(name, age) {
    this.name = name || "Oliver Queen";
    this.age = age || 27;
}
var user1 = new User();
console.log(user1.name); // Oliver Queen
console.log(user1.age); // 27
var user2 = new User("Barry Allen", 25);
console.log(user2.name); // Barry Allen
console.log(user2.age); // 25

5 Caching the array.length in the Loop

This tip is very simple and causes a huge impact on performance when processing large arrays during a loop. Basically, almost everybody writes this synchronously to iterate an array:

for(var i = 0; i < array.length; i++) {
    console.log(array[i]);
}

If you work with smaller arrays, it’s fine, but if you process large arrays, this code will recalculate the size of an array in every iteration of this loop and this will cause some delays.

To avoid it, you can cache the array.length in a variable to use it, instead of invoking the array.length every time during the loop:

var length = array.length;
for(var i = 0; i < length; i++) {
    console.log(array[i]);
}

To make it smaller, just write this code:

for(var i = 0, length = array.length; i < length; i++) {
    console.log(array[i]);
}

6. Getting the Last Item in the Array

The Array.prototype.slice(begin, end) has the power to cut arrays when you set the beginning and end arguments. But, if you don’t set the end argument, this function will automatically set the max value for the array.

I think that few people know that this function can accept negative values, and if you set a negative number as the beginning argument, you will get the last elements from the array:

var array = [1,2,3,4,5,6];
console.log(array.slice(-1)); // [6]
console.log(array.slice(-2)); // [5,6]
console.log(array.slice(-3)); // [4,5,6]

7 Truncating Array

This technique can lock the array’s size, this is very useful to delete some elements from the array based on the number of elements you want to set.

For example, if you have an array with 10 elements but you want to get only the first five elements, you can truncate the array, making it smaller by setting the array.length = 5. See this example:

var array = [1,2,3,4,5,6];
console.log(array.length); // 6
array.length = 3;
console.log(array.length); // 3
console.log(array); // [1,2,3]

8. Replace All

The String.replace() function allows you to use string and regex to replace strings; natively, this function only replaces the first occurrence. But you can simulate a replaceAll() function by using the /g at the end of a Regex:

var string = "john john";
console.log(string.replace(/hn/, "ana")); // "joana john"
console.log(string.replace(/hn/g, "ana")); // "joana joana"

9. Converting NodeList to Arrays

If you run the document.querySelectorAll("p") function, it will probably return an array of DOM elements, the NodeList object. But this object doesn’t have all the array’s functions, like: sort(), reduce(), map(), filter().

To enable these and many other native array functions, you need to convert NodeList into Arrays. To run this technique, just use this function: [].slice.call(elements):

var elements = document.querySelectorAll("p"); // NodeList
var arrayElements = [].slice.call(elements); // Now the NodeList is an array
// This is another way of converting NodeList to Arrayvar arrayElements = Array.from(elements);

10. Merging Arrays

If you need to merge two arrays, you can use the Array.concat() function:

var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.concat(array2)); // [1,2,3,4,5,6];

However, this function is not the most suitable to merge large arrays because it will consume a lot of memory by creating a new array.

In this case, you can use Array.push.apply(arr1, arr2), which instead creates a new array. It will merge the second array into the first one, reducing memory usage:

var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];

Resource : JavaScript Tips

javascript programming

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Learning JavaScript: Development Environments for JavaScript Programming

One of the nice things about learning JavaScript these days is that there is a plethora of choices for writing and running JavaScript code. In this article, I’m going to describe a few of these environments and show you the environment I’ll be using in this series of articles.

Learning JavaScript: Data Types and Variables

To paraphrase the title of an old computer science textbook, “Algorithms + Data = Programs.” The first step in learning a programming language such as JavaScript is to learn what types of data the language can work with. The second step is to learn how to store that data in variables. In this article I’ll discuss the different types of data you can work with in a JavaScript program and how to create and use variables to store and manipulate that data.

[ Professor JavaScript ]: Introduction

Professor JavaScript is a JavaScript online learning courses YouTube Channel. Students can learn how to develop codes with JavaScript from basic to advanced levels through the online courses in this YouTube channel.

From imperative to declarative JavaScript

In this post, I will explain why declarative code is better than imperative code. Then I will list some techniques to convert imperative JavaScript to a declarative one in common situations.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.