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

Blessing Hirwa @blessinghirwa

About: Fullstack web developer 💻 | ReactJS enthusiast ⚛ | Music 🎵 | Blogger | UI Designer | I love and trust Javascript

Location:
Kigali,Rwanda
Joined:
Jun 18, 2020

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

Publish Date: Dec 10 '20
325 92

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.

Comments 92 total

  • Nathan Cai
    Nathan CaiDec 10, 2020

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

    • Jon Randy 🎖️
      Jon Randy 🎖️Dec 10, 2020

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

      • Nathan Cai
        Nathan CaiDec 10, 2020

        but it still kinda achieves the exact same thing.

        • Jon Randy 🎖️
          Jon Randy 🎖️Dec 10, 2020

          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

          • Blessing Hirwa
            Blessing HirwaDec 10, 2020

            Thanks for the support Nathan.

            • Blessing Hirwa
              Blessing HirwaDec 10, 2020

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

              • Blessing Hirwa
                Blessing HirwaDec 10, 2020

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

                • Alex Ivasyuv
                  Alex IvasyuvDec 13, 2020

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

  • Best Verie Iradukunda
    Best Verie IradukundaDec 10, 2020

    Awesome mr. Stack . thanks for sharing

  • Oreste Abizera
    Oreste AbizeraDec 10, 2020

    good content. Loved "Optional Chaining" 😍

    • Blessing Hirwa
      Blessing HirwaDec 10, 2020

      Try it, it really saved me from a headache especially in React lol 😂

  • Didier Munezero
    Didier MunezeroDec 10, 2020

    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.

  • Kinanee Samson
    Kinanee SamsonDec 10, 2020

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

  • Best Verie Iradukunda
    Best Verie IradukundaDec 10, 2020

    tnx a lot

  • Aleksandr Filatov
    Aleksandr FilatovDec 10, 2020

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

  • Mohammad Fazel
    Mohammad FazelDec 10, 2020

    thanks

  • Achinike Chidera
    Achinike ChideraDec 11, 2020

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

  • Dima
    DimaDec 11, 2020

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

    • Blessing Hirwa
      Blessing HirwaDec 11, 2020

      Do you want to extract unique values from this array?

      • Dima
        DimaDec 11, 2020

        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', ],
        },

        • Blessing Hirwa
          Blessing HirwaDec 11, 2020

          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.

  • Adam
    Adam Dec 11, 2020

    Thank You!

  • pl709
    pl709Dec 11, 2020

    Nice post with neat tricks

  • Jeremy Chambers
    Jeremy ChambersDec 11, 2020

    I learned something new, thank you!

  • Joao Romao
    Joao RomaoDec 12, 2020

    Thank you for the post.

  • Lloyd Franklin Smith
    Lloyd Franklin SmithDec 12, 2020

    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.

    • Blessing Hirwa
      Blessing HirwaDec 12, 2020

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

      • Lloyd Franklin Smith
        Lloyd Franklin SmithDec 12, 2020

        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.

        • Blessing Hirwa
          Blessing HirwaDec 12, 2020

          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 😁

          • Blessing Hirwa
            Blessing HirwaDec 12, 2020

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

            • Johannes Kettmann
              Johannes KettmannDec 12, 2020

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

      • Daniel Wilianto
        Daniel WiliantoDec 13, 2020

        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.

        • Blessing Hirwa
          Blessing HirwaDec 13, 2020

          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.

          • Lloyd Franklin Smith
            Lloyd Franklin SmithDec 13, 2020

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

      • Chad Windham
        Chad WindhamDec 13, 2020

        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 👍

    • sureshvv
      sureshvvDec 14, 2020

      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.

      • Lloyd Franklin Smith
        Lloyd Franklin SmithDec 14, 2020

        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

        • Zack Sheppard
          Zack SheppardDec 14, 2020

          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.

          • Josef Jelinek
            Josef JelinekDec 14, 2020

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

            • sureshvv
              sureshvvDec 20, 2020

              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.

  • theMightiestT
    theMightiestTDec 12, 2020

    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.

    • Blessing Hirwa
      Blessing HirwaDec 12, 2020

      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 😊

  • Johannes Kettmann
    Johannes KettmannDec 12, 2020

    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

    • Blessing Hirwa
      Blessing HirwaDec 13, 2020

      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.

    • sureshvv
      sureshvvDec 14, 2020

      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!

      • Johannes Kettmann
        Johannes KettmannDec 14, 2020

        How would that be a win?

        • sureshvv
          sureshvvDec 14, 2020

          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,

          • Gil Fewster
            Gil FewsterDec 14, 2020

            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.

    • Jon Randy 🎖️
      Jon Randy 🎖️Dec 16, 2020

      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

  • Carlos A.
    Carlos A.Dec 13, 2020

    Thanks for the post.

    You may also use String(value) to cast value to string.

  • АнонимDec 13, 2020

    [hidden by post author]

    • Blessing Hirwa
      Blessing HirwaDec 13, 2020

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

    • majiyd
      majiydDec 21, 2020

      Can't you people express yourselves without being condescending?

  • Amine M
    Amine MDec 13, 2020

    hi, thanks for sharing, just wanna know is there any reason for using snake case ?

  • Steve Huckle
    Steve HuckleDec 13, 2020

    But I knew all of them! ;)

  • pris stratton
    pris strattonDec 13, 2020

    I didn’t know you could add a ‘+’ before a string to turn into a number. I’m not sure I particularly like it, either. I’d prefer to see Number(string) which feels clearer.

  • АнонимDec 13, 2020

    [hidden by post author]

    • Blessing Hirwa
      Blessing HirwaDec 13, 2020

      Not really, some of them don't know or even remember this. So it's always important to remind people of these kind of tricks. But anyway sorry for that 😊

      • sureshvv
        sureshvvDec 14, 2020

        Thank you for the interesting article which has generated so much conversation. :D

    • АнонимDec 14, 2020

      [hidden by post author]

    • АнонимDec 14, 2020

      [hidden by post author]

    • Gil Fewster
      Gil FewsterDec 14, 2020

      This is a thoroughly unhelpful comment. Please keep your remarks courteous and respectful.

      • Arun Kumar
        Arun KumarDec 15, 2020

        I appreciate your criticism, but I disagree with you. I haven't disrespected the author. My comment merely states facts. When someone promises you 8 tricks you didn't knew, they are required to at least deliver 1. The author was using a click bait and delivered very less and wasted my time. And about the tricks that ze shared, a couple of them are horrible code smells. A junior developer after reading this ACTUALLY might take the author's word for it and will starts to write +str to make numbers from strings. If you think this is good, ask any junior developer you know

        what is going to be 'sum' if you do var sum = +"5"+5

        I bet you they will either say 55 or will say 'it will throw error'.
        I'm generally supportive of authors irrespective of their experience. But I found this post misleading and not well thought of, hence my comment.

        • Gil Fewster
          Gil FewsterDec 15, 2020

          Disagree by all means. Healthy debate benefits the entire community, and all of us are here to share and learn from each other.

          But please remain respectful and courteous. It’s possible to express a disagreement in a friendly and supportive way. Thank you.

          • Blessing Hirwa
            Blessing HirwaDec 15, 2020

            you're a good man Gil. I like it 😁

            • АнонимDec 15, 2020

              [deleted]

              • Arun Kumar
                Arun KumarDec 15, 2020

                You should stop using that sentence to justify your article. Instead you should have an open mind to accept valid criticism and improve your writing.

                • Blessing Hirwa
                  Blessing HirwaDec 15, 2020

                  I got your idea but as Gil said there's a way to express your thoughts/opinions in a good way. Thank you once again.

      • АнонимDec 15, 2020

        [hidden by post author]

  • sureshvv
    sureshvvDec 14, 2020

    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.

    • Blessing Hirwa
      Blessing HirwaDec 14, 2020

      It was available in Ecmascript 2020

      • Blessing Hirwa
        Blessing HirwaDec 14, 2020

        And also it was available in Typescript 3.7

      • sureshvv
        sureshvvDec 14, 2020

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

        • Blessing Hirwa
          Blessing HirwaDec 14, 2020

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

  • sureshvv
    sureshvvDec 14, 2020

    Calling these as "tricks" is not giving these "techniques" the respect they deserve. :)

  • EECOLOR
    EECOLORDec 14, 2020

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

    • Gil Fewster
      Gil FewsterDec 14, 2020

      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
      • Blessing Hirwa
        Blessing HirwaDec 14, 2020

        I like this one.

      • EECOLOR
        EECOLORDec 14, 2020

        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.

        • Gil Fewster
          Gil FewsterDec 15, 2020

          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.

      • АнонимDec 15, 2020

        [hidden by post author]

        • Gil Fewster
          Gil FewsterDec 15, 2020

          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.

  • Ivan Pozderac
    Ivan PozderacJan 4, 2021

    Thanks on this great article,

    I am already using them for years now (optional chaining was available in babel) them except 1. and 2. and array shorting/emptying as I never really had need for those!

    • Blessing Hirwa
      Blessing HirwaJan 4, 2021

      wow, that's good to hear. Optional chaining really saved me a lot of pain.

  • Μάριος
    ΜάριοςJan 7, 2024

    Nice tricks, I would avoid 1& 2 though in a real project 😄

Add comment