r/programming • u/dreasgrech • Apr 22 '10
Add a number to another number in JavaScript [img]
167
u/aristotle2600 Apr 22 '10
I've got a FEVER! And the only PRESCRIPTION, is more jQUERY!
25
u/OpenSourceFuture Apr 22 '10
Yeah there are not many songs that feature jQuery.
226
u/antimetric Apr 22 '10
There are a few though; http://en.wikipedia.org/wiki/Jake_Weary
35
u/thisusernametakentoo Apr 22 '10
Well done
13
u/antimetric Apr 22 '10 edited Apr 22 '10
Thanks :)
Edit: The freakiest thing is though, I'm English and to the best of my recollection, I've never fucking heard of him.
6
u/freeall Apr 22 '10
How did you find his name, then? Or did you just guess that someone was called that and searched? Nice find, though :)
14
u/antimetric Apr 22 '10
Yes. Tried google suggests; Jay K.. Jay Q... nothing interesting, Jake Wea.. ah!
→ More replies (1)5
2
9
29
27
u/sitruss Apr 22 '10
"Its really great and does all things"
But does it know why kids love cinnamon toast crunch?
8
1
84
u/Fabien4 Apr 22 '10
The thing is, the question is not so stupid. I mean, adding to numbers is trivial, but first you have to make sure the two things you add are actually numbers. I've been bitten a couple of times by functions that returned "42" instead of 42. And of course, "42"+1 is "421" in Javascript, 43 in PHP, and an error in sane languages.
33
u/masklinn Apr 22 '10
And of course, "42"+1 is "421" in Javascript, 43 in PHP, and an error in sane languages.
FWIW it's
"421"in Java as well, but that doesn't make me disagree with your final assessment of the situation.And just to prove I'm not joking:
$ cat > Test.java class Test { public static void main(String[] args) { System.out.println("42" + 1); } } ^C $ javac Test.java $ java Test 42114
u/cc81 Apr 22 '10
And in C#.
5
1
u/jmcqk6 Apr 23 '10
I get a compile time error when I try to compile equivalent code using the microsoft compiler. have not tried mono.
2
u/cc81 Apr 23 '10
I just tried with
Console.WriteLine("42" + 1);Which gives the result 421. With .NET. What error did you get?
→ More replies (2)1
1
0
Apr 22 '10
[deleted]
54
34
u/tisti Apr 22 '10
Why not? "42" is more or less a pointer and you incremented it to point to 2, instead of 4.
But yea, C/C++ can fuck with you in unique, entertaining and rage inducing ways (usually at least 2 of those things are present)
→ More replies (5)2
Apr 22 '10
Haha yes, the test to see if someone really knows C++ is to see how much they hate it.
→ More replies (9)18
u/darth_choate Apr 22 '10
With a slight variation you could confuse the hell out of a budding C programmer:
main() { puts("-0.5" + 1); }→ More replies (1)7
u/The_Duck1 Apr 23 '10
You've inspired me to a search for other examples of correct C string arithmetic. So far I've only found the rather derivative
"-1.5" + 2 = ".5"
but surely there must be more, especially if you allow other number strings like "1.5e5".
15
u/darth_choate Apr 23 '10
Oh yeah, there's more:
"(int)1.8"+7 = "8" "1.1+1.9"+6 = "9"→ More replies (1)4
2
1
6
u/yogthos Apr 22 '10
and a sane exception in Clojure:
(println (+ "42" 1)) java.lang.String cannot be cast to java.lang.Number [Thrown class java.lang.ClassCastException]Incidentally this is why people argue that operator overloading is evil :P
4
u/masklinn Apr 23 '10
Incidentally this is why people argue that operator overloading is evil :P
I disagree, though it can be misused (hrm hrm C++) or used a bit too much (hrm hrm Haskell) it's a great tool for creating more readable a language.
On the other hand, this Java example is a great demonstration of how two-faced the guys who created java were: on the one hand they went all "oooh operator overloading baaaad, though shall not pass!", on the other hand not only did they override the
+operator for string concatenation, they added the "feature" of automatically converting the other operand to a string...1
u/kamatsu Apr 23 '10
The only freaky operators haskell has are like.. Control.Applicative.. operators aren't that common in haskell.
→ More replies (6)3
u/IHaveScrollLockOn Apr 23 '10
When do you use Clojure? Do you write it at work?
6
u/yogthos Apr 23 '10
Actually I do, I don't use it for production code, but I write a lot of internal tools in it. For example I wrote a tool to aggregate usage stats for our web app from the db and spit out charts using JFreeChart.
In fact I'm doing a presentation on it at work next week. We're trying to start having people give talks about new languages and technologies they're experimenting with.
I also use Clojure for all my personal projects outside of work, and I really enjoy coding in it.
→ More replies (4)1
u/cezar Apr 23 '10
I'm curious, do you always have to write System.out.println to print in Java? I know in Python there is "from System.out import println". Has Java developed anything similar?
7
u/redditnoob Apr 23 '10
import static java.lang.System.*; ... out.println("Who's expressive now, bitch?");→ More replies (1)2
u/mcosta Apr 23 '10
Of course, from the very begning of the language. When you say "import foo.Bar" Bar comes into the local lexical space. What you mean is importing functions. Java has no functions, so you can't import them. println is method of the out object statically declared in the System class. BTW out is final too.
→ More replies (6)0
u/doitincircles Apr 23 '10
That's kind of disingenuous. "42" + 1 is "421" in a String context, like as the argument to System.out.println().
2
u/Anderkent Apr 23 '10
I'm fairly sure "42" + 1 will always return a string (what else could it possibly match?), if one is not expected you'll get a type error on compile.
1
u/doitincircles Apr 23 '10
Yeah, I guess I phrased that wrong...but I don't really see the problem with this in Java. Outside of anywhere a String is allowed, it's a compile error. Hardly the same thing as in PHP or Javascript.
I'm pretty amateur so I can't think of a situation where this could actually be a problem. If you're expecting a string, you get a string, and if you're not, it won't compile, so...what's the problem?
→ More replies (1)→ More replies (1)1
u/MedeaMelana Apr 23 '10
Evaluating expressions in a way that depends on their context is the devil.
19
Apr 22 '10
Yeah. Weak typing is for crazy people.
I really don't understand the advantage, either for the programmer or for the compiler/interpreter. OK, I guess you don't have to explicitly parse strings to numbers, but that's a piddling little bit of less typing, at the cost of total chaos which does a really good job of hiding errors.
43
u/PstScrpt Apr 22 '10
A better conclusion is that languages with implicit type conversion really ought to have different operators for addition and concatenation.
21
Apr 22 '10
Agreed. If only the + could be an arithmetic operator for numbers and . could be a concatenation operator for strings.
→ More replies (5)8
Apr 22 '10
Agreed. If only someone had invented PHP.
7
3
u/potatolicious Apr 23 '10
I'm pretty sure PHP was just copying Perl on that point. Hell, a lot of PHP is straight out of Perl.
→ More replies (1)8
u/LieutenantClone Apr 23 '10
PHP does.
("42" + 1) : Converts "42" to 42, then adds the one, returns integer 43.
("42" . 1) : Converts 1 to "1", concatenates, returns string "421".
In PHP, plus (+) always adds, period (.) always concatenates.
2
u/PstScrpt Apr 23 '10
Wow, I had assumed the suggestion of "." for concatenation was a joke, that 42.1 would return "421".
2
u/killerstorm Apr 23 '10 edited Apr 23 '10
I don't think that implicit conversion of strings to numbers is a great idea.
What does ("abc" + 1) produce? ("123abc" + 1)? ("123 " + 1)?
Conversion of string to a number can be done in many ways, so I think it's better to do it explicitly (EDIT).
3
u/sad_bug_killer Apr 23 '10
What does ("abc" + 1) produce? ("123abc" + 1)? ("123 " + 1)?
1 124 124
I think it's better to do it implicitly.
Good, that's how PHP does it. Whether it makes sense or not, it's all in the manual
→ More replies (4)2
u/LieutenantClone Apr 23 '10
I don't think that implicit conversion of strings to numbers is a great idea.
Then you don't grasp the main feature of PHP. In PHP, you should never have to know what type a variable is. It should not matter. You just do whatever it is you want to do with it, and you don't have to bother with converting things all over the place.
And as Draders said below, if you are adding a string that is "123abc", the question should be why you are using an alphanumeric string in a mathematical equation.
3
Apr 23 '10
It's really quite simple, if there is a number at the start of a string, it will use it, if not its 0. Rather then being superstitious over it, a simple test script would reveal this to you and then it becomes expected behaviour.
The real question is why are you coding yourself into a situation where you would even be adding combination number/letter strings like "123abc" to a number in the first place.
→ More replies (12)2
u/davvblack Apr 23 '10
Yeah, that's why people hate PHP. It embarrasses them by doing simple things right.
1
3
3
u/_zoso_ Apr 22 '10
An even better conclusion would be to not code with your eyes shut and be aware of type precedence. Its not rocket science.
Why you need a prefix to every variable stating what type it is to work out if its a string, int or whatever is beyond me. I'm not against strongly typed languages, far from it, but I just don't see the big deal here, if there is uncertainty, cast it, you can still do that.
2
u/daelin Apr 23 '10
I hate explicit typing with a passion. You don't need explicit typing to have strong typing. Python, for instance, is strongly typed. (So's Haskell, but you need variables to participate in this discussion.)
→ More replies (2)7
u/barsoap Apr 23 '10
...Haskell has variables, and is statically and implicitly typed. (All three features being optional, including the mutability of variables)
→ More replies (5)1
u/redditnoob Apr 23 '10
If you have your own conventions, fine. If you ever are going to work with another programmer, or your code will be worked on by another programmer, you're going to have to check the type of everything manually anyway, in case someone passes in "1" to your function that is expecting 1.
→ More replies (1)3
u/redditnoob Apr 23 '10
OK, I guess you don't have to explicitly parse strings to numbers
Except you do!! And just try using parseInt without specifying a base.
Javascript is brain-dead. The other nice one is that you "don't" need to put quotes around object literals, like { interface: "My Interface" }... Oh wait that doesn't work, what does Javascript have interfaces? Nope but it's a reserved word. Oh and you think "undefined" is a reserved word too? No!! I can set undefined=6 if I want...
So basically, in object literals you need to use quotes anyway, and you lose the expressive power of passing in something like {keyParam: arrayParam} to a function that expects a dictionary (and keyParam is a variable). Instead I have to assemble that shit myself: "var dictParam={}; dictParam[keyParam=arrayParam];"
7
Apr 22 '10
I can't tell if this is sarcasm or not, because so many people here seem to love the "elegance" of weak typing so much. Granted I'm a fairly inexperienced programmer, but I just had my first experience with weak typing in Perl and it felt like I was selling my soul to the interpreter.
11
Apr 22 '10
weak typing != dynamic typing.
From reddit, I get the vibe that dynamic typing (i.e. where you don't know or don't specify the types of the variables upfront) is preferred over static typing, and that strong typing (i.e. where mixing types in certain expressions will lead to errors) is preferred over weak typing (i.e. where mixing types in certain expressions will cause variables to be coerced into a new type).
2
Apr 22 '10
ah thanks for the clarification. I see my inexperience reared its ugly head.
→ More replies (1)3
Apr 22 '10 edited Apr 22 '10
That's not exactly right.
Static typing means that the type that a certain variable holds is determined at compile time.
Dynamic typing means that the type that a certain variable holds is determined at runtime (and is possibly subject to change/rebinding.)
--
Strong typing means that once the type of a variable is determined, it is given a definite type that will be enforced by later function/operator calls. (e.g. If you put a 2 in x, x is an int and can't be passed to a function or operator that requires a string.)
Weak typing means that variables are able to be treated as several different types because the language will do implicit casting (or the equivalent) for you. (There is still typically a runtime type for the value being held, it's just subject to interpretation and coercion by the language when it's passed to the receiver.)
--
Whether or not "mixing types in certain expressions" will lead to errors depends on weak/strong typing, operator overloading, implicit casting, message/function dispatching, etc. For example, C# is a static/strong language, but you can still do this:
"42" + 1as pointed out above. This isn't because of weak typing. It's because of operator overloading.NOTE: This has been edited to include some corrections made by those replying.
→ More replies (4)7
u/voidspace Apr 22 '10
Disagree with your definition of strong typing "Strong typing means that once the type of a variable is determined, it is set in stone. (e.g. If you put a 2 in x, you can't later put "Hello" into x.)"
I would say "Strong typing means the type of an object is fixed and you can't perform operations inappropriate to the type. The language doesn't perform implicit conversions for you by treating objects of one type as if they were of another type."
Allowing variable reassignment (name rebinding) is a standard feature of strongly typed dynamic languages like Python and Ruby.
→ More replies (1)4
1
u/killerstorm Apr 23 '10 edited Apr 23 '10
There are no language-level implicit conversion in JavaScript (as far as I know). It is a trait of specific operator "+" to automatically convert parameters. So I would not call JavaScript weakly typed.
OK, I guess you don't have to explicitly parse strings to numbers
I don't think JavaScript spares you from parsing strings to numbers. Parsing doesn't work in all cases, so it's better done explicitly.
JavaScript can just add .toString() for you. E.g.
alert("Values: " + a.toString() + " " + b.toString());can be written as
alert("Values: " + a + " " + b);Yeah, sometimes it might cause problems, but I would not call it "total chaos". People rarely have problems with this.
0
u/yogthos Apr 22 '10
This has nothing to do with weak typing. The problem here is operator overloading. Clojure is a weak typed language and this can't happen in it, check my post above.
5
2
→ More replies (2)1
u/SoPoOneO Apr 23 '10
Is it stupid to use the trick num = ("42"/1)+1 ? You will get the 43 you were looking for.
And of course you can do the same thing with a variable to coerce a string representation of a number into being an actual number
2
Apr 23 '10
When Number() exists, kinda.
1
u/SoPoOneO Apr 23 '10
Excellent point. Thank you. I hadn't known, or had forgotten, about that function. It will make code much clearer than a random + sign.
1
1
u/Fabien4 Apr 23 '10
Is it stupid to use the trick num = ("42"/1)+1
Kinda. Better use unary
+.1
u/SoPoOneO Apr 23 '10
What is "unary +"? Would that be like: +"42"+1 ?
2
u/Fabien4 Apr 23 '10
Yep.
Well, it's pretty useless with a string literal. However, if you don't know the type of
n, and want to consider it a number and add2to it, you'll write+n + 2.
17
u/zombiekiller Apr 22 '10
the internet, a place where cynics can masturbate and one up each other.
5
6
u/Reflejo Apr 22 '10
Related: "Is there a jQuery plugin for making an HTML page appear in browser", "Where are my legs?"
38
u/Axiomatik Apr 22 '10
Troll question; troll answer.
23
6
u/jerschneid Apr 22 '10
Was never actually asked or answered on SO. It's just a doctored up screen shot.
4
u/IHaveScrollLockOn Apr 23 '10
SO is far too intelligent for something like that (so far). Whenever I have a problem, I go to Google and smile if I get a result from SO because it is almost always extremely helpful.
2
u/jerschneid Apr 23 '10
I agree, ALTHOUGH, one of my most popular answers on SO was a joke answer:
http://stackoverflow.com/questions/1763845/when-to-use-and-when-not-to-use-threads/1763889#1763889
0
1
1
u/dreasgrech Apr 23 '10
Giving credit where credit is due:
I got the image from Andrew Clover's blog
1
Apr 24 '10
I didn't read the whole article because the acidic attitude turned me off pretty quick, still, I got to this part:
Almost always, the ‘best’ way of finding out whether a checkbox is ticked is given with a straight face as: $(input).is(':checked') — as obviously input.checked just doesn't do enough selector-parsing busywork to be really modern.
I think this guy is missing the point of jQuery. This example is about cross-browser compatibility.
input.checkedreturnsundefinedin IE!Sure, some people learn it and think jQuery is JavaScript, and lots of stupid code then comes out of them. That's not jQuery's fault. In the end, hiring noobs will hurt regardless of the JavaScript framework they've chosen.
5
u/A_for_Anonymous Apr 23 '10
function add(x, y) {
return y == 0
? x
: (y > 0
? add(++x, --y)
: add(--x, ++y))
}5
4
4
u/placidppl Apr 22 '10
The same goes for the Boost C++ lib. The people on that site give very little thought before responding/voting to if the Boost(or jquery, or etc...) lib actually is suited to the problem. "Hey, got a problem? throw more Boost at it and MAGIC!"
2
13
u/hyperbolist Apr 22 '10
Waiting for the "Elitism on StackOverflow" blog post.
14
u/gx6wxwb Apr 22 '10
'k, I'll sort of bite, not about elitism though.
When I read the OP and how simple a question it was, my first thought was that it might have been from a kid who wants to learn to code and is playing around with Javascript to learn the basics.
If so, that kid's just been ridiculed simply because they asked a basic question. All it needed was a bit of basic civility and a 1-line answer to their question, they might grow up to produce something really cool and useful. Instead they might just give up trying to learn because, well, who wants to associate with assholes?
But yeah, it might just as easily been a troll question. My point is that you never know, and a civil and helpful response to a troll is still a civil and helpful response that might be useful to someone somewhere.
3
2
u/StabNSprint Apr 23 '10
I am compelled to believe that even a 5 year old dabbling in computer programming will at least attempt to use the "+" operator or at the very least Google "adding in Javascript". Very clearly a troll, in my opinion, if it were in fact a real post.
→ More replies (4)1
u/serious_face Apr 23 '10
I'm also going to sort of bite, and suggest that if a kid cannot make the mental leap from assigning to a variable, to adding a number to a variable, they will probably not produce something really cool and useful.
3
u/kumyco Apr 22 '10
Based on how the question is phrased, it would have been hilarious if after all that, the poster came and clarified that they were talking about an array as opposed to just a variable.
2
6
Apr 22 '10
I know it's fake, but I would completely believe that this can happen.
2
u/berlinbrown Apr 22 '10
Every question I ask about javascript and/or HTML ends up with something about jQuery.
There is some realm of the programming universe (gasp) where developers aren't allowed to or using jQuery.
0
Apr 22 '10
If you need to do anything with the DOM, you should not be using JavaScript. You should be using jQuery, YUI, Dojo, or even Prototype (ack).
Writing straight up JavaScript is like writing straight up Assembly when you should be using Perl.
3
u/daelin Apr 23 '10
Writing straight up JavaScript is like writing straight up Assembly when you should be using Perl.
So you should probably just avoid programming altogether?
2
Apr 23 '10
If someone else has already done the hard work, you shouldn't re-do the hard work. I think there's a name for that...
If I can avoid programming, I will avoid programming. I did not program my OS, my browser, my IDE, etc, because it would be a waste of my time.
→ More replies (3)2
u/robwgibbons Apr 23 '10
I realize you're trying to make a point about using the right tool for the job, and that DOM manipulations aren't very pretty in JS. But jQuery is as bloated as a dead fish for what most people use it for, most often. DOM manipulation can be made extremely simple just by including a dozen or so prototype methods and a dollar-sign function in your common.js file. I really can't justify the weight of jQuery, knowing what I do now about JavaScript.
→ More replies (2)
3
3
Apr 23 '10
It is not possible to do arithmetic in Javascript. The best solution is to implement a web service in J2EE+Struts. That's how we do it in the enterprise world.
2
Apr 23 '10
These people are idiots! Everyone knows for this you need to asyncronously call a webservice that will query a database which will take care of it.. A little T-SQL never hurt nobody.
1
u/grav Apr 23 '10
Exactly. It is often much more efficient to look something up instead of computing it. And it should be no problem distributing such a database since we're doing read-operations only. SELECT result FROM addition WHERE a=:a and b=:b
2
2
4
u/kordi Apr 22 '10
Nice question and nice answers. The downvotes for the last answers are quite cool, too.
6
3
4
u/lukemcr Apr 22 '10
Searching StackOverflow.com and Google for the phrase "add a number to another number in javascript" yields no matches for this page. I think someone's trying to make a funny...
18
5
3
2
u/oscarreyes Apr 22 '10 edited Apr 22 '10
Faaaaaaaake!!! You can tell by
1.- No user in the question
2.- Bobince reputation is some
3.- No url in the post ( yeah, somebody took the screenshot but forgot to include the URL )
4.- Timothy Goatse nor i<3jQuery users exists.
1
u/boredzo Apr 22 '10
3.- No url in the post ( yeah, somebody took the screenshot but forgot to include the URL )
They wouldn't need to forget; the “screenshot” is only of the page, and does not include any browser chrome. Moreover, even if it did include chrome, I know of at least two browsers that let you keep the Location field hidden.
But yeah, fake for the other reasons and more where they came from. (Among others: the karma scores of “Timothy Goatse” and “i<3jQuery”, and the view count on the question.)
1
u/FlyingBishop Apr 22 '10
I was really hoping for a step-by-step walkthrough of what a JavaScript interpreter does to add two numbers.
1
1
1
u/tintub Apr 22 '10
No one seems to have noticed the "Related Content" yet :)
2
1
Apr 23 '10
SNFU FTW!
You may think a man's brain stops
After he's been dead and his legs chopped off
Well, let me tell you a story to change that belief
1
1
u/SajiRaju Apr 23 '10 edited Apr 23 '10
Bah JQuery!, You should definitely use the GWT spread sheet widget!
1
1
1
u/guitarromantic Apr 23 '10
The guy who posted this also posted that famous comment about encoding that devolved into Lovecraftian wailings. He also answered one of my SO questions just the other day.</nerd pride>
1
u/omepiet Apr 23 '10
Does jQuery offer a more_cowbell function? Everybody knows that more cowbell is the solution to all problems.
2
u/ascii Apr 23 '10 edited Apr 23 '10
Yes and no. jQuery does have powerful cowbell functionality, but it's not implemented exactly the way you describe. You access cowbell through the cowbell operator, $. If you want to apply cowbell to something, say the variable f, you simply write $(f). jQuery does not have a single function to apply more cowbell than that, but you can do it manually by writing $($(f)). That will result in adding more cowbell to f. You could of course define something like function moar_cowbell(f){return $($(f));} but that would break the basic jQuery design principle of overloading every single library onto a single one character long namespace.
As a matter of fact, you can apply cowbell as many times as you like, in order to get exactly the kind of sound you're looking for for your web site. In fact, in a modern browser, you could even add a worker thread that continuously adds more cowbell to your website in the background, making it more and more awesome.
Hope this helps and good luck with jQuerying.
1
1
u/orbiscerbus Apr 23 '10
Is this some alternate reality? Are we all really in the mind of Philip K. Dick all this time?
1
u/ascii Apr 23 '10
The above article may be a joke, but it's not far from the truth. Adding two numbers may be pretty consistent across JS implementations, but take event management. Running a little scriptlet when e.g. the user presses a key, that should be one of the most basic things an application scripting language can do, right? Defining a handler in Javascript is ok, we can simply say el.onkeydown = function(event){...}; and we've defined a handler that will be triggered when the user presses a key inside the specified DOM node. But what if we want to find out which key was pressed? Then you're proper fucked, as they say. Different browsers use different event objects. Of course IE is the worst, but there are minor differences in the other browsers as well. In fact, you can't even reliably find out what the source of the event is! Just how could the Javascript people fuck up this badly?
Enter jQuery. Simply write
$(el).keyup(function(event){...});and jQuery will apply event normalization, so that your event handler will receive event objects with the same format regardless of platform. One less thing to worry about.
Wihtout jQuery, Javascript is so much less usable it's not even funny.
2
u/Lozzer Apr 23 '10
It's the DOM that's crap, not JS so much.
2
u/ascii Apr 23 '10
Very true.
Making a variable global if you forget to declare it is enormously retarded, but fortunately, it's possible to detect it using lint. There are some really stupid misfeatures resulting from the hash/object equivalency, e.g. you can't get the number of elements in a hash in a non-idiotic way. Other than that, JS is mostly sane, unlike the DOM, which is unbelievably crappy.
1
1
1
u/berlinbrown Apr 23 '10
...OK, so which is worse. The fake stackoverflow question? Or hundreds of comments to the fake stackoverflow question reddit?
...There are computer scientists that are rolling in their graves.
1
0
-4
u/MoonJive Apr 22 '10
StackOverflow, making us all long for the days of Experts Exchange.
4
u/kirun Apr 22 '10
At least Stack Overflow lets you see the answers without 10 screens of scrolling through THERE ARE NO ANSWERS ON THIS PAGE SO WHY DON'T YOU ENTER YOUR CREDIT CARD NOW FOR THE FREE TRIAL THAT IS FREE THAT SHOWS YOU THE ANSWERS THAT ARE NOT HERE.
-2
u/trevdak2 Apr 22 '10
Addition? I'm not sure computers were ever meant to add.
If your problem can be solved by adding two numbers, perhaps you're asking the wrong question.
4
u/berlinbrown Apr 22 '10
There is a webservice for adding, google and yahoo both have them. You use jQuery to make the request.
-3
Apr 22 '10
Yo dawg I herd you like Java, so we put a numba in yo numba so you can program while you program
0
u/HaMMeReD Apr 22 '10
Can anyone explain jquery's appeal to me? It seems like it goes to great lengths to not look like javascript.
3
u/BuffaloBuffalo Apr 22 '10
It smooths over the differences between all the modern browsers.
It's very lightweight (18k in production) and its tasteful design makes it a pleasure to use.
The elegant use of Javascript features (closures, dynamic types, prototype based), means more power with less code. Quicker to produce and easier to read, with less errors.
1
u/HaMMeReD Apr 23 '10
But there is no shortage of toolkits that also fulfull that criteria, without making javascript look like an abortion.
1
1
u/BuffaloBuffalo Apr 23 '10
Well, what is your Javascript supposed to look like? If it's merely remeniscent of Java and C, then I'd argue that you aren't taking advantage of Javascript's powerful features in an elegant manner. But more importantly, the API's style and semantics should strive for consistency, which jQuery does very well.
3
u/royrules22 Apr 22 '10
It seems like it goes to great lengths to not look like javascript.
That's the appeal.
3
u/HaMMeReD Apr 22 '10
I don't see the problem with that, I consider javascript to be one of the best scripting languages ever. I fucking love lazy typed languages, and the lazy prototyped javascript, fuck you can accomplish so much while being lazy.
1
u/bean-the-cat Apr 23 '10
I agree with you. I love JavaScript, though I can remember when I was not as comfortable with it as I am now. When I was like that, I enjoyed jQuery a lot because I didn't understand prototype-based programming. Now that I understand how to utilize JS to its full potential, I can't stand the extra weight that jQuery adds to the page. Though to me, JQuery is still the gateway drug to JavaScript.
2
u/robwgibbons Apr 23 '10
Me three. I love JavaScript. I have no problems with its syntax. If you have a problem with the way JavaScript looks or works, you most likely don't know much about it. It's an extremely powerful and dynamic language. Most of the problems people typically attribute to JS are actually problems with the DOM, or with the browser itself (cough IE).
For example, prototypes make extending the language to fit your usage patterns extremely simple.
IE: Method chaining. Here is a dramatic but potential use of prototypes:
Truck.start().turnLeft().turnRight().goForward().stop();...Instead of:
Truck.start(); Truck.turnLeft(); Truck.turnRight(); Truck.goForward(); Truck.stop();That's awesome. And you don't need a bloated, fat library for the majority of what you do on a daily basis. There's nothing wrong with using jQuery or another JS library, but too many people have come to rely on them without even attempting to learn JavaScript itself, which hurts the web. I'm not against jQuery or other libraries, as I have used them, but I still cringe when I'm looking for a particular function or script and find nothing but jQuery plugins.
→ More replies (1)1
u/A_for_Anonymous Apr 23 '10
It seems like it goes to great lengths to not look like javascript.
Is that a bad thing or a good thing?
Okay, so Javascript is not that bad. It's just that its type system is a humongous lump of shit, dictionaries are broken, arrays are kind of broken, for..in is broken, Number is broken, the standard library blows, the DOM sucks, and the way it's attached to a web browser is malignant, among other things. On top of that, Microsoft made sure it was as unusable as possible.
1
u/cjg_000 Apr 22 '10
It seems like it goes to great lengths to not look like javascript.
You answered your own question.
328
u/stratoscope Apr 22 '10 edited Jan 03 '15
Edit: The image link above is now broken, so here is another copy of the Stack Overflow screenshot.
Most of the comments and answers in that Stack Overflow thread are missing an important point: jQuery does not have support built in to add one number to another.
One answer references a "basic arithmetic plugin", but at the time of this writing, there was no such plugin to be found in a Google search.
Fortunately, anyone can write a jQuery plugin, even yours truly.
So to make your arithmetic needs simple, I present:
If you paste that code into the multiline Firebug console on any page that uses jQuery (such as this Reddit page) and then execute it with Ctrl+Enter, it should alert '42' four times. (To get into the multiline Firebug console, open Firebug and click the little orange arrow-thing at the lower right.)
The beauty of using a jQuery plugin for this is that you no longer have to remember complicated arithmetic operators, only the simple jQuery chaining that you're used to.
Edit: added
subtract()method. Now you can add and subtract numbers in the same jQuery chain!Edit 2: added test case showing how you can save a number and use it again later, without any of those pesky JavaScript variables!