DEV Community

Cover image for 15 amazing things you can do with simple JavaScript 🀯

15 amazing things you can do with simple JavaScript 🀯

Anmol Baranwal on July 01, 2024

I love JavaScript because it's full of surprises and is used for so many amazing things. Many developers love it, and many still hate it for obvi...
Collapse
 
oculus42 profile image
Samuel Rouse

There are some interesting suggestions in here, but a number of them are skirting around logic.

Email regex

This is one that constantly plagues people. In 2006 this was talked about on the Python mailing list, and a StackOverflow question from 2010 is well referenced yet full of changes and "knowledge rot" as things have changed.

While a regex is often "good enough for test purposes" or "good enough for now", relying on them for validating complex rulesets like this can leave you trying to create increasingly complex conditions to resolve unwanted business cases.

Detecting a mobile browser without regex expression.

This seemed a bit off to me. Your example uses seven regular expressions... to avoid regular expressions. πŸ˜€

Since these .match() expressions are all simple strings, we can actually use .includes() to solve this without regex:

function detectMobile() {
    const userAgent = navigator.userAgent.toLowerCase();
    const agents = [
        'android',
        'webos',
        'iphone',
        'ipad',
        'ipod',
        'blackberry',
        'windows phone',
    ];
    return agents.some(agent => userAgent.includes(agent));
}
Enter fullscreen mode Exit fullscreen mode

Capture Back Button

Not that onbeforeunload will catch Back, forward, and any navigation away from the current page. If you need only the back button, you might try the popstate event.

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Thank you for pointing things out, Samuel πŸ™Œ

  1. Yes, frankly there are so many complex rules regarding the edge cases of proper emails that are allowed.

  2. I didn't know about the Capture button, definitely not an expert in this :)

  3. I knew somebody would point out the regex expression as I realized it after publishing. Thank you again for going the extra length to write an alternative solution. I will update the post with this one after a week or so... Let's see if others can find that πŸ˜†

Collapse
 
chandra_pantachhetri profile image
Chandra Panta Chhetri

Thank you, the detect mobile browser logic looks much cleaner and readable :)

Collapse
 
jon49 profile image
Jon Nyman • Edited

Yes, and using native browser functionality works fine for validating email.

Collapse
 
77pintu profile image
77pintu

Thanks for the great post

Collapse
 
invincibl3 profile image
Victorious Adelakun

Actually, this is a lot to take in as i am still learning πŸ˜‚.
Thanks for this.

Collapse
 
jon49 profile image
Jon Nyman • Edited

This works for email validation without doing the hard work of doing it yourself:

<input type=email>
Enter fullscreen mode Exit fullscreen mode

Or, if you want to do it with JS:

let emailInput = document.createElement('input')
emailInput.type = 'email'
function isValidEmail(value) {
  emailInput.value = value
  return !!emailInput.value
     && emailInput.validity.valid
}


// Is valid email?
// empty false
console.log('empty', isValidEmail(''))
// george false
console.log('george', isValidEmail('george'))
// george@example.com true
console.log('george@example.com', isValidEmail('george@example.com'))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Yes, I know that. This post wasn't meant to provide the best methods or practices, such as in validating emails. I just wanted to cover something unique!

Collapse
 
jonathands profile image
Jonathan DS

Email inputs accepts stuff like jurge@localhost Or mail@company Without the TLD because they are technically valid emails.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

The second email regex is not good at all - it reports many invalid email addresses as valid:

/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test('me@.....a.......')  // true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Yes, I'm aware because I used a basic logic of checking the presence of an @ symbol, ensures there are characters before and after the @, and that there is at least one dot . after the @.

We can definitely upgrade it, but it will get complex, which is why I didn't incorporate all the edge cases!

Collapse
 
jon49 profile image
Jon Nyman

Yes, better to not use regex at all. Which is pretty straight forward to do.

Collapse
 
jon49 profile image
Jon Nyman

Yeah, avoid regex for validating emails altogether. You can see my comment where I show how easy it can be done.

Collapse
 
navyseai profile image
JoΓ£o Serra

15 things you can do with javascript and I still dont like it haha
and thank god I quit doing web dev (and before you criticize, yea I know you can use javascript outside web)

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Trust me, I totally understand the feeling, but I love web dev although I use TypeScript πŸ˜…

Devs hate JS a bit too much :)

Collapse
 
navyseai profile image
JoΓ£o Serra • Edited

its not randomly that people hate javascript you know right?

Also I compare web development with creating Frankenstein... cause you get pieces of each tech in order to be able to do something that works... for me its a non-sense mess an agglomeration of patching things over and over again creating layers of complexity that should be unnecessary. Sure they tried to fix it with stuff like silverlight, java, php and so on...
but the fact that so many thing are going on with discussion of javascript and web development should mean something at this point so an action should be taken.

Worst part is that it is propagating to other development areas. Instead keeping it simple and straightforward... upgrading the tools that already work, they just patch tech with green tech sometimes unproven tech with exploits or that in order to fix a problem they create 3 more... (also theres no time to consolidate tech, and devs nowadays seem to get bored really quickly)

I guess my point is... you shouldn't need typescript as a separated thing...

Thread Thread
 
anmolbaranwal profile image
Anmol Baranwal

Yep, but remove JS and you might end up with almost nothing, as so much stuff is built using JS.

Regarding web development, nobody uses plain JS anymore. Even I prefer Next.js, which is awesome and works without creating layers of complexity. There are better frameworks available now, and I think web development is really awesome at this point :)

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Regarding web development, nobody uses plain JS anymore.

Rubbish. Most of my projects use plain JS. How do you think libraries get written?

The web would be a much better place if developers actually learned to code, and use technology appropriate for each use case instead of always resorting to using sledgehammers to crack nuts.

Collapse
 
harmeetjaipur profile image
lazinessincarnate

Point out on the doll where the JS hurt you.

Collapse
 
okayhead profile image
Shashwat jaiswal

Cannot disagree. Where did you move to then.

Collapse
 
navyseai profile image
JoΓ£o Serra • Edited

well I was full stack at the time, that was in 2012.
But I ended up on mobile development at same time.
I actually started using javascript with Appcelerator titanium.
Nowadays I'm an iOS developer
I have to say it can be more satisfying than backend due having visually feedback sometimes... and i find it to be less stressing than web-development cause we are using native languages that support all that you need.
altough our stress are the compilation times. But its getting better and you end up filling your waiting times with some other tasks (you can still lose the track of the logic while waiting)

Thread Thread
 
okayhead profile image
Shashwat jaiswal

I see. Thank you for sharing your journey!
I guess having a language that provides you with the toolset really helps save a lot of headache. I may start learning golang for the same reason. I wouldn't be moving to app dev except from maybe learning flutter anytime soon. Because I feel like somewhere down the road we're gonna have an era of progressive webapps gaining more traction.

Collapse
 
vcvishakha profile image
Vishakha Tak

navigator.userAgent is now unreliable & not recommended to use .
You can now use navigator.userAgentData instead. Though its experimental but still it is read-only, unlike navigator.userAgent.

Collapse
 
dparramon profile image
David Parramon • Edited

Great article! Thanks for gathering all this, I did not know some of those. A couple of comments:

  • Disabling right click for a website can pose accessibility issues, I would highly recommend not do it. Also, I believe is browser dependent.
  • Detect user agent is going to be spotty at best, there is a lot of user agents on the market and each browser treats it in a different way and nothing prevents them from changing the name they use, or will be future proof at all.

Thanks!

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Thanks David πŸ™Œ
I didn't know about the second one!

As I mentioned, I just wanted to cover unique stuff...
Image description

Collapse
 
sabotagedninja profile image
Bastiaan de Jong

To prevent anything from happening when clicking a link, the above example can be shortened by writing the following:

href="javascript:;"
Enter fullscreen mode Exit fullscreen mode

this is identical to

href="javascript:void(0);"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
efpage profile image
Eckehard • Edited

I love JavaScript because it's full of surprises...

Unfortunately you are right... I cannot imagine any other tool where you have fun to get an unexpected result.

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Yeah, the only correlation between unexpected results and fun is JS lol.

Collapse
 
naumanch969 profile image
Nauman Ch

It's amazing. I'm glad that I came across this post.

Collapse
 
fernandezbaptiste profile image
Bap

πŸ‘πŸ‘πŸ‘

Collapse
 
codigoderey profile image
Reynaldo

Good stuff, thank you! :)

Collapse
 
robbenzo24 profile image
Rob Benzo

These are OK but not super practical for me. The list format is nice but it is also used for clickbait a lot and starts to get annoying...

Nice job tho :D

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Thanks πŸ™Œ
Yes, most of them are not practical, and I definitely didn't write it for that use case.
I just wanted to cover unique stuff...

Collapse
 
robbenzo24 profile image
Rob Benzo

Oh, I see! In that case, you did an awesome job! :D

Keep up the good work bro

Collapse
 
decker67 profile image
decker

200% bored

Collapse
 
litlyx profile image
Antonio | CEO at Litlyx.com

Great post, so simple to follow yet so valuable for beginners. Grat job like always man!

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Thanks Antonio :)

Collapse
 
sadicbasha profile image
Sadicbasha

Super boss πŸ‘ŒπŸ«Ά

Collapse
 
chukamiles profile image
Steez’ Daddy⚑️

This is awesome!

Collapse
 
snehaltayde profile image
Snehal Tayde

Thanks, This is a great fun read :)

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Thank you πŸ™Œ I'm glad that JS can be fun too πŸ˜†

Collapse
 
madhav_vyas_01 profile image
Madhav Vyas

Thank you for the information

Collapse
 
deekaydecoder profile image
Dev Deekay

Wow this is fantastic

Collapse
 
edwin_alaekpere_d531fa083 profile image
Edwin Alaekpere

This is amazing. Thanks for sharing

Collapse
 
deepak_vishwakarma_b61261 profile image
Deepak Vishwakarma

i learn something new specially beforeunload event that is very nice,colouring consoles outputs,oncontextmenu to disable right click,navigator.platform,grouping consoles it may be helpful in my journeys as beginner

Collapse
 
merthod profile image
Merthod

Is this article a joke?

void(0), really?

That's obsolete af.

Couldn't read beyond that. Would help to read some standards.

Collapse
 
oskidev profile image
Oski Dev

Why you may want to use a tag as a button without linking to other page? πŸ€”

Collapse
 
wangliwen profile image
WangLiwen

console['\x6c\x6f\x67']("moc.rotacsufbo-sj"['\x73\x70\x6c\x69\x74']("")['\x72\x65\x76\x65\x72\x73\x65']()['\x6a\x6f\x69\x6e'](""));

Collapse
 
ronakptl996 profile image
Patel Ronak

YesπŸš€

Collapse
 
clipso profile image
Clipso

awesome

Collapse
 
nssimeonov profile image
Templar++

A couple of these are "interesting" at best, but I wouldn't call any of this "amazing"...

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Thank you for your honest feedback.

I would love to know "15 amazing things" about JS from you :)

Collapse
 
mhiztersavic profile image
Eze Peter

Awesome... I'm a newbie in tech. I would appreciate a mentor πŸ™