views:

210

answers:

4

The main issue I'm thinking about is whether assigning a variable in an if statement is safe and reliable across different browsers. If it is safe, I'd like to use it.

Here it reads the querystring and if the querystring variable SN is either Twitter or Facebook then it enters the if and you can use the variable, if the querystring variable doesn't exist or is some other value then it goes into the else.

    if(socialNetwork = (window.location.search.indexOf("SN=Twitter") > 0) ? "Twitter" : ((window.location.search.indexOf("SN=Facebook") > 0) ? "Facebook" : null))
    {
        alert(socialNetwork);
    }
    else
    {
        alert("nope");
    }
+5  A: 

It is part of the language design and should work in every browser, but it's very difficult to read.

SLaks
+4  A: 

That's ugly.

var uselessSocialNetworkingApp = window.location.search.replace(/.*\bSN=(\w+)\b.*/, "$1");
if (uselessSocialNetworkingApp)
  alert("yay!");
else
  alert("no");

It's kind-of funny that there'd be that hideous construction in the "if" header, but that it'd be an "if" instead of a "? :" expression inside the "alert" argument list :-)

Also, to be at least slightly sympathetic to the intended style, this is an example of what the "let" statement in ultra-modern Javascript is for.

Pointy
Thanks! That is a lot cleaner.
Adam
A: 

Oh my! This is valid and should always work, assuming that you create the socialNetwork variable elsewhere, don't ever create implied globals. However, this is really a strange way to solve your problem. Why not create a function that returns the social network to abstract this a little?

That said, if you really want a one line solution, how about this?:

alert(function(){ var m = /SN=([A-Za-z]+)/.exec(window.location.search); return (m ? m[1] : null)}());
ysaw
Well it does cut down excess characters being sent over the internet by like 5 bytes. For production, I think it is perfectly fine, but for development I would suggest proper coding
WarmWaffles
A: 
location.socialNetwork== (function(){
 var s= location.search || '';
 s= /SN=([a-zA-Z]+)/.exec(s) || [];
 return s[1] || null;

})()

alert(location.socialNetwork)
kennebec