loading...
Cover image for 8 Ridiculously Simple Javascript Tricks Not Taught on Tutorials

8 Ridiculously Simple Javascript Tricks Not Taught on Tutorials

veebuv profile image Vaibhav Namburi ・2 min read

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

Posted on by:

veebuv profile

Vaibhav Namburi

@veebuv

All things software & product, honestly - FrontEnd, BackEnd, DevOps, ML - as long as we're solving massive problems. My code is used by millions of users globally - Potatoes make me happy

Discussion

markdown guide
 

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
 

Proxies are not talked about enough!

Thanks for this!

 

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.

 

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!

 

This decade-old engineer approves.

 

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 }
 

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

Pretty neat though

 

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...

 

Using the Babel preset will be sufficient enough

 

Fair play - will update the article to reflect :)

 

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]

 

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

Unless we're talking about two different things ofc 😂

 

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

 

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

 

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

 

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

 

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

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

 
 
 

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

 

This was a good read. Thanks for sharing Vaibhav!

 

Thanks Dinesh! Glad you liked it!

 

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

 

Thanks Ramesh! Really appreciate it!