hi@methebe.com

What this JavaScript One Liner tells for beginners is VITAL - 12/01/2024

To Err is Human

Site under construction! Migrated content might be displayed ugly!

medium-to-markdown@0.0.3 convert node index.js https://medium.com/stackademic/what-this-javascript-one-liner-tells-for-beginners-is-vital-589d279fd192

What this JavaScript One Liner tells for beginners is VITAL

[Enigma Bits

](https://medium.com/@birnadin?source=post_page-----589d279fd192--------------------------------)[![Stackademic](https://miro.medium.com/v2/resize:fill:48:48/1*U-kjsW7IZUobnoy1gAp1UQ.png)

](https://blog.stackademic.com/?source=post_page-----589d279fd192--------------------------------)

Enigma Bits

·

Follow

Published in[

Stackademic

](https://blog.stackademic.com/?source=post_page-----589d279fd192--------------------------------)·5 min read·Jan 12, 2024

Listen

Share

from unsplash.com

In this blog post, I aim to guide JavaScript (JS) beginners through common pitfalls. This isn’t about a one-off error; it’s about developing habits that will save you headaches down the road.

The One Liner

Consider this JavaScript function:

function tail(a) {  
  return a.pop();  
}

At first glance, this seems to grab the tail of an array, i.e., the last element. But is it really that straightforward? Well, no spoilers yet, but let’s just say that this simple function is a Pandora’s box of common beginner mistakes.

Goggles to Insight: TypeScript to the Rescue

JavaScript’s dynamic typing is a double-edged sword: it offers flexibility but can lead to chaos.

Enter TypeScript, a superhero in the world of JS-mayhem. Let’s see what happens when we convert our function to TypeScript.

Pitfall 1: Anything Can Be Passed Around

One major issue with JavaScript is its laissez-faire attitude towards types. For example:

passing in anything is bad

In a team environment, the diversity of coding styles and assumptions can lead to misunderstandings about function usage.

For instance, a colleague might mistakenly pass a string to our tail function, expecting the last character, or an object, anticipating the last assigned property. Without type checking, such misconceptions can easily introduce bugs, particularly in larger projects where not every team member is fully aware of each function’s specific purpose and design.

A TypeScript version of our tail function might look like this:

function tail<T>(a: T\[\]): T {  
  return a.pop();  
}

This syntax uses generics, allowing tail to accept an array of any type and return an element of that type. It’s like saying, “I don’t care what’s in the array, just give me the last item.” But wait, there’s a catch. If you try to trans-pile this, TypeScript will raise an eyebrow. Why? Because the story doesn’t end here.

Your support is invaluable 😍

Pitfall 2: To Err is Human, To Err Silently is JavaScript

In JavaScript, not all functions announce their flaws. The pop() method, for instance, returns undefined when called on an empty array. This means our tail function should actually have a return type of T | undefined.

It’s like saying, “I’ll either give you the last element, or a big fat nothing.” So, the function becomes much more clear…

function tail<T>(a: Array<T>): T | undefined {  
  return a.pop()  
}

The tail function’s self-explanatory design makes additional comments redundant. Its name intuitively suggests retrieving the last array element. The use of generics (``) and the return type `T | undefined` clearly communicate its functionality and handling of different scenarios, ensuring easy understanding and usage in a coding environment.

Why does this matter? Imagine you’re working in a team, and someone uses your function without considering an empty array. Suddenly, you’re the one explaining why the code broke. TypeScript, in this case, is like that friend who nudges you, saying, “Hey, did you think this through?”

Keep Teams in Mind

When you’re learning alone, some practices might seem overkill. But in a team environment, what seems tedious can prevent disaster. Think of it as not just coding for yourself, but for those who’ll inherit your code.

Borrow Ideas

Other languages, like Rust, handle potential null returns more explicitly with constructs like `Option`. While I’m not suggesting you dive into Rust right now, borrowing concepts from different languages can enhance your coding skills.

“Sometimes, I prefer return values for error handling over exceptions. Call it a quirk!” — Birnadin E.

Pitfall 3: Remember the Mutability of States

Always check if a function mutates the data it’s given. Let’s say you want the last two items of an array. One approach might be:

function tail2<T>(a: Array<T>): Array<T | undefined> {  
  let len = a.length;  
  let lastOne = a\[len-1\];  
  let lastTwo = a\[len-2\];  
  return \[lastTwo, lastOne\];  
 }

That is mouth-some. Let’s go declarative and understand JS runtimes silence-of-the-lambs play 👇🏻.

function tail2<T>(a: Array<T>): Array<T | undefined> {  
  return \[a.pop(), a.pop()\];  
}

This works because pop() removes the last element from the array (technically In-memory operation). By calling it twice, we get the last two elements. But beware, your array `a` is now missing those elements!

from MDN

Always read the docs to understand such side effects.

Conclusion

In this post, we explored common pitfalls in JavaScript and how TypeScript can help avoid them. We learned the importance of

Remember, coding is not just about writing code that works; it’s about writing code that’s robust, understandable, and maintainable.

As I delve into solving Lisp 99 problems using JS, I’ll share more insights and tips.

If you found this helpful, consider subscribing to my Substack (free by the way). Your support helps me continue providing content like this.

Keep coding, keep learning, and always read the docs!

And hey, don’t forget to check back for more coding adventures and misadventures 😉. Happy coding!

Till then, it is meTheBE signing off 👋.

Stackademic

Thank you for reading until the end. Before you go: