r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

101

u/nqvst Mar 18 '19

items[n % items.length]

gets an item from the list and wraps around to the start if n is larger than the list

0

u/[deleted] Mar 18 '19

[deleted]

28

u/mattlag Mar 19 '19

WTF kind of languages are 1-indexed‽

51

u/m0nn3rs Mar 19 '19

English

11

u/IntelligenceOptional Mar 19 '19

Visual Basic (pre-dot-Net) and some other old BASIC languages (shudder)

6

u/BecauseImAsian Mar 19 '19

Mathematica/Wolfram Language

5

u/JohnMcPineapple Mar 19 '19 edited Oct 08 '24

...

→ More replies (7)

0

u/[deleted] Mar 18 '19

[deleted]

31

u/StopPostingOnReddit Mar 18 '19

Slideshow where you want the current slide to wrap around to the first after the last slide

21

u/ghillerd Mar 19 '19

It spooks me that the current slide number just keeps increasing

2

u/tadziobadzio Mar 19 '19

Don't worry the number will just wrap around if gets too big. Jk once it hits max number it will stop incrementing

5

u/rcfox Mar 19 '19

The maximum value you can have in a Javascript number is 1.7976931348623157e+308, but doing a++ will stop incrementing after 253.

5

u/sharted_ptr Mar 19 '19

So, if each slide displays for 1 second, we are good for 285 427 017 years.

→ More replies (1)

8

u/barrtender Mar 19 '19

As long as it's not a carousel.

http://shouldiuseacarousel.com/

14

u/zombarista Mar 19 '19 edited Mar 19 '19

Month and hour. For example

let nowMonth = 2; // March 
let futureMonth = nowMonth + 18;
console.log( months[ futureMonth % months.length ] );  // still outputs September, even though there isn't a 20th month

Worth noting that lots of languages refer to their months from 0-11, presumably for cool tricks like this.

→ More replies (2)

6

u/[deleted] Mar 19 '19

I'm doing this right now in an app where each created item is assigned a color with ~15 predefined colors after which it will loop back around. Previously I was randomly generating a color and often getting similar shades back to back.

2

u/CromulentEntity Mar 19 '19

When you want to create a sprite animation from images in an array this is the way you achieve that.

→ More replies (2)

2

u/jseego Mar 19 '19

Awesome

2

u/pookage Senior Front-End Mar 19 '19

This is so simple and delicious...

→ More replies (2)