DEV Community

loading...

Useful Vanilla JavaScript tricks and tips

StuartCreed
Full Stack Web Developer
Updated on ・2 min read

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

Discussion (0)