DEV Community

Cover image for Useful JavaScript tips and tricks that you may not be aware of 💻👨‍💻
Aryan Dev Shourie
Aryan Dev Shourie

Posted on

Useful JavaScript tips and tricks that you may not be aware of 💻👨‍💻

JavaScript is a widely used web programming language. If you are looking to start a career in Software Engineering, then chances are that you will encounter the concepts of JavaScript.

JavaScript is unarguably the most popular programming language in the realm of web development. While it has its own caveats and tricky/confusing concepts, learning and using JavaScript is almost necessary if you want to progress in your web development career.

In this blog post, I will list down some useful JavaScript tips and tricks to help you out in challenging situations while using this language.

Automatic Semicolon Injection (ASI) in JavaScript

Some languages like C#, C++ and Java are very strict about ending each line with a semicolon.

JavaScript also uses semicolons to indicate the end of a line, but using the semicolon in JavaScript is actually optional. By optional, it means that JavaScript will apply a set of complex rules to work out whether a semicolon should have gone there or not. This is known as Automatic Semicolon Injection.

Example:

function returnSomething()
{
  return
    {
      name: 'JavaScript Expert'
      contactMethod: 'Shine batsign at sky'
    }
}
Enter fullscreen mode Exit fullscreen mode

Now upon first glance, you might think that logging this function call will show this particular object. But, if we call this function, we actually get undefined as the output.

Explanation: Because the opening bracket doesn’t occur on the same line as the return, ASI puts one semicolon in there for us. So, as far as JavaScript is concerned, our code actually looks like this:

function returnSomething()
{
  return ; // <-- semicolon inserted by ASI, remainder of function not evaluated.
    {
      name: 'JavaScript Expert'
      contactMethod: 'Shine batsign at sky'
    }
}
Enter fullscreen mode Exit fullscreen mode

This is the process of ASI. To avoid such scenarios, we should carefully look the placement of braces and other syntax.

Non-sequential Array keys and indexes

Let’s imagine we have a simple array, we know we can pop, push, append, and do whatever we like with arrays. But we also know that JavaScript, like other languages, lets us access array elements by index.

However, what’s unusual about JavaScript is that you can also set elements by array index when the array isn’t even up to that index just yet.

Example:

var arr = [];
arr[0] = 1;
arr[1] = 2;
arr[100] = 100;
console.log(arr);
console.log('The length of the array is ' + arr.length);
Enter fullscreen mode Exit fullscreen mode

Output:

[ 1, 2, <98 empty items>, 100 ]
The length of the array is 101
Enter fullscreen mode Exit fullscreen mode

Finding the OS type using JavaScript

The window.navigator object contains information about the visitor's browser OS details. Some of the OS properties are available under the platform property.

You can use the below snippet to get the OS type:

console.log(navigator.platform);
Enter fullscreen mode Exit fullscreen mode

Output:

Win32 (for Windows)
MacIntel (for modern macOS)
Linux x86_64 (64-bit Linux systems)
WebOS (for LG Smart TVs)
Linux (for Samsung Smart TVs)
Enter fullscreen mode Exit fullscreen mode

How to detect whether a mobile browser is being used for browsing

You can detect mobile browsers by simply running through a list of devices and checking if the userAgent matches anything:

function detectMobileBrowser() {
  if (
    navigator.userAgent.match(/Android/i) ||
    navigator.userAgent.match(/webOS/i) ||
    navigator.userAgent.match(/iPhone/i) ||
    navigator.userAgent.match(/iPad/i) ||
    navigator.userAgent.match(/iPod/i) ||
    navigator.userAgent.match(/BlackBerry/i) ||
    navigator.userAgent.match(/Windows Phone/i)
  ) {
    return true;
  } else {
    return false;
  }
}
Enter fullscreen mode Exit fullscreen mode

Apply CSS styles and colors on JS console messages

You can apply CSS styles and colors on the console messages using certain syntax. This can be very useful in differentiating certain messages from others.

Code example:

console.log(
        "%cStop!",
        "color:red;font-family:system-ui;font-size:4rem;-webkit-text-stroke: 1px black;font-weight:bold"
      );
Enter fullscreen mode Exit fullscreen mode

Output:

Console CSS Output

And that's it! These are just a few of lesser known JavaScript tips and tricks which might come in handy for you in the future.

Connect with me on LinkedIn :- Linkedin

Do check out my GitHub for amazing projects :- Github

View my Personal Portfolio :- Aryan's Portfolio

Top comments (7)

Collapse
 
mahmoudalaskalany profile image
Mahmoud Alaskalany

That is a great work , keep it up

Collapse
 
peter_lamb_fa3fc2089b698c profile image
Peter Lamb

It is good practice to include explicit semi-colons where applicable and not rely on JavaScript's implicit handling.

Collapse
 
sokoletu profile image
Daniel Kariuki

I have tried the mobile detection function but its not working.

The other two tips are working.

Advice way forward please.
Thanks

Collapse
 
aryan_shourie profile image
Aryan Dev Shourie

Hi Daniel, I'll look into the alternatives and get back to you

Collapse
 
makechi02 profile image
Makechi™

Great post.. đź‘Ť

Collapse
 
jeffrey_tackett_5ef1a0bdf profile image
Jeffrey Tackett

Mobile detection is not as simple as parsing the user agent string, and this does fail often enough to urge against using this technique. The truth is, you can try your best and will still fail to detect mobile devices at least 10-25% of the time, this is due to browsers being written to avoid fingerprinting methods being effective and helping protect users. If a user is using a privacy first browser, you will have a harder time detecting any stats that are correct -- the user agent string isn't required to send meaningful data, so any of that could be fake.

Collapse
 
kooiinc profile image
Info Comment hidden by post author - thread only accessible via permalink
KooiInc

Your first example would still fail when you removed the newline after return. Comma's are not optional.

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