DEV Community

Cover image for 8 neat Javascript tricks you didn't know in 4 minutes.
Blessing Hirwa
Blessing Hirwa

Posted on • Updated on

8 neat Javascript tricks you didn't know in 4 minutes.

Introduction
Javascript is a powerful programming language especially in web development that is used to create and control dynamic website content, i.e. anything that moves, refreshes, or otherwise changes on your screen without requiring you to manually reload a web page. During the last 5 years Javascript is becoming famous because of it's simplicity and many feautres it has and also many packages out there. So without further ado let's dive right into it.

1. String to a number
Now you can easily convert a string to a number by just only using + sign. Unlike the old method, using + operator is much cleaner and easier.

my_string = "123";
console.log(+my_string);
// 123

my_string = "amazing";
console.log(+my_string);
// NaN
Enter fullscreen mode Exit fullscreen mode

Please note that, it only works with string numbers as you can see in the example above.

2. A number to a string
You can convert a number to a string in a simpler way without using JavaScript built in toString() method.

Have a look at this:

let converted_number = 5 + "";
console.log(converted_number);
// 5

console.log(typeof converted_number); 
// string
Enter fullscreen mode Exit fullscreen mode

3. Get unique values
We can extract unique values from an array i.e removing duplicate values in an array by simply using the Set object and Spread operator.

Here's a simple demo

let array_values = [1, 3, 3, 4, 5, 6, 6, 6,8, 4, 1]
let unique_values = [...new Set(array_values )];
console.log(unique_values );
// [1,3, 4, 5, 6, 8]
Enter fullscreen mode Exit fullscreen mode

4. Replace all
We usually know string.replace method replaces on the first occurence. In any case, regular expressions in Javascript can be used to replace certain content on strings.

In our example we'll use global regex /g to replace all occurrences of of a string.

let replace_string = "Visit stunnitysoft. stunnitysoft is a software company";
console.log(replace_string.replace(/stunnity/, "Micro")); 
// "Visit Microsoft. stunnitysoft is a software company"
console.log(replace_string.replace(/stunnity/g, "Micro")); 
// "Visit Microsoft. Microsoft is a software company"
Enter fullscreen mode Exit fullscreen mode

5. Optional Chaining
The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

Let's consider the expression a?.b.

This expression evaluates to a.b if a is not null and not undefined, otherwise, it evaluates to undefined.

You can also chain this multiple times like a?.b?.c

If a is undefined or null, then this expression evaluates to undefined
Else if b is undefined or null, then this expression evaluates to undefined
Else this evaluates to a.b.c

Syntax

obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)
Enter fullscreen mode Exit fullscreen mode

6. Nullish Coalescing Operator
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

Consider the expression a ?? b. This evaluates to b if a is null or undefined, otherwise, it evaluates to a

7. Logical AND (&&) and Logical OR (||) Operators

Logical AND (&&) Operator
Let's say we have the following expression where b and c are expressions.

b && c
Enter fullscreen mode Exit fullscreen mode

This will be evaluated to the value of c only if b is truthy, otherwise, it will be evaluated to the value of b.

  • If b is falsy, then the expression c is not even going to be evaluated.
  • This is called short-circuit evaluation.
  • This is very useful while using React.

Logical OR (||) Operator
Let's say we have the following expression where b and c are expressions.

b || c
Enter fullscreen mode Exit fullscreen mode

This will be evaluated to the value of b if b is truthy, otherwise, it will be evaluated to the value of c.

  • Short-circuit evaluation happens here too.
  • If b is truthy, then the expression c is not even going to be evaluated.
  • This is also used often in React.

8. Using length to resize and emptying an array
In javascript we can override a built in method called length and assign it a value of your choice.

Let's consider the following example:

let array_values= [1, 2, 3, 4, 5, 6, 7, 8];  
console.log(array_values.length); 
// 8  
array_values.length = 5;  
console.log(array_values.length); 
// 5  
console.log(array_values); 
// [1, 2, 3, 4,5]
Enter fullscreen mode Exit fullscreen mode

Emptying an array

let array_values= [1, 2, 3, 4, 5, 6, 7,8]; 
console.log(array_values.length); 
// 8  
array_values.length = 0;   
console.log(array_values.length); 
// 0 
console.log(array_values); 
// []
Enter fullscreen mode Exit fullscreen mode

