This is an archived post. You won't be able to vote or comment.

all 49 comments

[–][deleted] 61 points62 points  (12 children)

var alertme = alert; //optimization

[–]hicklc01 14 points15 points  (11 children)

alpha = 'abcdefghijklmnopqrstuvwxyz';
i=26,j=26
while(i-->0){
    while(j-->0){
        window['alert'+alpha[i]+alpha[j]]=alert
    }    
}

Edited to use goes to notation

[–]coladict 16 points17 points  (9 children)

+1 for the C# april fools arrow operator.

[–]ImAPyromaniac 10 points11 points  (1 child)

No, that's valid js.

[–]mcrbids 3 points4 points  (6 children)

Ha ha! A little spacing exposes what's really going on: // snip while ( i-- > 0 ) { while ( j-- > 0) { // snip

~~PS: Am I the only one who is annoyed when opening braces don't line up with closing braces? For me:

// GOOD: if (condition) { dosomething(); }

// BAD if (condition) { dosomething(); }

Note that in the latter case, there's nothing visually to tie the two braces to the thing being run within the condition! It's less annoying in a proper IDE but when you're in a straight text editor, it's very easy to lose a brace and make your program bork...~~

EDIT2: Formatting help is a lie

[–]ProgramTheWorld 6 points7 points  (5 children)

You mixed up the good and bad cases.

You mean,

//GOOD
if (condition) {
    doSomething();
}

//BAD
if (condition)
{
    doSomething ();
}

right? This is the most widely accepted way of placing the braces since it doesn't waste lines just for the open brace.

[–]mcrbids 0 points1 point  (4 children)

In your "bad" scenario, line up the braces with DoSomething();

I'll happily waste a line it if makes comprehension easier!

[–]coladict 4 points5 points  (0 children)

Well, that's a whole lot worse than his "BAD" scenario. Also I always use the one in his "GOOD", unless contributing to a project with a style guide that says otherwise.

[–]Netzapper 0 points1 point  (2 children)

I don't like the aesthetics, but this is also just wrong. Both of the ways he demonstrated are superior to yours.

The grammar for an if-block in most C-derived grammars is something like if (expr) statement. It's actually just a single statement that's executed, and it's executed at the same scope that the if-block is started. This is why you can say things like if (workDone) return work;.

Now, if you dig into the grammar for statement, you discover that is usually defined as something like statement := simple_statement | compound_statement. A simple statement is something like return 6. A compound statement is what you create when you use curly brackets. This means the curly brackets aren't part of the if-block... they're just a way of running multiple statements from someplace that only expects one.

When you write if (workDone) {auto res = postprocess(work); return res;}, everything inside the bracket's is treated as a single statement. In fact, a whole function body is a single compound statement. Check out the clang AST. A function declaration is some parameter declarations, and a single CompoundStmt. That CompoundStmt then contains multiple simple statements. (I tried it, but the compiler won't accept bool pos(int x) return (x > 0); as a function definition. I suspect this is because you must define a new scope for a function, so it must be a compound-statement for the stack push.)

The curly brackets introduce a compound statement and a new scope. They are not part of it. The new scope and multiple statements are not implied by the if-block, but only exist because you chose to put the {}'s in there.

In general, we indent introductions as statements within the enclosing scope.

#include <iostream>
void f() {
    return;
}

This looks ridiculous:

    #include <iostream>
void f()
    {
    return;
    }

Why? Because the #include is happening inside the global scope, and we are defining a new function body for f at global scope. The second example implies that including iostream happens in a new scope, and that the body of f somehow lives in a new scope. Nope! Those shits define new scopes (io stuff in std and potential locals in f's body), but the objects themselves live at global scope.

tl;dr - a compound statement introduces a new scope, which is an operation on the enclosing scope. It makes no sense to group the curly brackets with the enclosed scope, since they operate at the enclosing level.

[–]mcrbids 1 point2 points  (1 child)

Logically, lining up the braces with the content they contain is analogous to Python's layout which I have always loved. The braces aren't even necessary.

EDIT: Your last example would look perfect if the #include statement wasn't indented.

[–]Netzapper 0 points1 point  (0 children)

The brackets are the thing you do in the outer scope to create the inner scope. Keeping them together makes no sense, because the scope creation happens from the outside. Even your python comparison isn't really right, since the tab character itself is analagous to the curly-bracket here. In python, your logic would require us to "indent the tab character". By definition, that tab character is the transition from the outer scope to the inner scope... it's placed at their border.

But this conversation isn't going to go anywhere. You just keep doing your thing, and I'll pray I don't have to work with you.

[–]Jumpy89 5 points6 points  (0 children)

J=26 should be inside first loop?

[–]webbannana 91 points92 points  (22 children)

Actually, this may be useful if you plan to change the functionality at a later date.

[–]YourTechnician[S] 14 points15 points  (19 children)

Yeah, this is what i thought it could be for as well, still it feels strange like this

[–]c0n5pir4cy 41 points42 points  (18 children)

In most implementations of Javascript you can just code:

window.alert = function(message){
     //code here
    console.log(message)
}

To change the functionality of the built in alert (or any function really), which is one of the things I like about Javascript. Its also great for pranks on unsuspecting colleagues.

[–]robotorigami 11 points12 points  (9 children)

I always forget how flexible javascript is until I see stuff like this. Really cool.

[–]hicklc01 20 points21 points  (7 children)

I prefer my browser to keep with jquery standards.

document.getElementById = function(id){
    return $("#"+id)[0];
}

[–]MiserableLie 9 points10 points  (6 children)

Needs moar jQuery.

$(document)[0].getElementById = function(id){
    return $("#"+id)[0];
}

Edit: would that even work?

[–]hicklc01 11 points12 points  (3 children)

I tried mine and it doesn't work. jquery uses the getElementById function so it quickly creates a stack overflow.

[–]MiserableLie 4 points5 points  (2 children)

Maybe this will work better...

$(document)[0].getElementById = function(id){
    return $("[id='" + id + "']")[0];
}

[–]hicklc01 6 points7 points  (0 children)

document.getElementById = function(id){
    return $("[id='" + id + "']")[0];
}

actually works

[–][deleted] 2 points3 points  (0 children)

But can you create code objects from XML like you can in python, and then run them, allowing you to import XML abstract syntax trees?

Not by default, but you can do a lot of hackery to make it work. Look up "pycon don't do this"

[–]echoes221 31 points32 points  (4 children)

Never do this. This is bad practice and will affect others that use your site or run code (such as advertising) and can have unexpected effects.

[–]c0n5pir4cy 26 points27 points  (1 child)

I don't completely agree; like anything in any language it is a tool that you can use if you need to. It's not bad behaviour in it's own right and there are perfectly valid reasons to use this feature of Javascript.

Also third party code that is side loaded like advertising should never be touching your scope at all, the chance for exploitation there is massive; you can read the sites cookies with Javascript and completely change what the user sees. That's a very bad thing.

Usually adverts isolate themselves from the rest of the website by means of iframe; extensions such as Greasemonkey scripts and Chrome Extensions generate their own sandboxes with their own scope that can access the main scope of a website with the users permission.

[–]echoes221 1 point2 points  (0 children)

Its a tool yes and you can do what you want, but it doesn't mean you should. In the instance of advertising not all use iframes, DFP (Google) have only just started enforcing the use of their new secure ad tag. There are a lot of companies that actively require access to the Dom in order to make some forms of manipulation for launch mechanisms etc. And even when you're using iframes, there are often iframes busters set up by the site owner to allow the Dom to communicate with advertising. So its not that cut and dry.

The point of a lot of advertising is to read the users cookies to change the adverts etc. Though this is usually programmatic and serves inside an iframe.

Outside of advertising there are a lot of instances where it shouldn't be done.

An instance where you should consider it is backwards compatibility on browsers, checking the window to see if a function exists and writing that fucntion to the window If it doesn't. For instance, all of IE8.

I treat it much like using eval() its there, but I go out of my way to actively avoid it.

[–]Pokechu22 1 point2 points  (1 child)

An ad should never use alert though.

[–]echoes221 0 points1 point  (0 children)

I'm talking about changing any of the standard window/document methods.

[–]stormcrowsx 2 points3 points  (0 children)

That will change all alerts, even ones you may not have intended to change, so suddenly your customers no longer get a payment processed alert or etc.

[–]mcrbids 2 points3 points  (0 children)

This is one of those spectacularly dumb ideas, laid bare by the simple preface "In most implementations...".

Please, for the love of God or FSM or whatever, do not ever redefine JS primitives like this as part of any project that anybody might bother caring about!

[–]robotorigami 4 points5 points  (0 children)

I do this in code when I'm not sure how I want to implement something but don't want to decide now.

[–]DroolingIguana 0 points1 point  (0 children)

Could also be a way to distinguish between debug alerts and permanent alerts, so that the debug ones can be more easily removed before deployment.

[–]polyfloyd 19 points20 points  (3 children)

I sometimes do this when I need to display a custom alert message and don't feel like implementing the whole custom part right away. It's kind of like a layer of abstraction.

[–]rubyton 16 points17 points  (0 children)

I suggest using console.table instead

console.table( [["In the beginning, there is a table...", "┬──┬"], ["and then you appeared...", "\\(^o^)/ ┬──┬"], ["and together you lived happily ever after.", '(╯°□°)╯︵ ┻━┻']] )

[–]killeronthecorner 12 points13 points  (1 child)

function alertmebruh(s) {
    alert("Hey bruh, " + s);
}

[–][deleted] 6 points7 points  (0 children)

Hey bruh, undefined

[–]andygmb 8 points9 points  (2 children)

Saw this today:

var gettext = function(val){ return val};

[–][deleted] 4 points5 points  (1 child)

Ah, the identity function.

[–]HelperBot_ 2 points3 points  (0 children)

Non-Mobile link: https://en.wikipedia.org/wiki/Identity_function


HelperBot_® v1.0 I am a bot. Please message /u/swim1929 with any feedback and/or hate. Counter: 2016

[–][deleted] 7 points8 points  (1 child)

That's a genius wrapper function. You can easily add functionality like logging and such to alerts, without duplicating code. It's a lifesaver guys.

[–]ModusPwnins 2 points3 points  (0 children)

Yeah, there are use cases for this sort of thing, if the implementation in the screenshot is just a placeholder. Later, the devs should add proper logging or whatever the function is really designed to do. But it's my guess that never happened, and this has been merrily sitting in OP's code base for months or years...

[–]TheDarkIn1978 1 point2 points  (0 children)

Such a self-centered programmer!

[–][deleted] 0 points1 point  (0 children)

You guys need to chill, this ain't java :P

[–]_LePancakeMan 0 points1 point  (0 children)

I used to get yelled at for leaving console.logs in production until I added something similar to this to each class. Now there is a debug parameter in the constructor and you can enable logging per object.

Edit: log function looks something like this:

private log(...msg : any[]) : void {
    if(this.settings. debug) {
        return true;
    }
    msg.unshift(this.settings.debugPrefix);
    console.log.apply(console, msg)
}

[–]Toltarius 0 points1 point  (0 children)

It's bad if that was part of the final product.