r/ProgrammerHumor • • Dec 31 '14

How to add two numbers in JavaScript

1.7k Upvotes

270 comments sorted by

221

u/csorfab Dec 31 '14

I feel one of my favourite bash.org quotes is relevant here

<@joosa> how do you say float in java? just 1.5f?
<@Gliptic> FloatFactoryFactory.getInstance(FloatFactoryFactory.defaultInstanceDescriptionString).getFactory(Locale.getLocale("en-US")).createBuilder().setString("1.5").getResult()

45

u/hello_hawk Dec 31 '14

My favorite is SimpleBeanFactoryAwareAspectInstanceFactory. Classes with "Simple" in the name are like countries with "People's" or "Democratic" in their name - i.e. they're like, the polar opposite of simple.

14

u/cordoroy Dec 31 '14

something something 'you have been banned' something something

79

u/[deleted] Dec 31 '14

Fake. Class name isn't long enough.

Real one from Spring: AbstractSingletonProxyFactoryBean (source)

43

u/jtra Dec 31 '14

Still too short. Enjoy this 97 letter class named HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor

http://grepcode.com/file/repository.springsource.com/org.aspectj/com.springsource.org.aspectj.weaver/1.6.3/org/aspectj/weaver/patterns/HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor.java

I spotted that one while debugging some Spring AOP server-boot problems.

27

u/[deleted] Dec 31 '14 edited Mar 20 '18

45

u/peridox Dec 31 '14

In C, this would be called ififtpiftpmbwnf_state i know c doesn't have classes

32

u/RenaKunisaki Dec 31 '14

ififtpiftpmbwnf_st

ftfy

5

u/PBI325 Dec 31 '14

And of course it extends something equally ridiculous

State InternalFrameInternalFrameTitlePaneInternalFrameTitlePaneMaximizeButtonWindowNotFocusedState() {

6

u/colossus16 Dec 31 '14

You misread that. It extends State, the next line is the constructor.

3

u/PBI325 Dec 31 '14

Oh Jesus you're right haha

7

u/Tru3Gamer Dec 31 '14

8

u/peridox Dec 31 '14

now, someone write a script that uses gfycat names to refactor Java classes.

0

u/[deleted] Dec 31 '14

[deleted]

12

u/GaianNeuron Dec 31 '14

I never understood why people did that.

→ More replies (6)

5

u/[deleted] Dec 31 '14

Surprisingly the Reddit Enhancement Suite displays a webm anyway...

God bless it.

1

u/Tru3Gamer Jan 01 '15

I just looked for the first gfycat link, it was only for an example of the URL.

17

u/TheOnlyMrYeah Dec 31 '14

I read the Wikipedia article but I didn't get it: Why do people (especially Java programmers) use factories instead of constructors?

24

u/m00nnsplit Dec 31 '14

As far as I know, it allows you to decouple instantiation and execution. (so the execution class has no control, knowledge or any role in instanciation of classes).

There are two design patterns doing that, Factory Method which uses inheritance and Abstract Factory which uses composition.

8

u/the_omega99 Dec 31 '14

Here's an example: suppose we have code that needs to create a widget. It has to do the creation (perhaps it needs to generate objects on the fly). But we don't want to hardcode the object created because we might want to use this code to create different objects.

The factory pattern is the solution. We pass in a factor and the code uses the factory to create the objects it needs. The factory would implement some interface (or extend some class), ensuring that what is passed in a factory of the correct type and that it has a method that creates an object of the type we want (most likely a subclass of that type).

Granted, I find factories are overused oftentimes. As the above humorous example shows, they provide nothing but verbosity if you don't need the factory.

5

u/[deleted] Dec 31 '14

dependency injection, i believe

4

u/iopq Dec 31 '14

Because constructors don't let you return instances of other classes because they are special-cased in the language. Other languages like Smalltalk don't use this pattern because every class is a factory by default.

3

u/Jestar342 Jan 01 '15

For configuration purposes, mostly. The nuance is to be ignorant of the implementation of your dependency. Lets take a data accessor as an example. You have a method to get your model - do you really care where/how this data is kept? Or do you just care that your model is saved/retrieved?

var myModel = dataAccessor.getMyModel();

Right? So the dataAccessor could be a DB accessor, or a flat-file accessor, or a memory accessor etc. The current context really doesn't care. So the Factory that creates that instance is aware of the current system configuration without your implementation caring.

//ctor, or within method.. whichever is suitable.
public ThisClass(IDataAccessorFactory dataAccessorFactory)
{
    this.dataAccessor = dataAccessorFactory.createDataAccessor();
}

Now that example is weak - you'd just pass a reference to the accessor and not the factory in this example, but if you're lazy loading or some other implementation that's what this is for.

1

u/alkavan Dec 31 '14

The factory pattern is really useful when working with a DI container object. you configure factories via DI object and it saves a lot of code later.

But this has no relation to Java.

23

u/enigmamonkey Dec 31 '14

This reminds me of the Java based "FizzBuzz Enterprise Edition".

https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition

For example, do you need to implement scalable enterprise integer division? Just use this IntegerDivider class in the com.seriouscompany.business.java.fizzbuzz.packagenamingpackage.impl.math.arithmetics package:

package com.seriouscompany.business.java.fizzbuzz.packagenamingpackage.impl.math.arithmetics;

import com.seriouscompany.business.java.fizzbuzz.packagenamingpackage.impl.strategies.comparators.integercomparator.IntegerForEqualityComparator;
import com.seriouscompany.business.java.fizzbuzz.packagenamingpackage.impl.strategies.comparators.doublecomparator.FirstIsSmallerThanSecondDoubleComparator;
import com.seriouscompany.business.java.fizzbuzz.packagenamingpackage.impl.strategies.comparators.doublecomparator.FirstIsLargerThanSecondDoubleComparator;
import com.seriouscompany.business.java.fizzbuzz.packagenamingpackage.impl.strategies.converters.primitivetypesconverters.DoubleToIntConverter;
import com.seriouscompany.business.java.fizzbuzz.packagenamingpackage.impl.strategies.converters.primitivetypesconverters.IntToDoubleConverter;

public class IntegerDivider {
	
	public static final int INTEGER_DIVIDE_ZERO_VALUE = 0;
	public static final int INTEGER_ORIGIN_ZERO_VALUE = 0;
	
	public static int divide(int nFirstInteger, int nSecondInteger){
		boolean denominatorEqualsZero =
			IntegerForEqualityComparator.areTwoIntegersEqual(nSecondInteger, INTEGER_DIVIDE_ZERO_VALUE);
		if (denominatorEqualsZero) {
			throw new ArithmeticException("An attempt was made to divide by zero.");
		}else{
			final double dbFirstNumber = IntToDoubleConverter.Convert(nFirstInteger);
			final double dbSecondNumber = IntToDoubleConverter.Convert(nSecondInteger);
			final double dbQuotient = dbFirstNumber / dbSecondNumber;
			double dbRoundedQuotient = 0;
			if(FirstIsSmallerThanSecondDoubleComparator.FirstIsSmallerThanSecond(dbQuotient, INTEGER_ORIGIN_ZERO_VALUE)){
				dbRoundedQuotient = Math.ceil(dbQuotient);
			}else if(FirstIsLargerThanSecondDoubleComparator.FirstIsLargerThanSecond(dbQuotient, INTEGER_ORIGIN_ZERO_VALUE)){
				dbRoundedQuotient = Math.floor(dbQuotient);
			}
			final int nIntegerQuotient = DoubleToIntConverter.Convert(dbRoundedQuotient);
			return nIntegerQuotient;
		}
	}
}

15

u/gliptic Dec 31 '14

What, I don't see what's funny.

28

u/Cheesemacher Dec 31 '14

Found the Java programmer

9

u/citizen-rosebud Jan 01 '15

Actually you found the OP from the quote. Check the username! ;)