Note: Setting the length to 0 is not advisable as it can lead to a memory leak. In order to clean objects in an array from memory, they need to be explicitly removed.

Conclusion
As you can see, we did a lot of powerful stuff without writing too many lines of code. Go ahead and use these JavaScript skills as they will keep your code more cleaner and maintainable.

This was too long but thank you for holding on until the last line
😊, I hope this article was helpful, and if so please share it to other people who can find it useful. Feel free to give a suggestion or shoot me a message on Twitter or Linkedin.

Top comments (92)

Collapse
 
lloydfranklinsmith profile image
Lloyd Franklin Smith • Edited

I really dislike 1 and 2 if someone tried to get a pull request passed using those techniques I would reject them.
It just makes the code harder to read because it isn't immediately if you are attempting a conversion or just made a mistake.

Collapse
 
sureshvv_37 profile image
sureshvv

Why would you assume that it is a "mistake" when there is a perfectly reasonable alternative?

These are idiomatic usages that will become popular over time. Since code lives forever, economy of expression is vital.

Collapse
 
lloydfranklinsmith profile image
Lloyd Franklin Smith

It isn't that I would assume it is a mistake its more that parseInt clearly lets me know it wasn't which prevents misunderstandings at the end of the day this is a code style issue and every team needs to develop their own to work together efficiently for me that means writing my code in a way that won't confuse people less familiar with JS then myself(I'm a freelancer and am often get called in when someones 'in over their heads').
Concerning the economy of expression, we seem to have very different development philosophies I would rather write a few lines more and have my code be either to understand then confront any future developers with clever ternary expressions and one liners.
Code doesn't live forever it is constantly changed and replaced requirements and environments change so it is important we keep things flexible which in my opinion includes preferring code the function of which someone that doesn't even know the specific language could understand.

Sorry about the blog post and lets not forget that the two methods under discussion function differently

Thread Thread
 
zackdotcomputer profile image
Zack Sheppard

I agree with Lloyd here about using the single "+" instead of writing "parseInt". While it's a fun trick to know about, this would also be a thing I would flag (or worse, miss) in a PR and ask to be changed to the more understandable "parseInt".

Economy of expression or terseness isn't more valuable than understandability, otherwise we'd all minify our code before committing it.

Thread Thread
 
josefjelinek profile image
Josef Jelinek

parseInt(s) is not a good example, it works very differently and has a radix issue... parseFloat(s) is closer, but still ignores any junk at the end of the string... I usually call Number(s) (not new Number(x), which has even worse problems), which is explicit and behaves just like unary + operator... Even this has a surprising issue of an empty string evaluating to 0...

Thread Thread
 
sureshvv_37 profile image
sureshvv

Do not confuse Economy of Expression with Minification because the intention of the former is to increase clarity and ease of understanding. Sometimes fewer words express more clearly what is intended and longer sentences are a means of hiding the real crux of the message.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Yes, it has other alternatives but what's wrong with them please? Is there somethings wrong with the two?

Collapse
 
lloydfranklinsmith profile image
Lloyd Franklin Smith

It's just unnecessarily difficult to tell what you are trying to do which makes the code less maintainable with parseInt I can look at the line and immediately know you meant to receive a number with the + method you might have wanted a string and just made a mistake and forgot whatever should have come before.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

The reason why you see parseInt and know what it's doing is because you're familiar with it, so by the time many people become familiar with it then they'll easily recognize it, but I think this ones are also obvious by the way. But anyway it's totally fine, thank you for the feedback 😁

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

This makes sense. At this point then one has to be more careful.

Thread Thread
 
jkettmann profile image
Johannes Kettmann

I would disagree. parseInt is much more explicit because it does what it says. It parses an integer.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

I agree. But all can be used.

Collapse
 
vitalcog profile image
Chad Windham

When using the parseInt or toString methods, it is an example of self documenting code. The instructions of what is happening are in the methods themselves, like writing comments without having to write comments. Simple, straightforward, self-documenting code is the best type of code when working large production code bases IRL. Your tricks were fun though, thanks for sharing 👍

Collapse
 
danielwu profile image
Daniel Wilianto

parseInt makes it obvious that we want to get an integer (from string). Using +"123" is confusing, and it's not apparent that we want to get integer 123. There is a reason why programming languages use natural language.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

