CodeinWP CodeinWP

Some Random JavaScript Coding Tidbits

Some Random JavaScript Coding TidbitsAlthough my knowledge of HTML and CSS seems somewhat rounded and complete, I don’t feel the same way about JavaScript. I always seem to be learning something new, or else reminding myself of stuff I might have learned years ago but have forgotten.

So here are a few things I’ve recently learned or read about that might be useful to you.

Functions With Optional Arguments

Have you ever done the following, or something like it:

alert("hello world!");

Wow, that’s complex stuff, huh? Well, as you probably know, the alert() function is built into the language. You generally pass a single argument into the alert() function, and the browser will throw a pop-up message to the user displaying the message passed in.

But what happens if you do this:

alert("hello world!", "How you doin'?");

You might assume one of two things should happen: (1) Two consecutive alerts showing the same message, or (2) an error with no alert. But the answer is neither. Instead, the result is exactly the same as the first example that has only one argument.

The reason for this is that, in JavaScript, function calls can accept an unlimited number of arguments — even if the defined function itself only processes one or two (as in the case of alert()).

So what does this mean? Well, this has its pros and cons. If someone mistakenly adds an extra argument to a function call that will only deal with a certain number of arguments, they could be left scratching their heads over why the argument isn’t being processed, since no error informs them of the problem.

On the plus side, this allows you to write functions that accept optional arguments, and then write code to deal with this accordingly. This happens all the time in jQuery, and it’s something that can make your functions more flexible.

Redefining Native Objects

While we’re on the topic of alert(), here’s another thing it might be useful to know. Try this:

function alert(myvalue) {
    document.write(myvalue);
}

alert('hello world');​​​​

To save you the trouble, here it is in a fiddle.

In this example, we’ve redefined the alert() function so that instead of the message being displayed in a customary alert dialog, the alert() function writes the message onto the page. In the past, this also meant you could redefine other values, like the undefined property.

Try the following example in an older browser like IE8:

var undefined = 'hahaha';
var myvar;

if (myvar === undefined) {
    alert('it is undefined');
} else {
    alert('it is defined');    
}

Although the myvar variable has not yet been defined, when we check to see if it’s equal to “undefined”, the if-else statement resolves to tell us that “it is defined”. This is because of what we did on the first line of that code block: We redefined “undefined”.

Update: As pointed out in the comments, being able to redefine certain properties like “undefined” is no longer possible in ECMAScript 5 compliant browsers. But this does work in an older browser, like IE8.

Comparing Strings Like Numbers

You probably have done numeric comparisons before using greater-than or less-than operators (“>” and “<“). And if you’ve wanted to compare two strings, you’ll just check to see if they’re equal. But you can also do this:

if ('baseball' > 'football') {
    alert('baseball rules!');
}​​​​​​​​​ else {
    alert('football rules!');
}​

Notice that I’m checking to see if the string “baseball” is greater than the string “football”. Unfortunately, JavaScript doesn’t know anything about sports. Baseball is obviously much greater than football. But in this case, the result will be an alert message of “football rules!”. Try it.

So how does the browser calculate which string is greater? Well, it simply assigns a number value to each letter and then the comparison is done from the resulting assigned numbers, comparing each digit from left to right (not the numbers as wholes). To make the baseball/football comparison return a positive alert for us baseball fans, all we have to do is convert the first character in the string “football” to uppercase, like this:

if ('baseball' > 'Football') {
    alert('baseball rules!');
} else {
    alert('football rules!');
}

Uppercase letters are viewed as lower in value than lowercase letters, so now the if-else statement will return the correct result — that baseball is in fact greater than football.

Again, this is not necessarily something that you’ll be using any time soon. It’s not often you have to compare strings in this way. But it’s good to know that it is possible should the need for such a computation ever arise.

Update: Thanks to “bz” in the comments for a few clarifications in this section. Clearly, I should be paying him to write this. :)

More Like This?

What do you think of these types of posts? I normally don’t cover JavaScript as much as I do CSS. But I would like to publish stuff I pick up here and there, if for no other reason than to have a reference of my own to use. Your thoughts are welcome — especially if anything I’ve said here is incorrect.

