DEV Community

StuartCreed
StuartCreed

Posted on • Edited on

2

Useful Vanilla JavaScript tricks and tips

Putting a + in front of a number string e.g. ‘10’ turns it into a number e.g 10.

Breaking a loop
Use return in a foreach method to breaks for the for loop:

e.g:

[1,2,3,4,5].forEach((n) => {
if (n === 3) {
console.log(n, 'returned file')
return
}
console.log(n)
})

returns:
Alt Text

Using Objects as parameters
Use objects as parameters in functions so that you do not have to specify all of the parameters when you call it. e.g.

htmlGenerator({parentElement, title1, content1, content1Listener, title2 = 'Bob Marley is awesome', content2, content2Listener} = {}) {
CODE BLOCK
}

this.htmlGenerator({parentElement: nearbySiteInfo, title1: 'Site:', content1: siteProperties.name, title2: 'Site Address:', content2: siteProperties.address})

See how content1Listener and content2Listener are not defined. This does not return in an error and if they are called in the function they return undefined as expected. This very useful when you have lots of options.

To make defaults just use the = function like the 'Bob Marley is awesome' example above.

The same principle applies to constructors in classes. An easy way to assign an object parameter to a property of the class is the following:
Object.assign(this, arguments[0]);

Where arguments is the position in the constructor arguments where the object parameter is defined.

e.g.
constructor({
map,
style,
}) {
Object.assign(this, arguments[0]);
}

Results in the following:
constructor({
map,
style,
}) {
this.map = map;
this.style = style;

}

The benefit of this is that this it is directly related to what is defined in the object parameter

Assigning a non-writable property of an object
Useful if you need to attach the parameters to the window -> i.e. can be accessible by the public.

Object.defineProperty(ElsaApp.Constants.Keys, 'bing', {
     value: "{{ config('maps.bing.key') }}",
     writable: false
});
Enter fullscreen mode Exit fullscreen mode

_ denotes a private variable in a class /** also adds it to the top of the file in JS in PHPStorm

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay