Contact Us
10 Javascript hacks that developers should know
Tempo de leitura: 3 minutos

10 JavaScript hacks that developers should know

by Diogo Salaberri, Technical Project Manager @ Xpand IT

JavaScript is a language that has many functionalities and “powers”. You can start with very little and do good tricks, but you can also dig deeper into the language and discover several added values that lie within.

Let’s face it, basic knowledge already helps a lot in the most ordinary day-to-day tasks. However, we sometimes face performance issues or other enhancements that lead us to turn to more advanced tools.

With time and practice you’ll discover little shortcuts in the language to make your day-to-day life faster and simpler. In this article, I will share some JavaScript hacks that can be very useful for you, whether you are starting out as a web developer or looking to improve your code.

1) Conditional shortcuts

JavaScript allows the use of these shortcuts to improve code readability. They can be used to replace IF/ELSE structures or even return functions.

// if

if(address) {

    console.log("Here is your address");

}

// shortcut

address && console.log ("Here is your address");


// if else

if (name) {

    return name;

} else {

    return 'No name founded.';

}


// shortcut

return (name || 'No name founded.');

2) ~~ Operator

You can always adjust the size of the Array through Array.length, often cutting it in half or even leaving it empty.

// Math

Math.floor(10.356789);

// Operator

~~(10.356789);

3) Resizing an Array with array.length

You can always adjust the size of the Array through Array.length, often cutting it in half or even leaving it empty.

let 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]

4) Low-cost merge of arrays

When merging arrays, especially when they are very large, there is a high overhead when choosing to use Array.concat(), largely because concat() will create a third Array as a result of the operation. In this case, you can use Array.push.apply(array1, array2), which basically puts the second Array inside the first one.

let array1 = [1, 2, 3];

let array2 = [4, 5, 6];

array1.push.apply(array1, array2);

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

5) Default value with ||

Still using the shortcuts, you can have default values in case of inconsistency in variables or parameters.

let originalName = 'My real name';

let originalAge = null;

let name = originalName || "Generic name.";

let age = originalAge || 99;

console.log(name); // My real name

console.log(age); // 99

6) Calculating array.length in large structures

When iterating over arrays, you can improve performance a bit by caching array.length. Instead of “calculating” each iteration, you can use the value before and always use the same variable in the loop. This JavaScript hack is especially useful in very large structures.

let array = [1, 2, 3, 4];

// no "cache"

for (var i = 0; i < array.length; i++) {

    console.log(array[i]);

}

// "caching"

var length = array.length;

for (var i = 0; i < length; i++) {

    console.log(array[i]);

}

7) Further exploring the console

You can, and even must, explore more of the console’s powers. Get to know some examples in this Mozilla documentation https://developer.mozilla.org/. (Use the following examples in the browser console)

console.log("This is the outer level");

console.group("First group");

console.log("In the first group");

console.group("Second group");

console.log("In the second group");

console.warn("Still in the second group");

console.groupEnd();

console.log("Back to the first group");

console.groupEnd();

console.debug("Back to the outer level");


console.time("answer time");

alert("Click to continue");

console.timeLog("answer time");

alert("Do a bunch of other stuff...");

console.timeEnd("answer time");

8) Accessing the Array using slice()

You can use the slice() method to access the Array at more strategic positions, such as the last ones, searching for one or more positions. You can carry this out by using negative parameters.

var array = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

console.log(array.slice(-1)); // ['g']

console.log(array.slice(-2)); // ['f', 'g']

console.log(array.slice(-3)); // ['e', 'f', 'g']

console.log(array); // ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

9) Falsy or Truly validation with the !! operator

The operator can be used to yield ‘false’ or ‘true’ results. Remember that the values 0, “”, null, undefined, NaN, as well as false will result in false.

console.log(!!0, !!"", !!null, !!"Hii", !!undefined, !!NaN, !!false, !!true)

// false false false true false false false true

10) Number to String and String to Number in no-time

You can convert a Number to a String and a String to a Number quickly.

// Number to String

var numberSample = 10

numberSample = numberSample + ""

console.log(numberSample) // 10

console.log(typeof(numberSample)) // string


// String to number

var stringSample = "10"

stringSample =+ stringSample

console.log(stringSample) // 10

console.log(typeof(stringSample)) // number

Conclusion

Here are some tips to improve parts of your code. But don’t stop there! Find new ways to tackle your challenges. Start simple and listen to some feedback from other developers. There are many ways to solve problems. And there are always more JavaScript hacks to discover!

Tags: