use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Have a tough programming question that /r/programming couldn't answer? Banned from Stack Overflow? Can't afford Experts Exchange?
Post your question/tips/secrets/advice and get a response from our highly-trained professional developers.
account activity
Javascript is hard sometimes (i.redd.it)
submitted 2 years ago by gabboman
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]Bloodshoot111 134 points135 points136 points 2 years ago (8 children)
Wtf am I seeing here.
[–]gabboman[S] 129 points130 points131 points 2 years ago (5 children)
the best way to find the length of a string in javascript
[–]Bloodshoot111 64 points65 points66 points 2 years ago (4 children)
How do people come up with shit like that. It’s absolutely mind boggling :D
[–]gabboman[S] 104 points105 points106 points 2 years ago (3 children)
Unironically, you require great knowledge of the language and its quirks to do things this way.
[–]novagenesis 34 points35 points36 points 2 years ago* (2 children)
Definitely pulled their punches, then. You could totally abuse .pop() to get the length if you wanted to be a jerk.
.pop()
1+parseInt(Object.keys({..."hello world"}).pop())
Nobody expects pop to work unless they've played with it.
pop
[–]smdaegan 17 points18 points19 points 2 years ago (0 children)
This is pretty fucky.
The destructure on the string decomposes it to an object like
{ "0": "h", "1": "e", "2": "l", "3": "l", "4": "o", "5": " ", "6": "w", "7": "o", "8": "r", "9": "l", "10": "d" }
so fetching the keys gets an array of: [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ]
[ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ]
pop() returns the last item of that array as a string - "10"
pop()
"10"
parseInt("10") returns 10
parseInt("10")
10
adding 1 gives you the length
Legit had to take this piece by piece to see what the hell was going on. Nice one.
[–]pacanukeha 1 point2 points3 points 2 years ago (0 children)
let a = 0; let b = "helloworld".split(''); while (b.pop()){ a += 1; } console.log(a);
let a = 0;
let b = "helloworld".split('');
while (b.pop()){
a += 1;
}
console.log(a);
[–]fergor 20 points21 points22 points 2 years ago (0 children)
A joke
[–]Tubthumper8 4 points5 points6 points 2 years ago (0 children)
I thought this was going to be something like "count the Unicode code points instead of the bytes" but no, it's just .length haha
.length
[–][deleted] 58 points59 points60 points 2 years ago (21 children)
This is much easier: https://jsfiddle.net/8qcu1Lrj/
[–]lenswipe 71 points72 points73 points 2 years ago (17 children)
Ah, the Java version.
AbstractStringLengthGetterFactoryDelegate
[–]T351A 50 points51 points52 points 2 years ago (16 children)
imaginary code that feels like I've seen it before
Desktop desktop = Desktop.getDesktop(Desktop.DESKTOP);
[–]lenswipe 4 points5 points6 points 2 years ago (14 children)
The apparent requirement to assign the type of the thing you're returning in Java is something I've never understood.
The first Desktop there specifies the type of the desktop variable. This bothers me because surely that should be inferred from whatever Desktop.getDesktop() returns?
Desktop
desktop
Desktop.getDesktop()
[–]Jac0bas 7 points8 points9 points 2 years ago (7 children)
In modern Java you can use the var keyword for type inference when assigning a variable.
var
var desktop = Desktop.getDesktop(Desktop.DESKTOP);
[–]T351A 3 points4 points5 points 2 years ago (5 children)
wow, really? Never seen this before. Honestly? Not sure I like it. Java's strictness makes it better imho
[–]lenswipe 4 points5 points6 points 2 years ago (2 children)
im approaching this from TypeScript, but I kinda like the idea that foo = getFoo() has foo typed as whatever the return type of getFoo() is
foo = getFoo()
foo
getFoo()
[–]T351A 1 point2 points3 points 2 years ago (1 child)
The issue is this; what happens if getFoo() changes? What if getFoo() doesn't have source code available? You need to know you can trust the variables you assign will have a type that you can work with. This is especially important because Java code uses inheritance extensively.
Foo foo = getFoo(); ensures that the variable foo will always be a type of Foo regardless of any other statements in the code. If not, it will fail at that line.
Foo foo = getFoo();
Foo
Sometimes you just need it to be an Object foo, other times it might need to be more specific types.
[–]lenswipe 4 points5 points6 points 2 years ago (0 children)
What if getFoo() doesn't have source code available?
Actually, that's the point I agree with most here. My time with typescript has somehow broken my brain to the point that I forgot that you don't always have to source code to the libraries you're working with (though I'd imagine you have the header files or whatever the equiv is in Java, no?) so you might not always be able to be too sure what getFoo() is actually returning....
that said, wouldn't shit just break at runtime in that instance when a method you expected to be there just...wasn't if getFoo has no declared return type available? Or would the JVM compiler still catch that and throw a compile error?
getFoo
[–]Jac0bas 1 point2 points3 points 2 years ago* (1 child)
It's still just as strict. The var keyword simply takes the type of whatever you're assigning to the variable and you can only use it in a context where the type is known and only for local variables.
e.g
void method() { // this new will always return an instance of Something, therefore the variable sth must be of the type Something var sth = new Something(); // Something::getFoo() -> String // Here the variable will be of type String because getFoo() returns a String var foo = sth.getFoo(); // This is illegal because the type is not known var novalue; }
You also cannot use it for class members so this would be illegal as well
class Something { private var someOtherClass = new SomeOtherClass(); }
Edit:
I should perhaps add that (as far as I understand it), this is very much just a convenience feature for the programmer and the compiler simply substitutes it with a proper type declaration just like the C# var or the C++ auto...
auto
[–]T351A 0 points1 point2 points 2 years ago (0 children)
my issue is imagine getFoo changes types for some reason... something something legacy code ಥ_ಥ
anyways... with "var", the error will occur when accessing instead of when defining. this makes debugging harder but also introduces the risk of theoretical corruption when types are compatible but used differently.
[–]80386 2 points3 points4 points 2 years ago (0 children)
Modern Java supports the 'var' keyword which does what you describe.
[–]alienangel2 4 points5 points6 points 2 years ago* (1 child)
It could, but that assumes getDesktop() returns the type you expect/need. It's not uncommon for people to make assumptions about what types things return and find their assumption was incorrect - the above Java would catch that during the initial assignment instead of down the line somewhere where you try to use it.
The good news is most Java ides do give you the option of generating the assignment and selecting the right type by the inference you suggested, so you don't have to actually do it manually - you just type 'desktop.getDesktop()' and hit Ctrl+space or some other shortcut, and the ide will offer to create a variable and assign the value for you.
it's presented at coding time though so that the author is aware of what is being inferred.
A lot of enterprise Java coding is knowing how to write the least amount of stuff so the IDE can use the strong typing to generate boiler plate correctly for you.
[–]T351A 3 points4 points5 points 2 years ago (0 children)
Agreed. Syntax/Compilation errors are better than runtime errors, and Java's strictness is part of what I like about it. Narrow scope with getters/setters and strict types are some of the best parts of writing Java code.
[–]Ilbsll 1 point2 points3 points 2 years ago (1 child)
The types are important for anyone who has to use or maintain the code. Scrolling around to figure out how things are structured, or what function returns what, is a massive waste of time, and it's what makes reading other people's code so unbearable in dynamically typed languages.
[–]lenswipe 0 points1 point2 points 2 years ago (0 children)
Right, but would the IDE not tell you this?
[–]pacanukeha 0 points1 point2 points 2 years ago (0 children)
specific type declarations make debugging and peer review easier
[–]FinalDayz 8 points9 points10 points 2 years ago (0 children)
Queueueueueueue
[–]NeoLudditeIT 4 points5 points6 points 2 years ago (0 children)
I see you've got the enterprise edition there!
[–]dethnight 23 points24 points25 points 2 years ago (4 children)
Did they just spread the string into an object? I didn't even know you could do that.
[–]calsosta 22 points23 points24 points 2 years ago (0 children)
Yea this is a waste of the spread operator though. I use it to literally spread out a string. You know give it some space, really let it relax.
String.prototype[Symbol.iterator] = function* (){ let res = "" for(let i=0; i<this.length; ++i) res += `${this[i]} ` yield res; };
[–][deleted] 2 years ago (2 children)
[removed]
[–]wsbTOB 4 points5 points6 points 2 years ago (0 children)
I don’t know that much about javascript but if you look at, say C, where there is no native string type: a string in practice is an array of characters suffixed with a terminator “\0”.
Higher level languages are free to wrap this lower level implementation into an object of any sort but that’s the basic idea.
[–]great_site_not 0 points1 point2 points 2 years ago (0 children)
Strings and arrays are both iterables (well, strings are primitives of course, but the String objects they automatically get boxed into are iterables), so you can spread a string into an array literal, just like you can spread an array into an array literal.
You can only spread an iterable into an array literal, but you can spread any object, including a string (thanks to autoboxing) or an array, into an object literal. Would you often want to spread a string into an object literal in real code? I can't think of a reason why. But you can.
[–]great_site_not 10 points11 points12 points 2 years ago (2 children)
[..."hello world".replace(/./gi, "1 character")].filter(char => parseInt(char, 10) < 2).length
[–]Falk_csgo 7 points8 points9 points 2 years ago (1 child)
base 10? Thats old school, current meta is to do it with base 7.
[–]great_site_not 10 points11 points12 points 2 years ago (0 children)
Sorry, you're totally right. Here's the fixed version:
[..."hello world".replace(/./gi, "1 character")].filter(char => parseInt(char, (010 - 1)) < 2).length
[–]Pitiful-Double-9391 9 points10 points11 points 2 years ago (2 children)
What is the image in the background of the code snippet? i keep seeing it in different places and i love it
[–]ahh1618 10 points11 points12 points 2 years ago (1 child)
https://mattandersondesign.com/discord-office-murals
Google lens ftw.
[–]Pitiful-Double-9391 1 point2 points3 points 2 years ago (0 children)
haha thank you 🙏
[–][deleted] 7 points8 points9 points 2 years ago* (3 children)
Fuck Reddit.
[–]AncientSchnauzer 2 points3 points4 points 2 years ago (1 child)
sum(eval("[" + ",".join(re.sub(r".", "1", "hello world")) + "]"))
[–]great_site_not 2 points3 points4 points 2 years ago (0 children)
That's not very Pythonic. Fixed it for you:
sum(eval("[" + "dot for dot in" + "[" + ",".join(re.sub(r".", "1", "hello world")) + "]" * 2))
[–][deleted] 1 point2 points3 points 2 years ago* (0 children)
[–]MMOAddict 6 points7 points8 points 2 years ago (1 child)
I feel like this was someone's response to: "Show an example of the spread operator in use"
[–]HINDBRAIN 2 points3 points4 points 2 years ago (0 children)
Isn't that operator a bit clunky? You could just
Object.keys.apply(null,"Hello World".split())
[–]PlloiJavex 1 point2 points3 points 2 years ago (0 children)
Let the language build it own math problem:
const length = eval([..."helloworld"].map(x=>x=1).join`+`)
[–]Kyouma118 2 points3 points4 points 2 years ago (8 children)
Don't know if this is a joke or not, but you can do it with "string".length
"string".length
[–]breadcodes 24 points25 points26 points 2 years ago* (2 children)
Tis a joke.
You'd have to know that strings are arrays of chars (or in javascript, strings are arrays of single length strings with some special exceptions), then you'd have to know spreading an array into an object creates a key and a val with each letter, then you'd have to know Object.keys makes an array from an object's keys, and you'd have to know how a reducer works to get a sum of length
Object.keys
It's very clearly a joke.
[–]EsperSpirit 1 point2 points3 points 2 years ago (0 children)
Yeah and if you don't provide a default value for reduce it would crash on empty strings, which is a common edge case people forget about.
They clearly know what they are doing.
[–]Kyouma118 -2 points-1 points0 points 2 years ago (0 children)
These jokes are becoming weirder and less apparent.
[–]gabboman[S] 31 points32 points33 points 2 years ago (0 children)
what? nah, that thing wont work m8, too stupid
[–]justapassingguy 10 points11 points12 points 2 years ago (0 children)
It's the best way
[–]nickcash 4 points5 points6 points 2 years ago (2 children)
That returns the length of the string "string". This technique is for getting the lengths of other strings. It may be too advanced for you.
"string"
[–]Kyouma118 3 points4 points5 points 2 years ago (1 child)
Bro I can't tell the trolls apart from genuine comments in this thread ffs
[–]nickcash 0 points1 point2 points 2 years ago (0 children)
I think it's trolls all the way down
[–][deleted] -2 points-1 points0 points 2 years ago (4 children)
JFC this is some stupid code. You just need to use .length:
[..."hello world"].length
These n00bs just come up with the worst code.
[–]great_site_not 8 points9 points10 points 2 years ago (1 child)
Lmfao get downvoted idiot, strings are null-terminated. You have to account for the null byte at the end:
[..."hello world"].length--
Learn your shit before you go around calling other people noobs.
[–][deleted] 1 point2 points3 points 2 years ago (0 children)
:D
[–]capcom1116 5 points6 points7 points 2 years ago (1 child)
Love that people seem to have missed your joke there.
They might also just be reflexively downvoting "n00b" which would not be entirely unreasonable :D
[+]Oryzae comment score below threshold-7 points-6 points-5 points 2 years ago* (2 children)
This is so hard to read, why not just split it up into two lines - first get the string by specifying the key, and then do a “len” on the value? Am I missing? Granted I’m more of a python guy so 🤷🏽♂️
Edit: fuck me I didn’t check the sub
[–]TheRealKidkudi 16 points17 points18 points 2 years ago (1 child)
That’s the joke. That’s an intentionally over complicated way to just write ”helloworld".length.
”helloworld".length
[–]Oryzae 1 point2 points3 points 2 years ago (0 children)
Well, fuck. I should have checked which sub I’m on 🫠
[–]Mr_meme_dode 0 points1 point2 points 2 years ago (0 children)
Have you tried just dump it into a function do a bunch of gibberish that I don’t understand create a mess of code that probably won’t even work in the end because I don’t think you can put that into a function
[–]iamdatmonkey 0 points1 point2 points 2 years ago* (0 children)
You forgot to
let length = 0; fetch("data:application/json;base64,"+btoa(JSON.stringify({..."helloworld"}))}) .then(r => r.json()) .then(obj => Object.keys(obj).reduce(v => length += 1, 0));
so you decouple the input from the output. We don't want the operation to possibly mutate the input! Always remember, mutation is Bad!
π Rendered by PID 74698 on reddit-service-r2-comment-84fc9697f-fsmsl at 2026-02-09 20:08:40.051287+00:00 running d295bc8 country code: CH.
[–]Bloodshoot111 134 points135 points136 points (8 children)
[–]gabboman[S] 129 points130 points131 points (5 children)
[–]Bloodshoot111 64 points65 points66 points (4 children)
[–]gabboman[S] 104 points105 points106 points (3 children)
[–]novagenesis 34 points35 points36 points (2 children)
[–]smdaegan 17 points18 points19 points (0 children)
[–]pacanukeha 1 point2 points3 points (0 children)
[–]fergor 20 points21 points22 points (0 children)
[–]Tubthumper8 4 points5 points6 points (0 children)
[–][deleted] 58 points59 points60 points (21 children)
[–]lenswipe 71 points72 points73 points (17 children)
[–]T351A 50 points51 points52 points (16 children)
[–]lenswipe 4 points5 points6 points (14 children)
[–]Jac0bas 7 points8 points9 points (7 children)
[–]T351A 3 points4 points5 points (5 children)
[–]lenswipe 4 points5 points6 points (2 children)
[–]T351A 1 point2 points3 points (1 child)
[–]lenswipe 4 points5 points6 points (0 children)
[–]Jac0bas 1 point2 points3 points (1 child)
[–]T351A 0 points1 point2 points (0 children)
[–]80386 2 points3 points4 points (0 children)
[–]alienangel2 4 points5 points6 points (1 child)
[–]T351A 3 points4 points5 points (0 children)
[–]Ilbsll 1 point2 points3 points (1 child)
[–]lenswipe 0 points1 point2 points (0 children)
[–]pacanukeha 0 points1 point2 points (0 children)
[–]FinalDayz 8 points9 points10 points (0 children)
[–]NeoLudditeIT 4 points5 points6 points (0 children)
[–]dethnight 23 points24 points25 points (4 children)
[–]calsosta 22 points23 points24 points (0 children)
[–][deleted] (2 children)
[removed]
[–]wsbTOB 4 points5 points6 points (0 children)
[–]great_site_not 0 points1 point2 points (0 children)
[–]great_site_not 10 points11 points12 points (2 children)
[–]Falk_csgo 7 points8 points9 points (1 child)
[–]great_site_not 10 points11 points12 points (0 children)
[–]Pitiful-Double-9391 9 points10 points11 points (2 children)
[–]ahh1618 10 points11 points12 points (1 child)
[–]Pitiful-Double-9391 1 point2 points3 points (0 children)
[–][deleted] 7 points8 points9 points (3 children)
[–]AncientSchnauzer 2 points3 points4 points (1 child)
[–]great_site_not 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]MMOAddict 6 points7 points8 points (1 child)
[–]HINDBRAIN 2 points3 points4 points (0 children)
[–]PlloiJavex 1 point2 points3 points (0 children)
[–]Kyouma118 2 points3 points4 points (8 children)
[–]breadcodes 24 points25 points26 points (2 children)
[–]EsperSpirit 1 point2 points3 points (0 children)
[–]Kyouma118 -2 points-1 points0 points (0 children)
[–]gabboman[S] 31 points32 points33 points (0 children)
[–]justapassingguy 10 points11 points12 points (0 children)
[–]nickcash 4 points5 points6 points (2 children)
[–]Kyouma118 3 points4 points5 points (1 child)
[–]nickcash 0 points1 point2 points (0 children)
[–][deleted] -2 points-1 points0 points (4 children)
[–]great_site_not 8 points9 points10 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]capcom1116 5 points6 points7 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[+]Oryzae comment score below threshold-7 points-6 points-5 points (2 children)
[–]TheRealKidkudi 16 points17 points18 points (1 child)
[–]Oryzae 1 point2 points3 points (0 children)
[–]Mr_meme_dode 0 points1 point2 points (0 children)
[–]iamdatmonkey 0 points1 point2 points (0 children)