yes but there's always a reason why something was invented. Sometimes you'll see where people used these kind of tricks so it's good to know them too.

Thread Thread
 
lloydfranklinsmith profile image
Lloyd Franklin Smith

It definitely is good to know and your article did a good job of explaining it.

Collapse
 
destroyer22719 profile image
Nathan Cai • Edited

Hey nice post, however "emptying array" can simply be done with array=[]

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Technically not emptying the array, rather replacing it with a new empty one

Collapse
 
destroyer22719 profile image
Nathan Cai

but it still kinda achieves the exact same thing.

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

Not really. If you have another reference to the original array, and you use this method to 'empty' it - stuff is going to break as the other reference will still contain the unemptied array

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

Thanks for the support Nathan.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

I've never met that kind of error but I'll try it in the future. Thanks for the assistance though.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

I've never met that kind of error but I'll try it in the future. Thanks for the assistance though.

Thread Thread
 
industral profile image
Alex Ivasyuv

var a = [1, 2, 3]
var b = a;
a = [];
console.log(b); // [1, 2, 3]

Collapse
 
jkettmann profile image
Johannes Kettmann • Edited

These are all nice tricks but I wouldn't recommend using most of them on production code. +'123' for example just doesn't explain what's going on to anyone who's not familiar with the syntax

Edit: "most of them" was exaggerated to be fair. 1,2, and 8 wouldn't pass a code review from my perspective. 3 would be critical, but it might be a nice way when wrapped in a descriptive function

Collapse
 
sureshvv_37 profile image
sureshvv

No one would write +"123". They may as well write 123.

But they may write value = +value instead of value = parseInt(value)

And that would be a win!

Collapse
 
jkettmann profile image
Johannes Kettmann

How would that be a win?

Thread Thread
 
sureshvv_37 profile image
sureshvv

Economy of expression. Strength of any language is how well it can express ideas in a well understood and succinct manner. Unary plus (+) is now a type conversion operator with well defined semantics,

Thread Thread
 
gilfewster profile image
Gil Fewster

One reason why you may favour unary plus over parseFloat/parseInt is to protect against incorrect results if the string you're attempting to convert contains one or more thousands separator commas or more than 1 decimal point:

const str = "6,750";
const str2 = "6750.45.99";
console.log(parseFloat(str)) // 6
console.log(parseFloat(str2)) // 6750.45
console.log(+str) // NaN
console.log(+str2) // NaN
Enter fullscreen mode Exit fullscreen mode

I'd typically prefer to sanitise the data before attempting type conversion, but I still like that the unary plus operator refuses to take a guess when given an ambiguous input.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

That's a good example Gil. Thanks 😁

Collapse
 
blessinghirwa profile image
Blessing Hirwa

These tricks are used by some people, so it's better to know them so that whenever you see it you won't get confused. But some of them are confusing lol.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Coding to the lowest common denominator of syntax understanding is one reason so much code these days is so bloated and slow. It is not something we should strive towards

Collapse
 
eecolor profile image
EECOLOR

I noticed some other people have already voiced their concerns about +string and number + ''. I would like to raise some concerns myself.

As you mentioned in one of the comments, in real life it would be +someVariable. This means that the value most likely is from an external source and should be checked for NaN. Please note the difference in output between these two forms:

+''
parseInt('', 10)
Enter fullscreen mode Exit fullscreen mode

Another reason I would prefer parseInt is that it is now clear the value was supposed to be parsed as an integer and there is no typeo.

For a + '' my only argument is the intention one. To me it's much more clear if it is written as follows:

`${value}`
value.toString()
Enter fullscreen mode Exit fullscreen mode

Here I think toString() might be best because it forces you to make a conscious decision on how to deal with null and undefined. When dealing with outputting for display I would probably recommend ${value}.

Collapse
 
gilfewster profile image
Gil Fewster

Good catch on the parseInt('',10) vs +''

But on the flip side, consider:

console.log(+'1,234')  //  NaN
console.log(parseInt( '1,234', 10)) //  1
Enter fullscreen mode Exit fullscreen mode

In this instance, I'd say the unary operator gives a more reliable result, since NaN at least indicates an error in type coercion. The result from parseInt is not correct, but is still a valid number so a much more difficult bug to catch.

Either way, the moral of the story is that almost any method of type coercion is vulnerable to failure unless the data is carefully sanitised beforehand.

As far as which method best indicates the intended operation, I think the solution most often is to wrap the code inside a function, so that the intention is signposted by the function name not the implementation code.

const stringToNumber = (str) => { 
  // whatever code we use in here, the name
  // of the function clearly indicates our intent
  const num  = +str;
  if (str.length == 0 || isNaN(num)) {
    throw new Error (`Cannot coerce ${str} to Number`);
  }
  return num;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ajinspiro profile image
Info Comment hidden by post author - thread only accessible via permalink
Arun Kumar

Great one, Gil. I truly appreciate your js skills. But the author hasn't mentioned this in his post, has he ? He is simply promoting the use of unary operator for string conversion instead of using parseInt( ), FOR WHICH he is receiving EECOLOR's criticism (and mine for that matter).

Even though I accept your point that in the case you mentioned above, where use of unary + is better than parseInt - I strongly disagree this is a real world scenario. We explicitly make a string variable to number only when we actually know it is going to be a number. If a developer would knew there is going to be a comma between the numbers they would be replacing those commas with nothing, which will produce correct results.

 
gilfewster profile image
Gil Fewster • Edited

I agree that relying on the coercion method alone is dangerous and liable to produce errors.

Which is why I said in my previous post that almost any method of type coercion is vulnerable to failure unless the data is carefully sanitised beforehand.

Collapse
 
eecolor profile image
EECOLOR

Ahh yeah, I forgot about the fact that parseInt ignores anything non-numeric after a number.

I would still rather use Number(value) to +value to clarify intent.

Thread Thread
 
gilfewster profile image
Gil Fewster

Yeah, I don’t think I’d use unary plus either, but sometimes a use case presents itself for unexpected things. I certainly didn’t know about it, and now I do, so I’ve learned something.

I think partly the dislike of it comes from its unfamiliarity. We don’t see it in common use very often, whereas the old value * 1 trick for type coercion is scattered throughout the internet. While you could certainly debate the wisdom of that technique, I’d imagine most developers would understand the intent immediately when they see it — largely because it’s an old and well-known shortcut. But on the face of it, multiplying something by 1 could seem a pretty pointless thing to do.

This is all a great example of the fact that what we think of as intuitive as often really just what we learned through repetition and convention.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

I like this one.

Collapse
 
sureshvv_37 profile image
sureshvv

Since what version of javascript these features are available?

My sense is that the shortcut logical operators have been there forever (inspired from C) whereas the null coalescing operators are fairly recent.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

It was available in Ecmascript 2020

Collapse
 
sureshvv_37 profile image
sureshvv

Short circuiting logical operators have been around for over a decade. I don't think that is new.

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa

Some in the comments said that they didn't know it so it was beneficial to some. Btw thanks for the feedback 😊

Collapse
 
blessinghirwa profile image
Blessing Hirwa

And also it was available in Typescript 3.7

Collapse
 
ram12ka4 profile image
Info Comment hidden by post author - thread only accessible via permalink
Ram Kumar Basak

There is a below silly mistake

let replace_string = "Visit stunnitysoft. stunnitysoft is a software company";
console.log(replace_string.replace(/stunnity/, "Micros"));
It prints Visit Microssoft. stunnitysoft is a software company

Collapse
 
majiyd profile image
majiyd

Can't you people express yourselves without being condescending?

Collapse
 
blessinghirwa profile image
Blessing Hirwa

ohhh I didn't catch that. Thanks the correction.

Collapse
 
themightyt_v3 profile image
theMightiestT

that first example of string conversion is actually implicit type coercion - not really a "neat trick" but an oft-debated "feature or bug" point of contention.

also really bad practice.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

I've been using it for a while but I've never met a problem with it, but I'll inspect that too. Thank you for the feedback 😊

Collapse
 
glowkeeper profile image
Steve Huckle • Edited

But I knew all of them! ;)

Collapse
 
greybax profile image
Aleksandr Filatov

great set of snippets! Didn't know some of them. I have list of js snippets as well just check it out in my blog alfilatov.com/posts/useful-js-snip...

Collapse
 
jeremy_chambers profile image
Jeremy Chambers

I learned something new, thank you!

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more