Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 34

Thread: String replace

  1. #16
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by Airblader View Post
    Just to point one thing out even more:

    If you look at the results, === performs about ten times faster than == when types are different.
    Yes, but testing unequal types, unequal numbers IE9 still ran 848,904 times in 0.082 seconds.

    Speed of execution is hardly ever an issue with Javascript these days. Someone who tells me that a executes faster than b is to my mind a drowning man clutching at a straw. In most cases there is no measureable difference.

    Airblade - you are showing signs of becoming a Javascript Taliban. You ought not to throw insults such as "lazy" at people who I dare say have a great deal more experience than you have. 10 times more experience perhaps - and that is measureable. There are quite a few words to describe you, you know.
    Last edited by Philip M; 02-10-2013 at 03:49 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  2. #17
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    Yes, it is executing extremely fast, even using type-insensitive comparisons. But you generally execute more than a single comparison and there is much more to optimize than just comparisons.
    If speed was the only gain and if it would come at a certain cost, I would agree that it's more of a waste of time. But that's not the case here – It's a single character and typing it brings more benefits than just speed.

    You say speed isn't an issue with JavaScript these days, but if so, how come libraries are compared based on speed? How come even the big libraries in this business try to become faster and faster? Maybe it's not too much of an issue on desktops, but it sure is on mobile phones. But sooner or later it also becomes an issue on desktops. If I can have a speed improvement of factor ten with so much as a single '=', then I will type that one '=' out. I don't see why one would deliberately make code slow if it's so easy to not have that happen.

    But like I said, it's not just about speed.

    Let's take a step back:
    Advantages of type-safe comparison are speed (as proven(!) above) and robustness (type-safe). These are two facts. One more thing, that might be more of a matter of taste, is readability of the code. In my opinion, if I know for sure what type a variable is, I'm more unlikely to make a mistake using it, like '5' + '3' = '53' (which comes back robustness again). And you know very well how often people make those mistakes. We all made them and maybe still do.

    Now my question: What are disadvantages of '===' and what are advantages of using '=='?
    Because at least so far I haven't heard any. The only things mentioned so far were "because JavaScript can do it" and that you don't need to convert everything yourself (rnd_me called it a boilerplate – I would agree, if the '==' comparison would be just as fast as doing the conversion yourself, which it isn't, and if it wouldn't result in error-prone code). But both arguments don't really have any value, because they only comfort the developer in the sense that he has to write less. That's nice and I sure welcome having to write less, but that's not what makes good software. Speed and robustness, however, are part of what makes good software. I try to write as little as possible, but as much as needed. So yes, I currently have no better explanation for deliberately not writing a single character, knowing that it not only has no advantages but actually has downsides, than laziness.

    Airblader - you are showing signs of becoming a Javascript Taliban. You ought not to throw insults such as "lazy" at people who I dare say have a great deal more experience than you have. 10 times more experience perhaps - and that is measureable. There are quite a few words to describe you, you know.
    I feel Old Pe(n)dant's pain.
    First of all, I didn't call anyone in paritcular "lazy". I said this way of programming is lazy and I outlined above why I think so. I didn't use it as a simple insult, I used it as a logical conclusion after thinking about pros and cons. If you feel insulted because this is how you code, but you feel it is not laziness, then I'll gladly listen to your reasons. By the way, I certainly am lazy in some details too. Just because I'm trying to get rid of them doesn't mean I am there yet. I'm speaking in ideological terms.

    In any case I can assure you that you can feel free to describe me however you want. I think we established that we have different opinions on certain issues and if a discussion comes up, I will provide my opinion. Especially when I think it is wrong to teach "newbies" certain opinions which, while being okay with experienced developers living by them, I feel are out-dated. For example, I don't care that you write your code unindented. But if you were to suggest a newbie to do so, I sure would intervene.

  3. #18
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Once more, let's just agree to disagree. You do what you want. I will do what I want. You are starting to bore me. OK?

    You have been a member of this forum for less than a month. It is not a good idea for newcomers in any group to start throwing their weight around. Your opinions would be more respected if you yourself offered useful code to solve the OP's problems, rather than making lofty pronouncements and picking pointless arguments based on your limited experience.
    Last edited by Philip M; 02-10-2013 at 07:33 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  4. #19
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    Actually, Philipp, I originally wasn't even talking to you. You were the one to comment what I had said. If that bores you, don't do it, no one is forcing you to join or continue a discussion.

    I frankly don't care too much if you respect my opinion, because I am not here for you. but I take that you don't and that's fine. I'm helping people asking questions and that may be in the way of answering their questions, but it may also be in the form of a discussion that they can read up on. I'm also here to maybe take something from these discussions for myself, which, by the way, I already have.
    I also wasn't the one to start the discussion. Before I even posted in this thread you had already written posts that were not "offering useful code to solve the OP's problem".

    Furthermore, to me this is not a pointless argument. I would love to learn why people do what they do, but if what has been said so far are the reasons, I will stick with my current opinion. If something good comes up, I'll be ready to change my mind.

    Lastly, for the sake of professionalism I won't comment your last sentence too much. Let's just say that your experience isn't unlimited either.

    So yes, we agree to disagree, but please allow me to choose which discussions to join and simply don't comment my posts if they bore you.

  5. #20
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by Airblader View Post
    Advantages of type-safe comparison are speed (as proven(!) above) and robustness (type-safe). These are two facts.
    any robustness of the kind you describe comes from detecting errors earlier, but again, type mis-conversions aren't that common of an err in JS. In fact, aside from noobs concatenating form values (JS should have two different "+"s), i don't see type errors at all.

    I think a lot of times, user-coded tool functions are overly strict. I've seen a lot of old-school artifacts in such code, all in the name of robustness.
    Examples include:
    rejecting number object keys
    rejecting string array keys
    "!!" in front of local var assignments
    "if(typeof x==='function'){x();}" instead of letting x throw naturally if an exception occurs: "x();"
    Math.floor(Number(x))

    I call all that stuff boilerplate, and i believe it makes JS less like pseudo-code and more like C++


    Quote Originally Posted by Airblader View Post
    Well: As long as types are equal, == and === don't make much of a difference. Actually, === may even be slightly slower.
    wait, i thought the fact was that "===" was faster than "=="?
    my favorite kind of facts are those that are true all the time...
    it's a fact that 9 is prime, expect for that 3 that nobody uses...


    in fact, (hehe), one of the places "==" or "===" is used most often is after typeof , which always produces a string. When comparing the result to a string literal, "===" offers no additional robustness and slower performance. downplay the example if you like, but "these are two facts."

    by my count, jQuery uses "==" about 25% of the time. are they lazy? are they sandbagging the performance of all apps running on top of them?

    Or, are you perhaps over-generalizing by substituting a few specific artificial benchmarks for the much-revered work of many coders with centuries of collective experience?


    the bottom line is simply that "==" works well in some cases, "===" better in others. It's a bit foolish to put the focus on "===", or strong typing in general being a bit faster. You must also consider how long would C++ take to do "=="?


    When you see how much C/JAVA-esqe boilerplate you could avoid (several IFs or a SWITCH) if you could only use "==" in strong typed environments, maybe you can gain respect for such literal weakness and the lazy programmers who prefer it.


    EDIT
    more background on why i call it boilerplate.

    once you go back the other way, the power of JS to sniff proper types without explicit checking becomes quite clear.

    i have turned js into a a pretty strongly typed language using Hungarian notation.
    the first toy in my magic script testbed is a strong-typing Function method.

    It can ensure 3 kinds of proper type usage:
    -function arguments
    -function local variables
    -function returns

    it runs on the function and writes/parses new code that does the type guards, turning this silly demo (which implores all three kinds of type checks):

    Code:
    function int_sum( num_x, int_y){
    
      // strong type declaration block : 
      Var:start; 
      Var: int_n=parseInt(x);
      Var:end 
    
      var result= n + y;
    
     return result;
    }

    into this generated function:

    Code:
    function int_sum(x, y) {
    	var _SCOPE_ = {};
    	with(_SCOPE_) {
    
    		var _x, _y, _n, RETURN;
    
    		Object.defineProperty(_SCOPE_, 'x', {
    			configurable: true,
    			get: function _get() {
    				return _x;
    			},
    			/* end _get */
    
    			set: function _set(x) {
    				if (typeof x !== 'number') {
    					throw new TypeError('x is not a number')
    				} /* end if */
    				;
    				_x = x;
    			} /* end _set() */
    		});
    		x = arguments[0];
    		Object.defineProperty(_SCOPE_, 'y', {
    			configurable: true,
    			get: function _get() {
    				return _y;
    			},
    			/* end _get */
    
    			set: function _set(y) {
    				if (Math.floor(y) !== y) {
    					throw new TypeError('y is not an Integer')
    				} /* end if */
    
    				if (typeof y !== 'number') {
    					throw new TypeError('y is not a number')
    				} /* end if */
    				;
    				_y = y;
    			} /* end _set() */
    		});
    		y = arguments[1];
    		Object.defineProperty(_SCOPE_, 'n', {
    			configurable: true,
    			get: function _get() {
    				return _n;
    			},
    			/* end _get */
    
    			set: function _set(n) {
    				if (Math.floor(n) !== n) {
    					throw new TypeError('n is not an Integer')
    				} /* end if */
    
    				if (typeof n !== 'number') {
    					throw new TypeError('n is not a number')
    				} /* end if */
    				;
    				_n = n;
    			} /* end _set() */
    		});
    		n = parseInt(x);
    		try {
    			var result = n + y;
    			return RETURN = result;
    		} finally {
    			if (Math.floor(RETURN) !== RETURN) {
    				throw new TypeError('RETURN is not an Integer')
    			} /* end if */
    
    			if (typeof RETURN !== 'number') {
    				throw new TypeError('RETURN is not a number')
    			};
    			return RETURN = RETURN;
    		} /* end try/catch */
    
    	}
    } /* end int_sum() */
    the difference is the boilerplate (non red code) that provides the type checking.

    example results:

    Code:
    var sum2= int_sum.strong();
    sum2(5,10) // === 15
    sum2(5.2,10) // === 15
    sum2(5,10.2) // === throw
    sum2("5",10) // === throw
    it's a toy function and i wouldn't use it in production without unit tests, but it well illustrates my point about JS's brevity.
    you don't need all that hooey, js is best pure, clean, and elegantly simple.
    if you compare the console/inspector to a crash log, i think this modern weak style is at a comfortable point that the perf/debug trade-offs from old to new ways are well worth it.


    see http://www.codinghorror.com/blog/200...nks-ships.html for an earlier back and forth on this.
    Last edited by rnd me; 02-11-2013 at 04:14 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  6. #21
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    Thanks rnd_me, that was an insightful post.

    "if(typeof x==='function'){x();}" instead of letting x throw naturally if an exception occurs: "x();"
    I wouldn't even see the use case for this (except when you're checking for the existence of a browser-specific function).

    However, catching an error is not stupid in general. If you're going to stop your script anyway, okay – let JavaScript throw it's natural exception. But you might want to ignore runtime errors for the time being and at least finish your script. However, that really wouldn't occur with the non-existence of functions but rather of, for example, properties of an object. But that's not the topic here.

    and i believe it makes JS less like pseudo-code and more like C++
    Is that even such a bad thing? Sure, a long time ago JS was this little fun language to decorate a website in (unfortunately mostly) annoying ways. But these days, JavaScript is used as a high-performing language for lots of things (WebGL, video decoding, …). But again, not the topic.

    wait, i thought the fact was that "===" was faster than "=="?
    my favorite kind of facts are those that are true all the time...
    Well, to be fair, you gotta read what I wrote and not pick only part of it. First of all, '===' is slower in "half" the cases, but only marginally slower. So little that it's barely measurable from within JavaScript. In the other half of the cases, however, '===' is faster – and not just a little, but a lot. So overall that does make '===' superior in terms of speed.
    The other aspect to it is that if you argue in favor of '==' for dynamic conversion, you really do only talk about the cases where types are inequal – which is precisely the case where '===' is (much) faster.

    in fact, (hehe), one of the places "==" or "===" is used most often is after typeof , which always produces a string. When comparing the result to a string literal, "===" offers no additional robustness and slower performance. downplay the example if you like, but "these are two facts."
    Since I'm arguing about effects that aren't noticable until you do thousands of operations like that, I won't downplay this example. In fact, I shall thank you – because I do the very thing you described.
    I would still prefer '===', even if the type check isn't necessary, if '===' were to be faster. But as explained above, it isn't. Awesome – I love discussions in which I learn stuff I can even directly put to use.

    by my count, jQuery uses "==" about 25% of the time. are they lazy? are they sandbagging the performance of all apps running on top of them?
    Why not ask the opposite question: Why are they using '===' 75% of the time? Maybe those 25% are cases in which we could know for sure that '==' is faster. Maybe it's cases in which it is known that performance won't be too big of a factor. Or maybe, even though unlikely, it is in fact "laziness" that hasn't been cleaned up yet (even jQuery gets cleaned up). Maybe later today I'll analyze some other libraries for the usage of '=='/'==='. That'll be somewhat interesting.

    the bottom line is simply that "==" works well in some cases, "===" better in others.
    Oh, I'm totally with you on that. I have been before and I am even more now after your post.

    The example you brought in the end is nice, but I do have several problems with it which I won't explain right now, but if you'd like me to, I can later. However, I too will bring an example of why I prefer having conversions in my code rather than letting the JS Compiler do that all by itself.
    Say we have a form with two number fields and say we have their values stored in two variables strFieldA and strFieldB. I'll use the 'str' prefix to emphasize their type. Now, say we do this:

    Code:
    // do some validation & stuff
    if( strFieldA < 0 || strFieldA > 10 ) {
        // throwing or whatever
    }
    if( strFieldB < 0 || strFieldB > 10 ) {
        // you shall not pass
    }
    
    var awesomeResult = +strFieldA + strFieldB;
    This, comments replaced with useful code, will work. Why don't I like it?
    First of all it reads terrible. Comparing strings and numbers feels dirty, it just doesn't read nicely (and code should make sense reading it, not just work).
    The next thing is that I feel like I'm raping the compiler by forcing the conversion of one(!) variable several times. You may argue that any compiler would optimize this and only do the conversion once. That's true, but I still wouldn't like how it reads. This(!) is the laziness factor. Sure, storing the converted value myself (see below) will create overhead, but that too would be gone after the compiler's optimization run (at least I would assume and expect that).

    But lastly, the robustness. And I'm not talking about newbies here. Say you wrote this code, you go on vacation and a colleague has to take over the project. $CUSTOMER decides that a third value, strFieldC, is needed. No problem. You add some validation and you rewrite the last line to

    Code:
    var newAwesomeResult = strFieldA + strFieldB + strFieldC;
    And boom – our code fails. This is such a subtle difference that it can and will happen to any developer, especially those having gotten (too) used to the weak-typed language. However, before you say it, I will agree that any decently developed software will have unit tests that would immediately fail (doh – we changed the way the code works) and when fixing that we will notice our mistake.
    And this really isn't a newbie mistake, it's a mistake that can even happen when simply refactoring code (oh, I'm sure there are refactoring tools out there that would throw out the apparently useless '+'). And that I know because just a few days ago I was fixing a bug that simply occurred because someone was "refactoring" some apparently superfluous code. And since the software we're fixing has originally been written by an Indian out-sourcing company that didn't give a damn about writing tests, this bug was in production for weeks before analysts hunted it down. Luckily, this was a rather harmless bug that only prevented some service agents from making a certain request, but we had similar bugs in the past that are in production for so much as a week and will cause damage in the area of tens of thousands of Euros. I should add that this was in Java and the bug was not exactly the same, but pretty similar. Similar enough to be an example. And again: Good test coverage will prevent this, but why take a risk and just hope your tests will catch it and what about taking over software you didn't write the tests for? In our project the test coverage is terrible (since we took over we have a few thousand test and still have way too many white spots) and it's not even our fault.

    So here is how I would write it (again, with prefixes that I usually wouldn't use, just for demo purposes):

    Code:
    var numFieldA = Number( strFieldA ),
        numFieldB = Number( strFieldB );
    
    if( numFieldA < 0 || numFieldA > 10 ) {
        // ...
    }
    if( numFieldB < 0 || numFieldB > 10 ) {
        // ...
    }
    
    var awesomeResult = numFieldA + numFieldB;
    Now, the beginning of the code clearly signals what types we are dealing with, we visibly only convert once and we eliminate any chance of accidentally screwing up (which still goes for other people, even if we're sure that we wouldn't make this mistake ourselves).

    All this being said, I'd like to pick up on my opening sentence again and thank you. I did learn something from your post and I'll agree that focusing on '===' only is not good, although I still prefer treating my code a little bit more strong-typed.

    General note: I only focused on results regarding Google Chrome. Performance results may vary with the browser, but I'm too lazy ( ) to test it right now.

  7. #22
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 583 Times in 564 Posts
    it's largely a matter of coding style, and what you're used to.
    i tend to coearce up-top on function if need be, along with assigning defaults to missing arguments.
    this ensures that my variable's methods are present.

    example:
    Code:
    arg1= arg1 ? String(arg1) : "anon" ;
    which can also be written as :
    Code:
    arg1= arg1 && String(arg1) || "anon" ;
    example2:
    Code:
    arg2= arg2 || 0 ;
    example3:
    Code:
    if( ! (arg3 && arg3.join) ) arg3=[arg3];

    on black box functions, i admit to using inline coercion operators to type cast. i know it's less-readable, but it's faster to execute (no function overhead) and less to type.

    for example,
    Code:
    var newAwesomeResult =  +strFieldA +  +strFieldB + +strFieldC;
    would turn my string vars into Numbers just-in-time for the addition operator.

    for example,
    Code:
    var newAwesomeResult =  numFieldA +  ''+numFieldB + ''+numFieldC;
    would turn my numbered vars into Strings just-in-time for the concat operator.

    but, if there are more than two of something, i tend to jump to an array, which opens up a lot of options.

    to concat:
    Code:
    var newAwesomeResult = [ numFieldA, numFieldB, numFieldC ].join("");
    doing mathy stuff is the converse, you need numbers.

    Code:
    var newAwesomeResult = [strFieldA, strFieldB, strFieldC].filter(Number).map(Number).reduce(sum);

    It's trivial to filter/cast a whole array using String, Number, Boolean, and other native constructors. i find this lets me do stuff like add a fourth value into the sum calculation without re-writing the core logic. It also means i can code the summation core apart from the summation operation, re-using the sum() function in many places, resulting in more self-documenting, more-reusable, more -cachable, and more-debuggable code.

    note that you can also use generics ascross types, even though not moany coders know about such magic.

    for example, new String().match can be used on numbers:
    Code:
    "".match.call(12345, /[24680]/g) // == ["2", "4"]
    this allows the handy methods that are locked into types (yuck) to be used freely (yay).
    you can use Function.bind() to pre-bake those generic applications (avoiding ".call(") into really fast callable functions:

    Code:
    match=Function.call.bind("".match);
    match(12345, /[2,4,6,8,0]/g) // == ["2", "4"]
    so to me, weak types have a few limitations that if one can live with, one can code simply and elegantly. Even in the cases where you need a certain type, as we've seen, you don't really need a certain type. "Laziness" is just fine so long as your method signatures are defensive.

    Sounds like you need a dynamic code therapist to help you with your dirty feelings of compiler guilt. While i get what you are saying about things "feeling bad", that's hardly a scientific reason to indicate one system or the other. I suspect your emotional attachment has to do with prior punishments and rewards, as my own experiences, drawing mainly from JS, subtly steer me in a different direction.

    in short, i think if you are going to go into a weak typed language, go all in.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  8. #23
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    I assign defaults too, but only if I actually want the arguments to be optional. If they are required, I want my function to throw an error and leave it to the usage to catch that error. Otherwise it would make debugging just more difficult.

    i know it's less-readable, but it's faster to execute
    IMHO a valid argument if and only if performance is an essential factor (i.e. lots of calculations), because then the trade-off is justified.

    and less to type.
    IMHO never a valid argument. Although, if it ever makes sense, then with JavaScript in order to keep the filesize down. But still, just personally, readability is more important than a few bytes.

    but, if there are more than two of something, i tend to jump to an array, which opens up a lot of options.
    True, and I enjoyed your examples. If it's more than a few, I would even prefer already collecting the data in an array instead of building one out of single variables.

    Sounds like you need a dynamic code therapist to help you with your dirty feelings of compiler guilt.
    Whether or not I need a therapist, it surely isn't compiler guilt. It's a matter of esthetics and readability. And yes, studying mathematics does teach you a certain sense of esthetics in a formal language, using punishment, and while I'm all for slang in American English – in a formal language, slang has no place. Code should be written such that it reads what it does.

    And
    Code:
    var result = +strA + strB;
    simply doesn't say "convert strA to a number, add strB and assign it to result". But we've been over this more than enough, I think.

    This is not an opinion I'm alone with, though. You will find this in most modern books about clean code/code style.
    Code style, to a certain extent, is a matter of taste. But there are some indisputable standards. When a new team is built, for example, no one ever argues about whether or not to indent the code, all they discuss is how many spaces to use for one indentation. Which, by the way, is a whole other side; it's one thing how you code on your own, in a team it's more important to agree on a code style, even if it differs from your own preferences.

    All that being said, the first book of this kind I had read was "Clean Code" by Robert C. Martin, because my company gave me this book right after the interview. If you think I need a therapist, take a look at that book. It goes much further and in parts further than I agree on. Although, the most "surprising" but valuable thing I learned from it was to not write comments whenever I can write my code to do the commenting for it. It's a good read, even if it goes a little far sometimes.

  9. #24
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by Airblader View Post
    I assign defaults too, but only if I actually want the arguments to be optional. If they are required, I want my function to throw an error and leave it to the usage to catch that error. Otherwise it would make debugging just more difficult.

    IMHO a valid argument if and only if performance is an essential factor (i.e. lots of calculations), because then the trade-off is justified.

    IMHO never a valid argument. Although, if it ever makes sense, then with JavaScript in order to keep the filesize down. But still, just personally, readability is more important than a few bytes.

    I said, "for black-box functions", not app code. Don't parse my words and turn a particular into a universal: that's not how i code applications. nor should anyone.


    black boxes are pure functions that server as tools like escape(), [].sort functions, isPrime(), sum(), getText(elm), etc that are to be:

    1. as fast as possible
    2. as compact as possible
    3. never modified in user-land
    4. semantically named by roll with Hungarian argument names.

    if something is not to be modified, then i don't see any value for semantic local variables or long-winded function calls where an operator can work.
    once a pure function passes a unit/component test, it can be safely closure'd/uglified, then have it's args re-named to Hungarian Notation, and then committed to a repo never to be modified again.

    These are typically smaller things like window.escape(): i don't care HOW it works, i just care THAT it works.


    i don't think these rules change for personal or group projects: nobody used the commented+whitespace source code version of jQuery in a real app...
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  10. #25
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    Okay, for fundamental functions like those I can agree. But it also falls into the category of needing to be extremely efficient (since they can potentially be called lots of times), which I did mention before.
    And the same thing goes for libraries like jQuery. It's 3rd party software, not my actual code. It will be committed to the repo and, as you said, never be touched again. I don't have to maintain it and neither does any of my colleagues. It has nothing to do with the actual code I'm writing.

    Minifying JavaScript is a way to speed up your website and uglification a reasonably good attempt at hiding your source code. But both minification and uglification are steps that are done in the deployment process, not in the development process, so this being my actual code, I can't write it the way the 3-rd party libraries I'm using or my blackbox functions are written.

    Side-Note: I have just learned about another JS quirk that I wasn't aware of. The question of whether to start curly braces on the same line or next line is a purely subjective matter of taste in most languages, but in JavaScript the same-line-style is the objectively better way:

    Code:
    // Will work
    function returnsSomething () {
        return {
            success : true
        };
    }
    alert( returnsSomething() ); // [object Object]
    
    // Won't work
    function uhOh () 
    {
        return 
        {
            success : false
        }
    }
    alert( uhOh() ); // undefined
    Funny how you miss such apparent quirks if you just never use the next-line-style. This surely is an example I'll remember.

  11. #26
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    Since I just happened to come across it:

    http://www.youtube.com/watch?v=taaEzHI9xyY starting at around 30min. He later on makes a strong case about the ===/== thing too. To put a part of it on here too:

    Code:
    0 == '' // true
    0 == '0' // true
    
    '' == '0' // false
    The example from my previous post was also from this video.
    Last edited by Airblader; 02-12-2013 at 11:38 PM.

  12. #27
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by Airblader View Post
    Side-Note: I have just learned about another JS quirk that I wasn't aware of. The question of whether to start curly braces on the same line or next line is a purely subjective matter of taste in most languages, but in JavaScript the same-line-style is the objectively better way:

    Code:
    // Will work
    function returnsSomething () {
        return {
            success : true
        };
    }
    alert( returnsSomething() ); // [object Object]
    
    // Won't work
    function uhOh () 
    {
        return 
        {
            success : false
        }
    }
    alert( uhOh() ); // undefined
    Funny how you miss such apparent quirks if you just never use the next-line-style. This surely is an example I'll remember.
    yes, after a return the semi-colon insertion rules are slightly different than mid-expression.
    you can use something and a continuation operator (,) if you need a newline after return by convention.
    see http://bonsaiden.github.com/JavaScript-Garden for more specifics.
    Last edited by rnd me; 02-13-2013 at 12:53 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  13. #28
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    So now both Crockford and that site explicitly state

    The above table shows the results of the type coercion, and it is the main reason why the use of == is widely regarded as bad practice.
    And Crockford really isn't just anyone.

  14. #29
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by Airblader View Post
    Side-Note: I have just learned about another JS quirk that I wasn't aware of. The question of whether to start curly braces on the same line or next line is a purely subjective matter of taste in most languages, but in JavaScript the same-line-style is the objectively better way:
    Well, that is something we do agree on. If you had followed this forum for more than a few weeks you would surely have noticed my oft-repeated comment

    It is recommended that the opening brace { is placed on the same line as the function, if, else, do, while, or for statement and not on the following line. This is because of something known as automatic semi-colon insertion. If you disregard this advice it is looking out and one day it will rise up and bite you in the undercarriage, and create an error which can be hard to find.


    In your example

    return
    {

    Javascript inserts a semi-colon after return, thus breaking the code.

    Crockford is an important authority, but he is not the Pope and there are quite a few of his views that do not command 100% acceptance. You should not regard people who do not agree with you as idiots, either. For myself, I am not young enough to know everything.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  15. #30
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    I didn't call anyone idiot, did I? If I did, I'm sorry (but I really don't remember).

    And I too have things I don't agree on with Crockford. For example, in the above linked video he also advises to never use '++'. To be honest, I don't think that I'll stop using it. Although I certainly would prefer 'x += 2;' instead of '++x; ++x;' (one of his examples in there).

    However, regarding the '==' versus '===' thing, transitivity of equality is a really basic concept. So basic, that in everyday life everyone knows it to be true without knowing its name, most people would even think it's so obvious that it doesn't need a name. But JavaScript breaks this property, which does make it potentially dangerous to use.
    Arguably, a lot of people have been using '==' without any problems and "typeof myVar !== 'undefined'" still is unnecessarily much. But I do think that it's a strong point that hadn't been mentioned before in this discussion and which does make a really good case for using '==='. I'd put it like this: It won't immediately break your neck to use '==', but it's just very advisable to prefer '===' and then use it consistently.

    Gosh, I love JavaScript (maybe that is what I should hire a therapist for).


 
Page 2 of 3 FirstFirst 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •