DEV Community

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

Posted on • Edited 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.

Oldest comments (92)

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
 
bestverie profile image
Best Verie Iradukunda

Awesome mr. Stack . thanks for sharing

Collapse
 
blessinghirwa profile image
Blessing Hirwa

I'll try to share more of what I know.

Collapse
 
oreste profile image
Oreste Abizera

good content. Loved "Optional Chaining" 😍

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Try it, it really saved me from a headache especially in React lol πŸ˜‚

Collapse
 
didiermunezer38 profile image
Didier Munezero

Cool from our brother.
For sure I did not know all the tricks above.
Well some can be done in other simple ways but
Thank you a lot.

Collapse
 
blessinghirwa profile image
Blessing Hirwa

I'm glad to hear that you found it useful.

Collapse
 
kalashin1 profile image
Kinanee Samson

Wow, i just learnt some nifty new trick. Thanks a lot

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Glad to hear that it was useful 😁.

Collapse
 
bestverie profile image
Best Verie Iradukunda

tnx a lot

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
 
mdhesari profile image
Mohammad Fazel

thanks

Collapse
 
achinikechider2 profile image
Achinike Chidera

This is beautiful. I saw John Smilga use most of these in his React Course.
Thanks for making it a lot clearer.
Much love! ❀️

Collapse
 
blessinghirwa profile image
Blessing Hirwa

I'm happy to heart that 😁

Collapse
 
mitya profile image
Dima

How can i replace this method
.filter((item, index, array) => array.indexOf(skill) === index)
by new Set?

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Do you want to extract unique values from this array?

Collapse
 
mitya profile image
Dima

From some object with array inside. Like this (array with fruits):

const elements = [
{
type: 'Product',
email: 'buy@buy.com',
isTasty: true,
fruits: ['kiwi', 'mango', 'banana', 'kiwi', 'banana', 'orange', ],
},

Thread Thread
 
blessinghirwa profile image
Blessing Hirwa • Edited

Try this:

elements.map((element) => {
let unique_values = [...new Set(element.fruits )]
// console.log(element.fruits)
return unique_values;
})

or simply do it like this:

console.log(elements.map((element) =>
unique_values = [...new Set(element.fruits )]
))

You can either console them or store them in a variable. Overwriting the old values is also possible.

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