15 Responses

  1. bz says:

    Sometimes I feel like this blog is going back to the basics, stating obvious things… You are clearly learning as you write, but you did admit that you’re learning Javascript.

    Unfortunately you have stated a couple things that are not true. When comparing strings, you’ve said that “it simply assigns a number value to each letter and then checks to see which number result is greater”. That’s not entirely true.

    It actually only compares the first character, or the first couple characters until a result can be compared. So you don’t have to change all letters in 'football' to uppercase, only the first letter. If the first characters of both strings are different, it ignores the rest of the strings.

    Another thing is your section about undefined (which, to be precise, is a global property which can also be accessed as a variable). It clearly works in JSFiddle, but only because the code that is run in JSFiddle is actually run in a different scope, so that section is not always true. Try copying and pasting your code between script tags in an empty html file. You will get the opposite result, because as of ECMA 5 it is not allowed to reassign the value of the undefined global property (and NaN, and Inifinity). What you are actually doing in your JSFiddle is you are creating a local variable (in JSFiddle’s scope) called undefined. Try accessing window.undefined – it will still be ‘undefined’.
    So please correct your article.

    • bz says:

      Also, what is (in my opinion) a lot more interesting than the fact that you can redefine the alert() function is that you can do the following:

      
      Array.prototype.toString = function () {
          return 333;
      }
      
      var a = [] + [];
      console.log(a); // a is now 666

      or even

      Object.prototype.valueOf = function () {
          return function() { alert("Boo!"); }
      }
              (+{})(); // This code will display an alert saying "Boo!"​​​​​​​​​​​​​​​​​​​
      
    • Hey, bz. Thanks for the clarifications.

      One of the reasons I write stuff like this is so that I can get feedback and continue my own learning process. I never claim to know JavaScript extremely well at all.

      Yes, I know I was oversimplifying the string comparison thing. Evidently, every character you can enter in a string is treated using its Unicode equivalent, but I didn’t want to get into all the details of that as I really don’t fully understand it anyhow. I just wanted to point out that strings can be “greater than/less than” other strings.

      And yes, I will clarify the part on “undefined” as you are correct about ECMA 5 compliant browsers. So, for example, in IE8, I can redefine “undefined” but in Chrome I cannot.

      Thanks!

      *crawls back into his hole* :)

  2. augusto says:

    hope you’re from usa, and call football to that version of rugby you play. in the rest of the world football is that game played with the foot hitting a ball, called by usa people ‘soccer’ ahahah

    now..if you’re not from the usa, man! you got guts to declare that baseball is greater than football ;-)

  3. Florian says:

    I was thinking the exact same thing. In ES5 compliant browsers it’s not possible to overwrite window.undefined.

    “and it’s yet another reminder that everything in JavaScript is an object”

    You are just overwriting a variable, it has nothing to do with objects.

    • Well, as you pointed out, undefined is a property of the window object, so it certainly has something to do with objects.

      Anyhow, I was not aware of the change in ECMAScript 5, so I’ve updated the article in line with the clarifications in the comments. Thanks.

    • Actually, I believe it’s more accurate to say that undefined is a property of the global object:

      https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined

      Mozilla’s reference does not list “undefined” as a property of the window object:

      https://developer.mozilla.org/en/DOM/window

      • bz says:

        Nobody said it’s a property of the window object. By using window.variable you can access variables in the global scope.

        • Right. I thought he was implying that it was a property of the window object. I see what he was saying now.

        • Oh, and if you’re wondering why I’m writing about subjects that I clearly don’t have a very good grasp of, you might want to read this:

          http://www.smashingmagazine.com/2012/03/30/publish-what-you-learn/

          I think more developers should be willing to do this. Nothing wrong with learning publicly. After all, if I only write about subjects I’m ‘expert’ in, then how will I write about anything new? :)

          • bz says:

            It is great that you learn and you post about your findings, however it is very harmful to post things that are incorrect. You should research things properly before posting and be absolutely sure that you’re conclusions are correct.

            FYI your description of strings is still incorrect. To explain it in a simple way, imagine you’re trying to sort words alphabetically. You don’t really assign numbers to characters (your text is misleading, it states that JavaScript “assigns a number value to each letter and then checks to see which number result is greater”, so one could conclude ‘ab’ < ‘aaaaaaaaaaa’), you just check whether the first letter is earlier in the alphabet (in this case, in the Unicode “list” of characters). So if you have ‘apron’ and ‘apple’, you have to check the first three letters, since both words begin with ‘ap’ and you can’t determine the result; and since ‘r’ > ‘p’ (r is later in the alphabet than p), then ‘apron’ > ‘apple’. Do you get it now?

          • Harmful? Actually, violence, racism, and lies are harmful.

            This is not harmful. It’s just my blog and I misstated something accidentally. And if anyone wants to use anything I’ve said here, they’re going to test it, and then when it doesn’t work, they’ll correct it. That’s not really harmful. Temporarily misleading maybe. Not harmful.

            Anyhow, you’re right. I didn’t mean to say that the numbers were being compared as if they were “totals”. I understood what was happening, I just didn’t explain it properly. I hope the current revision of that sentence suffices.

  4. Greg Babula says:

    Great post, I would love to see more JavaScript related content.

  5. rakesh says:

    great posts man i havent think this kind of things i wish you keep on updating new post

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).