DEV Community

Cover image for 9 Extremely Powerful JavaScript Hacks
Klaus
Klaus

Posted on • Updated on

JavaScipt Hack 9 Extremely Powerful JavaScript Hacks

I like to optimize.

But users don't care about my optimized code if the site isn't working in their Internet Explorer 11 browser.

I use Endtest to create automated tests and execute them on the cross-browser cloud.

Netflix uses the same platform to test their web apps.

It's even listed as a Required Skill for some of their jobs.

Endtest does have some really nice features, such as:
• Cross-browser grid, running on Windows and macOS machines
• Codeless Editor for Automated Tests
• Support for Web Applications
• Support for both native and hybrid Android and iOS apps
• Unlimited Video Recordings for your test runs
• Screenshot Comparison
• Geolocation
• If Statements
• Loops
• Upload files in your tests
• An Endtest API, for easy integration with your CI/CD system
• Advanced Assertions
• Mobile Tests on real mobile devices
• Email testing with Endtest Mailbox

You should check out the docs.

Below are 9 extremely powerful JavaScript hacks.

1. Replace All

We know that the string.replace() function replaces only the first occurrence.
You can replace all the occurrences by adding /g at the end of the regex.

var example = "potato potato";
console.log(example.replace(/pot/, "tom")); 
// "tomato potato"
console.log(example.replace(/pot/g, "tom")); 
// "tomato tomato"
Enter fullscreen mode Exit fullscreen mode

2. Extract Unique Values

We can create a new array only with the unique values by using the Set object and the Spread operator.

var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8]
Enter fullscreen mode Exit fullscreen mode

3. Convert number to string

We just have to use the concatenation operator with an empty set of quotation marks.

var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number); 
// string
Enter fullscreen mode Exit fullscreen mode

4. Convert string to number

All we need is the + operator.

Be careful with this one since it only works with 'string numbers'.

the_string = "123";
console.log(+the_string);
// 123

the_string = "hello";
console.log(+the_string);
// NaN
Enter fullscreen mode Exit fullscreen mode

5. Shuffle elements from array

Every day I'm shufflin'

var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(my_list.sort(function() {
    return Math.random() - 0.5
})); 
// [4, 8, 2, 9, 1, 3, 6, 5, 7]
Enter fullscreen mode Exit fullscreen mode

6. Flatten multidimensional array

Simply by using the Spread operator.

var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries); 
// [1, 2, 5, 6, 7, 9]
Enter fullscreen mode Exit fullscreen mode

7. Short Circuit Conditionals

Let's take this example:

if (available) {
    addToCart();
}
Enter fullscreen mode Exit fullscreen mode

And shorten it by simply using the variable together with the function:

available && addToCart()
Enter fullscreen mode Exit fullscreen mode

8. Dynamic Property Names

I always thought that I first had to declare an object before being able to assign a dynamic property.

const dynamic = 'flavour';
var item = {
    name: 'Coke',
    [dynamic]: 'Cherry'
}
console.log(item); 
// { name: "Coke", flavour: "Cherry" }
Enter fullscreen mode Exit fullscreen mode

9. Use length to resize/empty an array

We basically overwrite the length of the array.

If we want to resize the array:

var entries = [1, 2, 3, 4, 5, 6, 7];  
console.log(entries.length); 
// 7  
entries.length = 4;  
console.log(entries.length); 
// 4  
console.log(entries); 
// [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

If we want to empty the array:

var entries = [1, 2, 3, 4, 5, 6, 7]; 
console.log(entries.length); 
// 7  
entries.length = 0;   
console.log(entries.length); 
// 0 
console.log(entries); 
// []
Enter fullscreen mode Exit fullscreen mode

I think it's really cool that you're looking for JavaScript hacks, but are you sure your Web Application is working correctly on all browsers and devices?

You can use Endtest to quickly create Automated Tests and execute them on the cross-browser cloud.

You don't even have to code in order to use it.

Seriously, just read the docs.

Cover photo by Laurie

Latest comments (71)

Collapse
 
bfunc profile image
Pavel Litkin

Please do not set lengh of Array like this:

entries.length = 4;

this is definitly a hack, and not likely will pass code review

Collapse
 
rajmohanpdy profile image
rajmohan s

useful info. thanks for sharing.

Collapse
 
mattsmithjs profile image
MattSmith-JS • Edited

Thanks a lot Klaus.
I've been using #1 (replace + regex + global flag) heaps since reading about it here. 7 is cool. I thought JS coercion might've turned the function into a boolean, but evidently it doesn't. Thanks again.

Collapse
 
jstewart8053 profile image
jstewart8053 • Edited

I noticed the same thing... adding

entries.flat(Infinity)
Enter fullscreen mode Exit fullscreen mode

will flatten the array down to a single array no matter how nested the array is :)
Oh... and also, super-helpful Post!

Collapse
 
frakman1 profile image
Frak • Edited

Will Endtest allow me to run a test on a webpage that is behind a company firewall? i.e. will the Extension let it run the script as if it's running from my laptop that is also behind the firewall?
It doesn't look like it works. The test script I set up can't access the internal webpage.

Collapse
 
liviufromendtest profile image
Liviu Lupei

Hi Frak, Endtest can easily do that.
You just have to follow the instructions from this chapter.

Collapse
 
jasterix profile image
Jasterix

Great list!

Collapse
 
osde8info profile image
Clive Da

loving the shuffle

Collapse
 
kumareth profile image
Kumar Abhirup

Interesting.

Collapse
 
sinteticwizard profile image
Ramon Ramirez

nice

Collapse
 
zeyadetman profile image
Zeyad Etman

There's replaceAll in Javascript using babel, find it here: v8.dev/features/string-replaceall

Collapse
 
learnbyexample profile image
Sundeep

The replace all trick with regexp will work only if string to search doesn't contain regexp metacharacters like ., ^, etc. You'll have to escape them first. developer.mozilla.org/en-US/docs/W... provides an escape function.

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

'abc a;c a.c apc a.c'.replace(/a.c/g, 'X')
// gives "X X X X X"

'abc a;c a.c apc a.c'.replace(new RegExp(escapeRegExp('a.c'), 'g'), 'X')
// gives "abc a;c X apc X"

String.prototype.replaceAll is proposed to avoid such issues: github.com/tc39/proposal-string-re...

Collapse
 
razgandeanu profile image
Klaus

Interesting.
Thank you for sharing that with us.

Collapse
 
deepakpal profile image
Deepak Pal

Nice article super like

Collapse
 
itepifanio profile image
Ítalo Epifânio

And if you use .Flat(Infinity) you flat all

Collapse
 
alonshmiel profile image
alonshmiel • Edited

Hi, nice article!

Shuffling by -0.5 is not good in execution time.
It may be less harmful if the array is small.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.