Source: long-ago lurker of that channel

1

u/Xenophyophore Jan 01 '15

At least does the monad thing!

Imagine if those were void methods!

296

u/EspyoPT Dec 31 '14

It's pretty funny how true this is. I remember one time, when I was just starting C++, and I searched on how to open a file given a path, except I wanted to know how I could do so from the program's local directory. The answer is easy: just don't include the absolute path (so like "/data/config.txt" instead of "C:/Users/Me/Program/data/config.txt").

The answers the internet gave me? Use Windows' API to know the current directory. Use a command line script to return the current path. Amongst other similarly-insane things!

As a general rule of thumb for all of you programmers out there interested in replying: If someone's asking a simple question, chances are they're just starting, and the answer for what they want is the simple one. Don't just assume "nah, they can't be asking for THAT, that's too basic!" It's never "too basic" when you're starting out. Remember your early days!

151

u/wtf_apostrophe Dec 31 '14

Using a relative path will get files relative to the working directory, which is not necessarily coincident with the application directory. Working out the application directory is surprisingly complicated and requires operating system specific code.

2

u/Wyboth Dec 31 '14

If the OP is a schoolkid, it is safe to assume that the working directory will be the same as the application directory.

1

u/RenaKunisaki Dec 31 '14
strncpy(path, argv[0], sizeof(path));
char *slash = strrchr(path, '/');
if(slash) slash[1] = '\0';
else strncpy(path, "./", sizeof(path));

? (we'll ignore the need to also check for \ on Windows)

4

u/wtf_apostrophe Dec 31 '14

argv[0] can't be assumed to have a full path, and defaulting to './' won't work either because the executable could be anywhere in the PATH. You can't actually rely on it containing anything useful at all because if the application is executed using the exec*() functions the caller can put anything it wants in argv[0].

On Linux the way to do it is to look at /proc/self/exe, which is a symlink to the current executable.

1

u/RenaKunisaki Dec 31 '14

Ahh, good to know.

You'd think that would be a standard C library function, but I guess on *nix you're not really expected to care about the executable's path anyway?

-5

u/lithedreamer Dec 31 '14 edited Jun 21 '23

worry encourage dirty wasteful sharp fly water complete squalid impossible -- mass edited with https://redact.dev/

26

u/sqew Dec 31 '14

OS X makes ~ the working directory

I don't think it does, unless you are running your programs from home.

If this is a problem, you can use chdir to change the working directory.

 chdir ("path/to/directory");

1

u/lithedreamer Dec 31 '14

Is there a way to write that into the code easily? I'd like something portable.

8

u/Sean1708 Dec 31 '14 edited Dec 31 '14

Tilde expansion is actually implemented by the language (I no longer think Bash was the first but I'm probably wrong), not the OS. Every language that I know of (that implements tilde expansion) makes ~ the home directory on both OS X and Linux, though usually not Windows AFAIA.

Edit: Tilde expansion comes from ADM-3A.

5

u/Fs0i Dec 31 '14

I think he meant that no matter what, OSX makes his home directory the working directory.

This behaviour is "bad" for him, because he can't simply open a file relative to the application directory (ehat is the usual working directory)

6

u/Sean1708 Dec 31 '14

Aaaahhhhhhh, that makes sense. That's definitely incorrect behaviour though.

5

u/ahruss Dec 31 '14

And it's definitely not how it works on OS X. I just tested it to be sure.

2

u/mallardtheduck Dec 31 '14

That behaviour is not just "bad", but completely broken. The CLI would be rendered completely useless for a start (since the "cd" command would do nothing). Clearly that is not how OS X functions.

1

u/[deleted] Dec 31 '14

I think they're talking about the default value, like when you launch an application stored in /Applications or wherever osx stores them, $PWD gets set to ~ rather than /Applications/Your.app/Resources or whatever might be the logical place, wherever the binary file is.

In windows, if you launch something from a shortcut in your start menu, that program sees the current directory is C:\program files\application\ and if you use a file path ".\foo" it'll expand to "c:\program files\application\foo"

Of course you can still change directories, but by default when the program is first launched, $PWD is set to ~ rather than the directory the program lives in.

2

u/mallardtheduck Dec 31 '14

In windows, if you launch something from a shortcut in your start menu, that program sees the current directory is C:\program files\application\ and if you use a file path ".\foo" it'll expand to "c:\program files\application\foo"

Actually, for Windows Start Menu items, the working directory is set in the shortcut file (.lnk), so can be anything. Although your example is the most common case.

2

u/peridox Dec 31 '14 edited Jan 08 '15

it comes from Lear Siegler's ADM-3A terminal which had the tilde on the same key as the 'home' key.

here's a picture of the ADM-3A's keyboard layout

1

u/autowikibot Dec 31 '14

ADM-:


See https://en.wikipedia.org/w/api.php for API usage


Interesting: ^ADM-144 | ADM-141 ^TALD | ADM ^formalism | Vice ^admiral | Al ^Adm

Parent commenter can toggle ^NSFW or ^delete. Will also delete on comment score of -1 or less. | FAQs | ^Mods | Magic ^Words

3

u/peridox Dec 31 '14

it doesn't; os x is posix-compliant. ~ is the $HOME directory

1

u/lithedreamer Dec 31 '14

Then why do my i/o files need to be in the home directory for me to compile with g++?

0

u/[deleted] Dec 31 '14

[deleted]

26

u/Deranged40 Dec 31 '14

Ah, well if he's in school, don't bother teaching him the right way to do it. That's not at all what school is for.

36

u/cfunkrun Dec 31 '14

Learning everything the "right way" would take too long and be too overwhelming for most people. School is meant to build the knowledge and foundations. In this case I think it would be appropriate for a student to do the quick and dirty way. Nobody has the time or money to spend 5+ years in school on that stuff.

13

u/dexter30 Dec 31 '14

I'm starting to think programming is a lot like philosophy.

There is no right way. Just the set up to get there.

13

u/__constructor Dec 31 '14

That's exactly what it is.

A good programmer isn't an encyclopedia of programming quirks and API use-cases, they're a seasoned problem solver that can think in applicable paradigms.

2

u/[deleted] Jan 02 '15

A lot of things are like that to be frank.

7

u/Deranged40 Dec 31 '14 edited Dec 31 '14

Yeah, but when you interview some dude who's fresh out of school and you ask the question "What's your preferred source control solution" and you see the blank stare on the guy's face... it's saddening.

See, that's a trick question. The trick is that ANY answer is the right answer. I personally hate SVN, but I've used it before, and if you prefer it, we'll have no problem getting you to switch to what we use. I can teach you the one we use so much more easily as long as you're already familiar with the basic concepts. Why use one? What can you use it for? Things like that.

Imo, programming 101 needs to introduce a version control system as soon as the class is done going over the syllabus on day one.

But, if school takes too long to teach people how to be good developers, then why are we still pressuring people to go to school? I honestly prefer interviewing people who haven't been to school. These people often have the passion to program rather than the desire to pay off student loans. And on that topic, everyone has the time and money to spend 5+ years in school as long as those checks keep coming in.

8

u/RitzBitzN Dec 31 '14

The point of university isn't to great developers, is it? I always thought it was to great engineers with a good understanding of theory in computer science and enhancing critical thinking skills.

6

u/Deranged40 Dec 31 '14

I hope that the students in school understand this, but I fear that all too many of them don't. I know of 3 or 4 people who are going to school to be a programmer based on the income posted on a popular job opening posted around here.

The number one problem with schools right now is that they all advertise "come here to be successful in life and make more money". I've heard it all my life. "If you don't have a degree you won't make as much as people with a degree". Sure, if those people manage to find a job. 85% of graduates last year didn't find a job in their field. School is not the place to learn programming. It's entirely too expensive.

→ More replies (2)

1

u/[deleted] Jan 01 '15

Depends what you went to school for. Sure, coming out with a good understanding of comp sci theory makes a lot of sense if you actually studied comp sci. Other people, e.g. software engineering grads really should be good developers.

4

u/cfunkrun Dec 31 '14

I think you're over simplifying and generalizing. Not everybody who's passionate about programming can afford to spend that much time and money in school. And that doesn't mean that someone is better off not going to school just because they're passionate about it. They could still end up being a really bad programmer.

I do agree that version control should be at least mentioned and explained to some extent, but you can end up creating a whole class on version control methods and practices alone.

But version control is very easy to pick up and understand, so when you're introduced to it in the work environment, it's a quick and easy thing to train for if you've never encountered it before.

One important thing that most new graduates have is the willingness to learn and understand, and to use the knowledge they have, even if it's not comprehensive. All they need is a chance to apply the skills and knowledge.

→ More replies (5)
→ More replies (4)

2

u/[deleted] Jan 01 '15

I really think everyone who just wants something quick and dirty because it's only for school gives up all right to complain about comp sci/software engineering/game development/etc etc education.

If you won't stick around long enough for a kind stranger to teach you how the os' API works on absolute paths it's not the school's fault for failing to prepare you for real life.

1

u/[deleted] Dec 31 '14

That's not necessarily true. There's plenty you learn in school that's applicable on the job. But through experience Nd osmosis, you do tend to learn better methods.

1

u/[deleted] Jan 01 '15

The experience and osmosis don't happen unless you apply yourself to begin with. It's why really enthusiastic developers end up doing better than really smart ones that are just phoning it in.

Don't get into the habit of doing bare minimums.

→ More replies (10)

16

u/ZionTheKing Dec 31 '14 edited Dec 31 '14

"Hey how do I print this into console?"

Have you heard of Boost you should definetely use Boost tell me when you got Boost

Boost is really good have you gotten Boost yet if you don't you should get it because Boost does all the things ok

7

u/invadrzim Dec 31 '14

And If it wasn't windows api it was boost. Boost fucking everywhere.

33

u/ocbaker Dec 31 '14

I think the jokes were pretty funny but the correct answer shouldn't have been downvoted. Really sucks seeing that happen to genuine answers on Stack Overflow. At least it is quite rare.

17

u/isaaclw Dec 31 '14

Yeah. I hope the image was doctored for the joke

27

u/nebffa Dec 31 '14

If you look on the right-hand side it's quite clearly a fake. "Where are my legs?"

3

u/dexter30 Dec 31 '14

Check your human biology books.

-2

u/Drew0054 Dec 31 '14

lol, SO is a disgrace. I have never experienced "experts" so uppity. I would never post there out of fear of getting flamed. Who would think there might be novices at an advice forum?

1

u/ocbaker Dec 31 '14

Well if you think SO is so bad perhaps you could grace us with some knowledge of more friendly places for newbies to ask questions.

It can always be trying to be a new person in a field asking the "dumb" questions, if you know a place that is more friendly to that on the internet I think everyone would like to hear about it, especially those who are just starting.

→ More replies (2)

5

u/jonatcer Dec 31 '14

It's a valid point as another user pointed out... Just because something works in a specific circumstance, doesn't mean you should use it. That's how bugs pop up that go unnoticed for ages.

Plus if you're new, you really don't want to pick up bad habits that you'll have to unlearn later.

13

u/Asmor Dec 31 '14

just don't include the absolute path (so like "/data/config.txt" instead of "C:/Users/Me/Program/data/config.txt")

/data/config.txt is an absolute path. A path starting with a slash is absolute; / is the root. data/config.txt would be a relative path.

Also, windows uses \ for directory separators, not /.

6

u/[deleted] Dec 31 '14

Also, windows uses \ for directory separators, not /.

Windows APIs (including all sane C runtime implementations) should accept either, though I think backslashes are required for UNC paths. The convention of using backslashes originates from the MS-DOS command line, where forward slashes were ambiguous with command options.

That said, because of legacy and convention, lots of Windows applications have buggy path handling code that only works when backslashes are used. Assuming that Windows only uses backslashes just perpetuates that problem.

2

u/Asmor Dec 31 '14

Everything in Windows displays directories with paths separates by backslash. Backslashes always works in anything made for Windows.

It seems to me that things that allow regular slashes, while not harmful and in fact convenient, are the exceptions; backslashes are the rule.

2

u/the_omega99 Dec 31 '14

In fact, forward slashes seem ideal in most situations. A relative path using forward slashes can work on any major OS (on Linux, a backslash is perfectly valid in a file name and thus cannot be a path separator).

Also, some languages seem to prefer forward slashes. It's the preferred cross-platform path separator in Java (no need to use File.pathSeparator -- it's for display purposes). At the very least, forward slashes are cleaner because you don't have to escape them in strings. IMO, foo/bar/baz.txt is more readable than foo\\bar\\baz.txt.

In fact, I've yet to encounter a programming language that can't handle forward slashes on Windows.

6

u/acoard Dec 31 '14

As a general rule of thumb for all of you programmers out there interested in replying: If someone's asking a simple question, chances are they're just starting, and the answer for what they want is the simple one. Don't just assume "nah, they can't be asking for THAT, that's too basic!" It's never "too basic" when you're starting out. Remember your early days!

I agree wholeheartedly, the audience is just as important as the message.

...That being said, StackOverflow's philosophy seems to be about creating good answers and having the "right" answer to them. It's not so much about answering questions when people are stuck, but creating a resource of good questions and right answers that people can use when they're stuck. I'm not an advocate of this philosophy, but it is entirely valid and reasonable. I think there's room for both tailoring your answer to the particular questioner's skill set, while also saying "and this is the 'real' answer once you've gotten there."

1

u/[deleted] Jan 02 '15

Stack Overflow's audience is really everyone who clicks the top result on google.

1

u/b10011 Dec 31 '14

~/path/to/application

-> Application reads relative path "files/test.txt"

-> Complete path is now "~/files/test.txt" instead of "~/path/to/application/files/test.txt"

1

u/slrqm Jan 01 '15 edited Aug 22 '16

That's terrible!

0

u/[deleted] Dec 31 '14

[deleted]

11

u/Genmutant Dec 31 '14

jquery is JavaScript, but yes.

8

u/RenaKunisaki Dec 31 '14

Java is to Javascript as ham is to hammer.

123

u/punking_funk Dec 31 '14

-1 not enough jQuery

91

u/[deleted] Dec 31 '14

$.upvote()

17

u/Hipolipolopigus Dec 31 '14
$('.id-t1_cna7xif > .unvoted > .arrow.up').click()

27

u/[deleted] Dec 31 '14

I wrote this sweet jQuery plugin that adds your numbers and returns an animated GIF of a cat farting.

16

u/[deleted] Dec 31 '14

animated GIF of a cat farting

n00b.

If you were truly a web developer in 2014, you'd be doing that in CSS3!

16

u/RenaKunisaki Dec 31 '14

Definitely convert all your vector graphics to pure CSS. SVG is soooo last year.

5

u/[deleted] Dec 31 '14

.gifv son

2

u/OmegaVesko Dec 31 '14

.gifv isn't an actual file format though.

4

u/[deleted] Jan 01 '15

That's how fresh it is.

4

u/mrivorey Dec 31 '14

Needs more cowbell jQuery.

3

u/nemec Dec 31 '14

+1 sufficient static gif

2

u/ArcTimes Dec 31 '14

you suck

52

u/KLDzzz Dec 31 '14

Related: Where are my legs?

LOL

13

u/Scorpius289 Dec 31 '14

Must be an FPS character.

17

u/[deleted] Dec 31 '14

How can I use JavaScript to parse some HTML using regex

ಠ_ಠ

7

u/shvelo Dec 31 '14

$(1).add(2).result()

21

u/jonatcer Dec 31 '14 edited Dec 31 '14

Doesn't Javascript concat stuff with a +? I get the joke, but what would happen if you tried "3"+2? I can't check now (phone), but my recent trip into js land has shown me all the weird idiosyncrasies it has.

That said, those types of users need to be docked some points so they can't fuck anything up... Stackoverflow is a really useful site and I hate seeing assholes like this ruin it.

God I'm a dumbass... Yeah, fake image - didn't read the usernames, sidebar, etc.. tl;dr whoosh

32

u/Delfaras Dec 31 '14

Yes, yes it does. "3"+2 = "32"

Edit: and the term you're looking for is "cast".

14

u/Lystrodom Dec 31 '14

For real fun do 2+"3"

36

u/nemec Dec 31 '14

[] + []

""

[] + {}

"[object Object]"

{} + []

0

{} + {}

NaN

https://www.destroyallsoftware.com/talks/wat

22

u/jtra Dec 31 '14

My favorite gotcha:

["10","10","10","10"].map(parseInt)
=> [ 10, NaN, 2, 3 ]

15

u/chimyx Dec 31 '14

Ok, please explain.

19

u/ultrafez Dec 31 '14

This happens because the parseInt function takes 2 parameters - the first is the string to parse, and the second is the base to interpret the number as (usually 10).

When the map function calls your specified function on every element of the array, it passes 3 parameters to the callback: the value, the index of the item in the array, and the array itself. So "map" ends up calling parseInt with the following parameters:

parseInt("10", 0) => 10
parseInt("10", 1) => NaN
parseInt("10", 2) => 2
parseInt("10", 3) => 3

4

u/YRYGAV Dec 31 '14

parseInt("10", 0) => 10

Am I missing something here? Why isn't this an error or NaN like the base 1 call?

0

u/[deleted] Dec 31 '14

[deleted]

3

u/the_omega99 Dec 31 '14

With JS, you can have default variables by simply checking if the variable is unset and setting it to an appropriate default if so (and presumably that appropriate default is any "falsey" value).

Eg,

function foo(x) {
    if(x === undefined) x = "default";
    console.log(x);
}

foo() // prints "default"
foo(5) // prints "5"

A little different from how other languages handle default variables, but really quite useful. If you have a callback that supplies arguments but you don't need them, you can exclude them entirely, making your code more readable (most statically typed languages will complain here).

→ More replies (0)

9

u/[deleted] Dec 31 '14
> parseInt(1/0)
NaN
> parseInt(1/0, 19)
18

js> parseInt(1/0, 23) 
18
js> parseInt(1/0, 24) 
151176378

Ready for the big reveal? 1/0 returns the string "Infinity" and the second argument is the base to parse it in. It maxes out at 36—at 37 it can read the whole "Infinity" and once again returns NaN.

3

u/sammypip Dec 31 '14

Small technicality: 1/0 returns the special float value Infinity, not a string.

1

u/[deleted] Dec 31 '14

Oh ok, guess javascript isn't as stringly typed as I thought. (I already know js has two data types: strings and floats)

5

u/the_omega99 Dec 31 '14

If you're interested, the types of JS are:

  • Boolean

  • Number (floating point)

  • String (using either UCS-2 or UTF-16)

  • Array (which can have any other type -- arrays don't need a uniform type). They're considered objects by typeof.

  • Objects (which can have any other type nested)

  • Functions (JS is a functional language)

Objects can be constructed on the fly. It's common to use objects as a means of grouping properties. For example, a JQuery AJAX call might look like

$.ajax({
    url: 'some/url',
    type: 'GET',
    beforeSend: function() {
        $('#spinner').show();
    },
    complete: function() {
        $('#spinner').hide();
    }
});

The object is the parameter of the ajax() function, enclosed by curly braces. url, type, beforeSend, and complete are fields of the object storing values of type string, string, function, and function, respectfully. If you've seen JSON before, then JS objects should look very familiar (after all, JSON stands for JavaScript Object Notation). It's not entirely the same because JS objects can store functions.

There's also the special types null and undefined (a variable that hasn't been assigned a value yet is given the value undefined).

2

u/Hydrothermal Dec 31 '14
["10","10","10","10"].map(function(i) {
    return parseInt(i, 10);
});

=> [10, 10, 10, 10]

:)

3

u/[deleted] Dec 31 '14

or even "just"

js> [10,10,10,10].map(function(i) { return parseInt(i) })
[10, 10, 10, 10]

Though I think for a lot of us, having map(f) and map(lambda x: f(x)) do different things is pretty scary.

2

u/Hydrothermal Dec 31 '14

Dropping the radix argument to parseInt works until your number starts with a 0. Then you end up with this.

2

u/mvaneerde Dec 31 '14

Where did the 08 come from? Are you parsing a date manually?

→ More replies (2)
→ More replies (1)

3

u/Daniel15 Dec 31 '14
['10', '10', '10', '10'].map(i => parseInt(i, 10)) 

Once you go ES6 and start using arrow function syntax, you never go back :p

6

u/Delfaras Dec 31 '14

You might want to have a look at this stackoverflow question : What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?

Although it explains why it behaves like this, we can all agree that this is a terrible behavior.

2

u/nj47 Dec 31 '14

Which part, specifically, is terrible behavior, and how should it "properly" work?

2

u/[deleted] Jan 01 '15

"Properly" work should be "compile-time error" like almost every statically typed language or "throw exception" like most sane dynamically typed languages.

2

u/the_omega99 Dec 31 '14

I'd argue that all the examples given there are not necessarily "terrible behavior" because they all show the programmer doing some seriously WTF stuff. Most statically typed languages would just fail to compile for such kinds of situations.

I suppose it's debatable as to whether JS should do whatever it does in this case as opposed to failing hard (personally, I think JS should fail with error messages in these cases, since they're likely the sign of bugs), but it's not a big deal (since you wouldn't typically encounter these situations and they should be easy to detect).

I would agree that the automatic type conversion can be inconsistent (eg, "5" + 1 == "51" and "5" - 1 == 4), but it rather makes sense when we consider that JS was made for web browsers, where user input is usually a string (and the issue can be avoided if we're sure to explicitly convert before attempting to use a string as a number or vice versa).

2

u/songbirdy Dec 31 '14

Array(16)

,,,,,,,,,,,,,,,,

when he says it's "an array of 16 commas" isn't this actually just an empty array and it prints out the commas as separators for each element in the array but since they are empty it just seems like an "array of commas"?

edit: nevermind i paused the video too early...i guess what i assumed was acceptable until you see how javascript prints out arrays after you actually put stuff in it...

3

u/chimyx Dec 31 '14

It should be more like 15 commas.

1

u/songbirdy Dec 31 '14

i think in the video it was actually 15 commas i just miscounted when i was typing it out

1

u/fredspipa Dec 31 '14

That was pure gold.

1

u/HomemadeBananas Dec 31 '14

Is there any explanation for this?

1

u/[deleted] Jan 03 '15

typeof(NaN)

>"number"

1

u/Lampjaw Dec 31 '14

Whenever I think I'm beginning to understand javascript all I have to do is look at a reddit thread to put me back in my place.

→ More replies (1)

2

u/HomemadeBananas Dec 31 '14
> 2+"3"
"23"

What would you expect?

1

u/Lystrodom Dec 31 '14

Shoot, you're right. I was thinking of 2+(+"3") (Or even just +"3")

1

u/[deleted] Jan 01 '15
2 + "3" - "3"

1

u/HomemadeBananas Jan 01 '15 edited Jan 01 '15

I guess it makes sense, because even though the addition casts to a string, you can't "subtract" a string the same way. I guessed correctly what the answer would be.

5

u/jonatcer Dec 31 '14

Thought so...

Edit: and the term you're looking for is "cast".

Actually I meant concat, but yes cast is fairly accurate too :).

4

u/Sean1708 Dec 31 '14

I suppose it casts then concats. I would argue it isn't the concatenation that is the issue but the completely fucked up casting rules that JS has.

2

u/[deleted] Dec 31 '14 edited Dec 31 '14

Well, it makes sense when you think about it. You start with "3", a string. You can't add 2 to "3", but int has an implicit cast to string. So 2 gets cast to "2" and we're left with "3"+"2" = "32".

0

u/Reelix Dec 31 '14

console.log(0.3*3);

Have fun.

2

u/YRYGAV Dec 31 '14 edited Dec 31 '14

That's just floating point funniness, it doesn't have anything to do with JavaScript. All programming languages will exhibit similar 'incredibly close but not quite correct' issues with floating point math that have to be properly accounted for whenever you are using floating point numbers to print to the user (rounding) or to compare to other numbers where precision is important (compare for a 'very close but doesn't have to be exact' number, not exact).

For an explanation why, it's because computers aren't doing the same type of math we are. It's doing it in binary, and it also doesn't try to group stuff together, it just does addition/subtraction/etc. on the number's it's given. It won't look at (1/3) + (1/3) and add the numerators together, it will try to add .33... + 0.33...

An analogy would be lets say we want to add (1/3) + (1/3) + (1/3) together in base 10 the same way a computer would work through it. The problem essentially becomes 0.333... + 0.333... + 0.333..., and the answer we get is 0.999... not 1 Now you might argue 'hey! but the original 0.3 given in the JS example wasn't an infinitely repeating decimal! this analogy doesn't apply!' But the thing is, whether something is infinitely repeating or not depends on the base of the number, sure 0.3 fits nicely into base 10, it's a multiple of 1/10. But since it's not a multiple of 1/2, it will actually be infinitely repeating once converted into base 2, and the computer will run into the exact same issue we got with adding 0.33.

If you had tried to add the (1/3) + (1/3) + (1/3) in base 3 instead of base 10 though, it would be much simpler. (1/3) is actually 0.1 in base 3, so it's not infinitely repeating and we get a nice, correct 1 as the answer when adding them together. Hopefully this helps illustrate how changing the base you are working in suddenly can make math easier or harder, even though it's the same numbers, and 0.3*3 looks so easy in base 10.

1

u/Reelix Jan 01 '15

So, instead of rounding up, it rounds down to 0.89' ?

1

u/YRYGAV Jan 01 '15 edited Jan 01 '15

It's not rounding when it's adding.

Lets go back to the (1/3) in base 10 example, as infinitely repeating binary decimals are harder to understand.

It does 1/3 first, which gives us 0.33... The computer isn't actually keeping in memory the concept of 'one third' or the fact it's infinitely repeating. It's just storing as precise a number as it can, which would be like 0.33333333333333333333333333 or something, which is correct in that it's the most precise way it can remember it. Then when we add it to itself 3 times, it adds them together and gets 0.999999999999999999999 which is also correct, in that if you take a bunch of 3 + 3 + 3 you get 9, it's not going to start automatically rounding the answer for you, and addition is an exact math with no rounding involved.

And that's more or less what is happening, in order to avoid it, it would take a lot of overhead on all calculations, as it would have to try and parse and interpret the statement as a whole, and change operations based on surrounding operations, rather than just doing each operation one by one and giving you a quick answer. Not to mention, for most real applications this isn't an issue. Either you wanted to round to a specific spot to display it to a user anyways most of the time (what if it was 1/7 * 3 instead of 0.3 * 3? Can you predict the answer will always be finite decimal places?) or you don't particularly care if it's off by a small amount (like the X position of an object in a game, it doesn't have to be so exact).

So because of that, nearly every programming language just has an implied rule that you never assume floating point math is exact, and is instead just really, really, really accurate. You'll also find a lot of financial databases will instead store money as integer amounts of cents rather than floating point amounts of dollars to avoid all this stuff.

1

u/nj47 Dec 31 '14

Floating point arithmetic is hard in all programming languages

0

u/UnspeakableEvil Dec 31 '14

Also:

console.log(0.3*3 === 0.9);

2

u/TwilightTwinkie Dec 31 '14

This is just floating math. Every programming language that I know of has this issue.

2

u/iopq Dec 31 '14

Languages with rational numbers do this correctly. Smalltalk would tell you 9/10.

1

u/UnspeakableEvil Dec 31 '14 edited Dec 31 '14

I know, as I expect so does /u/Reelix. Point is that, as with the concatenation or addition example, it gives an answer which differs from what you might intuitively expect to get.

7

u/mr_silverstrike Dec 31 '14

It does if "2" was input by a user and not cast to a Number (so basically if it's kept as a string).

"2"+3 
= "23"

What you'd want to do is:

2+3 
= 5

To get that to work, you'd do:

Number("2") + 3
= 5

You can try this out in your browser's console.

2

u/jonatcer Dec 31 '14

So what you're saying is that suggesting jQuery is a valid answer? Also couldn't you use something like "2".toInt?

8

u/Delfaras Dec 31 '14

Jquery is absolutely not a valid answer for this. To cast a string into a number, you can do

parseInt("2", 10)

you have to specify the radix ...

Number("2")

Or

+"2"

Pick the one you prefer :p

2

u/mr_silverstrike Dec 31 '14

I was saying your initial comment's assumption was correct. e.g. "6"+3 gets appended to "63".

About jQuery: it isn't lightweight. You don't need jQuery for these basic things.

Like /u/Delfaras explained, there's a variety of ways to convert a string with a number in it to a number (casting); if your number uses the decimal system, using the Number() function is the easiest way to do this.

The parseInt(string, radix) function works without supplying the radix, but the official docs1 state:

Different implementations produce different results when a radix is not specified.

I like my code nice and clean and parseInt() is perhaps overkill if I can just use Number().

1: Mozilla Developer documentation on parseInt()

1

u/mvaneerde Dec 31 '14

Other options are the idiomatic 0 + v and 1 * v

2

u/TwilightTwinkie Dec 31 '14

Javascript is not a type safe language. It leave that to the programmer, which is hard sometimes as you need to be aware of what types different variables are at all times.

There are usually three places that values come from in JavaScript:

  1. The User

  2. An API

  3. Your own code.

All user input should be sanitized, if you want it to be a number convert it to a number first. API data is hopefully to a spec and you know what is coming back to you. With your own code you just need to keep track of it.

Microsoft created a superset to JavaScript called TypeScript which helps you detect these problems before you run your code.

http://www.typescriptlang.org/

1

u/Reelix Dec 31 '14

console.log(0.3*3);

:P

7

u/Cley_Faye Dec 31 '14

"3"+2 is +(<string>,<number>), converting 2 to "2" and resulting in "32".
Javascript is not as typeless as people like to say :)

parseInt("3")+2 is +(<number>,<number>) and does return 5.

You can then do (parseInt("3")+2).toString()+0 to get "50" for example, but that's silly and I don't know why I mention it.

Once I have access to the documentation, I'll try getting the correct jQuery answer, but don't hold your breath I'm not very fluent in it.

2

u/Hydrothermal Dec 31 '14

Very important: make sure to specify the second argument to parseInt, which is the radix - i.e. parseInt("3", 10), not parseInt("3"). Leaving it undefined will have JS guess the radix, which will result in some tricky problems down the road.

1

u/Cley_Faye Dec 31 '14

Damn, your comment gave me hope that parseInt("010") would give something weird to unsuspecting students, but apparently parsing octal this way is deprecated (and is interpreted as decimal at least in chrome).

Oh well at leat I've learned how to make fixed font stuff in reddit from your comment :)

5

u/steak21 Dec 31 '14

kind of relevant. i'll take any reason to post this for those who haven't seen it:

wat

4

u/isaaclw Dec 31 '14

For what it's worth, the picture was faked for the joke. Still hilarious.

1

u/jonatcer Dec 31 '14

For what it's worth, the picture was faked for the joke. Still hilarious.

Was it?

How the hell did I miss that... Yeah, I'm gonna have to blame that one on browsing reddit on my phone.

3

u/isaaclw Dec 31 '14

If you scroll down, you'll notice someone had to tell me too ;)

8

u/Templer_90 Dec 31 '14
//Todo: Debugging; More Jquery; More todos
$('div.comment').find("div.unvoted").each(function(){
    $(this).click();
});

11

u/[deleted] Dec 31 '14

doesn't $('div.comment div.unvoted').click() work? out of curiosity

8

u/[deleted] Dec 31 '14

Yes it does. That's some bad jQuery.

4

u/[deleted] Dec 31 '14

Not bloated enough (but yes it works)

4

u/Hydrothermal Dec 31 '14

Bloated, you say?

$(document.body).data("div-tagname", "div");
$(document.body).data("method-each", "each");
$(document.body).data("method-get", "get");
$(document.body).data("method-trigger", "trigger");

$($("body").data("div-tagname"), document.body).find('.comment')[$("body").data('method-each')](function() {
    $(this).find($("body").data('div-tagname')).find(".unvoted")[$('body').data("method-each")](function() {
        $($('#' + this.id + "." + this.className.split(" ").join("."))[$("body").data('method-get')](0))[$("body").data('method-trigger')]('click');
    });
});

1

u/Templer_90 Jan 01 '15

It does. I thought with "find" it is more funny.

But \u\Hydrothermal 's version is better

1

u/shitwhore Jan 19 '15

Haha man you just destroyed all my hard work on an assignment! I know it should've been obvious but I was using .each() for other stuff so I never stopped to think about it until now!

from:

$('article').each(function(){
		$(this).one("click",showGeo); 	
		});

too

$('article').one("click",showGeo);        

4

u/blenman Dec 31 '14

This is funny and depressing because I feel like the guy at the bottom with a Computer Science degree (not that this is necessary for something so simple), but without knowing enough jQuery, Node.js, and other fancy tools, I can't seem to get a normal programming job... womp womp.

8

u/jonno11 Dec 31 '14

Well to be fair, if you don't know anything about the technologies a possible employer might be looking for, why would they employ you?

I find the backward assumption of knowledge interesting. I remember at A-Level, I was excused from the mandatory MS Excel/Word training etc. because I took Computer Science; it was assumed I'd already "know all there is to know".

I code everyday now, but I still haven't a fucking clue how to use Excel/Word. It baffles me.

2

u/blink_and_youre_dead Dec 31 '14

yeah, jQuery is definitely the way to go

-fishnipples

2

u/Bounty1Berry Jan 01 '15

JavaScript is one of the very few languages where 5+3 can equal 53, depending on how it decides to typecast the data.

It's to the point where I rarely use "+" for adding, always doing something like a - (-1*b) to ensure it does what I expect.

PHP may make a bunch of other stupid decisions, but having a distinct "concatenate" and "add" makes a lot of sense if the language isn't strongly typed enough to avoid ambiguity.

2

u/jxm262 Dec 31 '14

Is this still on SO? Would love to see if it's received any additional comments. I'm assuming it's been removed by the mods since I can't find the original

10

u/cyanuricmoon Dec 31 '14

It's obviously a fake image.... and I mean obviously.

5

u/jxm262 Dec 31 '14

sigh... you're right i didn't read the entire image :)

1

u/[deleted] Jan 01 '15

Real SO posts always have a "topic has been closed" box at the top. It's like their seal of authenticity.

1

u/[deleted] Jan 01 '15

1337h4x0r

1

u/[deleted] Jan 01 '15

Also a related question, what is the best number?

2

u/blah_guy Jan 03 '15

73 is the best number. In binary it is a palindrome: 1001001. 73 is the 21st prime number. Its mirror, 37, is the 12th prime number, and 12's mirror, 21, is the product of 7 times 3.

1

u/PHProfessional Jan 02 '15 edited Jan 05 '15

Most likely downvoted because his syntax is all wrong. Not a single '$' symbol for his variables.

1

u/IskaneOnReddit Dec 31 '14

I love it how the last answer was downvoted.

0

u/[deleted] Dec 31 '14

[deleted]

-1

u/boxxa Dec 31 '14

Javascript sucks with numbers.

3

u/[deleted] Dec 31 '14

Javascript sucks

FTFY

-2

u/boxxa Dec 31 '14

Javascript doesn't suck. Javascript programmers suck.

3

u/[deleted] Dec 31 '14

No, it sucks. This is a fact.

→ More replies (1)

1

u/brotherwayne Dec 31 '14

Nah. Floating point math is a problem in many languages. In JS you shouldn't do floating point without a library though.

It sucks slightly more than most, I'll admit that.

-3

u/Glenn1990 Dec 31 '14

Jokes aside.

This is why non-programmers think programmers are cunts.

Just saying.

0

u/[deleted] Dec 31 '14

Something something repost

-14

u/[deleted] Dec 31 '14

Fuck stackoverflow for this kind of bullcrap.

Ask any js question and they're like "LOL JQUERY FAGGOT"

9

u/ocbaker Dec 31 '14

Not at all and if you truly believe that they are that bad then contribute. The reason why Stack Overflow is so great is because people from the community contribute.

It is a shame they didn't take this question seriously but I've seen some users break the limit of posting in a day with all simple questions and they all got answered reasonably.

6

u/[deleted] Dec 31 '14 edited Dec 31 '14

It is a shame they didn't take this question seriously

This isn't a real question, the image is a joke. Look at the first answerer's name, or bobince's point count, or really just anything, it's a really obvious fake.

2

u/lithedreamer Dec 31 '14

It's often great for finding answers but I've sworn off asking there. I was a newbie asking a non-technical question. When I checked on it next, a random person had edited my post and someone else closed it for being too vague.

→ More replies (7)
→ More replies (4)