DEV Community

Cover image for 8 Ridiculously Simple Javascript Tricks Not Taught on Tutorials
Vaibhav Namburi
Vaibhav Namburi

Posted on

8 Ridiculously Simple Javascript Tricks Not Taught on Tutorials

I've been a little busy building cenario over the past few months and shining my coding skills again.

During this period I remembered/learnt a lot of simple tricks that might be useful for beginners or people looking to quickly upgrade their syntax knowledge

So here we go 🚀:

Null checker (optional chaining)

I used to use _.get from lodash, but since a little while I'm using a babel preset to use this pattern

PS this is available in Node 14, but if you want to use it in your current project you can use the optional chaining babel plugin

Alt Text

Destructuring Arguments in a function

It gets a little clunky to reference the same nested variable within the function, that could have been done on the argument level.

Alt Text

Reallocating variables

Naming variables is tougher than people think. Combine that with my low with destructuring, I found it painful that variables would conflict whenever I would destructure. This has been in my pocket for a few years now

Alt Text

Staying away from splice

I've stayed away from splice actively, just from seeing its internal working and knowing how slowly it operates. Yes you can also use splice for this

Alt Text

Maintaining the context of this easily in objects

Super simple shortcut

Alt Text

Typescript without Typescript

Okay I'm kidding, this is not typescript, but hey you can set arguments to be required values, vs doing null checks within the function

Alt Text

Unique array

This is a doozy and has been for so long, lodash has a uniq method too, I used to use that a lot until I remembered good mate JS allows for Sets and Maps (a topic for another day)

So you can create an array with unique values, in a very performant way, and in a clean way using Sets

Alt Text

Default away

Sometimes you want to ensure there's at least some default value set to the arguments of your function

Alt Text


There you go, all simple things and most importantly they don't ruin readability (like many hacks)

Hope you enjoyed this! Looking forward to getting more active again!

twitter: twitter.com/@veebuv
linkedin: linkedin.com/in/vaibhavnamburi
instagram: _veebuv

Top comments (27)

Collapse
 
amitcoditas profile image
Amit Thakkar

for validations, do explore object proxies.

developer.mozilla.org/en-US/docs/W...

let validator = {
  set: function(obj, prop, value) {
    if (prop === 'age') {
      if (!Number.isInteger(value)) {
        throw new TypeError('The age is not an integer');
      }
      if (value > 200) {
        throw new RangeError('The age seems invalid');
      }
    }

    // The default behavior to store the value
    obj[prop] = value;

    // Indicate success
    return true;
  }
};

const person = new Proxy({}, validator);

person.age = 100;
console.log(person.age); // 100
person.age = 'young';    // Throws an exception
person.age = 300;        // Throws an exception
Collapse
 
veebuv profile image
Vaibhav Namburi

Proxies are not talked about enough!

Thanks for this!

Collapse
 
eastonaltman profile image
Easton Altman

Nice tricks!
But why did you put screenshots of code instead of blocks of code?

See markdown cheatsheet here.

I'll get back to this article in a few days and I'm sure I'll see at least one comment from an "experienced" developer about how this code is not readable and how junior developers should not try this.

That "experienced" developer is usually someone who has been working in the same company for the last 3 years, which is also probably the only company where he worked at.

That person is probably also very vocal about how amazing Java is and how horrible PHP is.

Collapse
 
veebuv profile image
Vaibhav Namburi

Hey mate!

Thanks for the comment, honestly I was just exploring different styles of writing this blog. If you have a chance of checking out the previous blogs I've used the markdown approach 😀

That's fair but I tried being very particular about those tricks, and ensuring these are just good practices as well as be "tricks" at the same time.

So lets hope someone like that isn't too unimpressed with this 😉

Thanks again, hope you have a fantastic day!

Collapse
 
jvarness profile image
Jake Varness

This decade-old engineer approves.

Collapse
 
potouridisio profile image
Ioannis Potouridis • Edited

In addition to 'Reallocating variables', object-like destructuring of arrays is a trick I don't see that often.

const people = [
  {
    age: 33,
    name: 'John',
  },
  {
    age: 29,
    name: 'Helen',
  },
];

const { 1: secondPerson } = people;

console.log(secondPerson); // prints { age: 29, name: 'Helen' }

Or to make it even more ridiculous, you may want to destructure just the age of the secondPerson, but also keep the secondPerson object as a whole.

const { 1: secondPerson, 1: { age: secondPersonsAge } } = people;

console.log({ secondPerson, secondPersonsAge });
// prints { secondPerson: { age: 29, name: 'Helen' }, secondPersonsAge: 29 }
Collapse
 
veebuv profile image
Vaibhav Namburi

Jesus Christ, at this point I would probably have just done it in a non destructured way haha.

Pretty neat though

Collapse
 
codr profile image
Ilya Nevolin

The correct name for your null checker is optional chaining. And beware, its not supported on mobile browsers and IE.

developer.mozilla.org/en-US/docs/W...

Collapse
 
veebuv profile image
Vaibhav Namburi

Using the Babel preset will be sufficient enough

Collapse
 
codr profile image
Ilya Nevolin

not everyone uses babel

Thread Thread
 
veebuv profile image
Vaibhav Namburi

Fair play - will update the article to reflect :)

Collapse
 
manuelojeda profile image
Manuel Ojeda

You can remove items from an array by using the filter function by giving the desire value comparing the difference

const array = [1, 2, 3, 4, 5]

// Let's remove 3
console.log(array.filter((item) => item !== 3))
// [1, 2, 4, 5]

Collapse
 
veebuv profile image
Vaibhav Namburi

Yeah but this is a O(n) complexity, array.length = whatever is O(1) :)

Unless we're talking about two different things ofc 😂

Collapse
 
madza profile image
Madza

I always have to look up slice vs splice, lol xdd

Collapse
 
veebuv profile image
Vaibhav Namburi

The one I almost always forget I'd the argument structure of reduce 🤣

Collapse
 
notngan profile image
Ngan B. Nguyen

May I ask what's the difference between { date: objDate } = obj vs. objDate = obj.date?

Collapse
 
veebuv profile image
Vaibhav Namburi

Literally nothing, its just a pattern some people use. I try not to always do destructed reassignment because it looks "messy" but sometimes I inherit projects where destructuring is used across the project and to stay consistent i keep with this pattern

Collapse
 
wimjongeneel profile image
Wim Jongeneel

There is one important difference: destruction shallowly clones the object. This is very important when considering referential transparency.

Thread Thread
 
veebuv profile image
Vaibhav Namburi

Would love for you to expand on this further. I agree with you and have a similar understanding however keen to know your views

Collapse
 
athul7744 profile image
Athul Anil Kumar

This was amazing! Thanks for sharing!

Collapse
 
veebuv profile image
Vaibhav Namburi

No worries!

Collapse
 
mellen profile image
Matt Ellen

Arrays do have slice.

Collapse
 
veebuv profile image
Vaibhav Namburi

You're right lol, how did I miss that. Since arrays act like string stacks anyway. Fixed it :)

Collapse
 
dineshmadanlal profile image
dineshmadanlal

This was a good read. Thanks for sharing Vaibhav!

Collapse
 
veebuv profile image
Vaibhav Namburi

Thanks Dinesh! Glad you liked it!

Collapse
 
rameshkumarjain profile image
Ramesh Kumar M

Thanks for sharing Vaibhav. yes., above are simple tricks that we will be using every day in our code.

Collapse
 
veebuv profile image
Vaibhav Namburi

Thanks Ramesh! Really appreciate it!

Some comments have been hidden by the post's author - find out more