Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
qntm
Jun 17, 2009
Let me back up a little and make sure I know what you're saying.

Subjunctive posted:

Function declarations are hoisted, while the assignment of a function expression's result to a variable only occurs when that line of code is reached. Assigning an anonymous expression result requires the developer to think about the ordering of their source in a way that simple declarations don't.

By this, are you referring to the fact that

JavaScript code:
(function() {
    fib(56);

    function fib(n) {
        // ...
    }
}());
works, but

JavaScript code:
(function() {
    fib(56);

    var fib = function(n) {
        // ...
    }
}());
doesn't?

Adbot
ADBOT LOVES YOU

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/

This is a pretty good article on why hoisting does what it does.

Space Whale
Nov 6, 2014
I'm a full stack web guy who basically uses JS to glue libraries as much as possible, since I like C# so drat much. I finally get to the point where I do a little JS, and I promptly pick my jaw up off the floor, since you can't overload functions.

Now that I've stopped the room from spinning, what's the way in which we null check our arguments? Is it just if (param) or do we go if (param === null) or does it depend on which browser? :gonk:

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Space Whale posted:

I'm a full stack web guy who basically uses JS to glue libraries as much as possible, since I like C# so drat much. I finally get to the point where I do a little JS, and I promptly pick my jaw up off the floor, since you can't overload functions.

Now that I've stopped the room from spinning, what's the way in which we null check our arguments? Is it just if (param) or do we go if (param === null) or does it depend on which browser? :gonk:

Depends on what you're expecting. Often you're just checking whether things are false-y, so you can just say if (param) {. If you're expecting false-y input, then check for null with ===. You can also do something like
JavaScript code:
function doStuff(a, b, c) {
  //a & b required
  c = c || 'safe default';
}
as long as a valid c can't be false-y.

obstipator
Nov 8, 2009

by FactsAreUseless
^^^ that

Also if you want to check specifically that something hasn't been defined at all:
if(typeof thing == 'undefined')

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

qntm posted:

Let me back up a little and make sure I know what you're saying.


By this, are you referring to the fact that

JavaScript code:
(function() {
    fib(56);

    function fib(n) {
        // ...
    }
}());
works, but

JavaScript code:
(function() {
    fib(56);

    var fib = function(n) {
        // ...
    }
}());
doesn't?

Yes, but also that if you have two functions a and b that call each other, then

JavaScript code:
function a() { if (cond) b(); }

a(); // called after a is defined, I should be ok right?

function b() { }
works, but the equivalent using function expressions doesn't. This means that you need to keep your functions in a strict order reflecting their dependency graph, unlike pretty much everything but pre-ANSI C, or else put all top-level code (other than the assignment of expressions in lieu of function declarations) after all function assignments.

qntm
Jun 17, 2009
E: never mind

qntm fucked around with this message at 01:46 on May 30, 2015

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Space Whale posted:

you can't overload functions.

Yeah, JavaScript is not C#

obstipator posted:

if(typeof thing == 'undefined')

Or just if(thing === undefined)

edit:

Space Whale posted:

if (param === null) or does it depend on which browser? :gonk:

If you're going that route, check against undefined, not null.

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

Space Whale posted:

I'm a full stack web guy who basically uses JS to glue libraries as much as possible, since I like C# so drat much. I finally get to the point where I do a little JS, and I promptly pick my jaw up off the floor, since you can't overload functions.

Now that I've stopped the room from spinning, what's the way in which we null check our arguments? Is it just if (param) or do we go if (param === null) or does it depend on which browser? :gonk:

Are you trying to "fake" overloading by checking if certain parameters are null? Because you probably shouldn't do that.

Sedro
Dec 31, 2008

Wheany posted:

Or just if(thing === undefined)
If thing was (possibly) never declared you can use typeof thing :eng101:

Space Whale
Nov 6, 2014

HappyHippo posted:

Are you trying to "fake" overloading by checking if certain parameters are null? Because you probably shouldn't do that.

What I was trying to do was call a resource in AngularJS with no params to just do /foo/api/bar/GET/, and with param it would do /foo/api/bar/GET/?preDefinedParam="baz".

What should I be doing?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Space Whale posted:

What I was trying to do was call a resource in AngularJS with no params to just do /foo/api/bar/GET/, and with param it would do /foo/api/bar/GET/?preDefinedParam="baz".

What should I be doing?

code:
function thing(param){
  var url = '/whatever/';
  url += (param) ? 'something' : '';
  // do stuff with url
}

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

Space Whale posted:

What I was trying to do was call a resource in AngularJS with no params to just do /foo/api/bar/GET/, and with param it would do /foo/api/bar/GET/?preDefinedParam="baz".

What should I be doing?

It's hard to give specific advice without knowing more about what you're doing, but in general you factor out common operations into a separate function and then write two functions to call it:

code:
function doStuffWithUrl(url) {
	// common stuff that might happen
	doTheThing(url);
	//.. other stuff?
}

var baseUrl = "/foo/api/bar/GET/";
function doStuff() {
	doStuffWithUrl(baseUrl);
}
function doStuffWithParam(param) {
	doStuffWithUrl(baseUrl + "?preDefinedParam=" + param.toString());
}
Although javascript will allow you to call a function without passing in all the parameters defined in its signature (and will set the missing parameters to undefined), I would avoid using this "feature." You're basically forcing anyone using your function to read the implementation in order to understand that they can in fact omit certain parameters all for a pretty dubious benefit, IMO.

In a more complex scenario you can use a sort parameters object pattern, which works well with javascript's object literals. Basically you make the function so that you call it like this:
code:
someFunction({aParameter: 15, anotherParameter: "blah"});
I would only use this sparingly (again, you're relying on the user having to understand the implementation to a degree), but in certain situations it can be a good approach.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

HappyHippo posted:

You're basically forcing anyone using your function to read the implementation in order to understand that they can in fact omit certain parameters all for a pretty dubious benefit, IMO.
[...]
I would only use this sparingly (again, you're relying on the user having to understand the implementation to a degree), but in certain situations it can be a good approach.

Look, I know this is JavaScript and we're all agile rockstars/cowboys/ninjas here, but you could also document your interfaces.

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

Wheany posted:

Look, I know this is JavaScript and we're all agile rockstars/cowboys/ninjas here, but you could also document your interfaces.

Of course you can and should, but it's always better to reduce the number of places where confusion or inconsistency can seep in. Especially since you don't gain anything by trying to emulate function overloading in a language where it really doesn't work.

obstipator
Nov 8, 2009

by FactsAreUseless
The concept of sending an object for arguments can actually be a really good idea if you have a lot of optional parameters to pass along. Ruby programmers tend to rave about this a lot.

WrathOfBlade
May 30, 2011

Yeah, I'm a big fan of making functions more dynamic by throwing in an "options" object as a parameter. Declaring a dozen mostly-identical permutations of a function can be a headache in its own right, especially when it comes to inventing/remembering names for all of them.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
design better apis so that doesn't happen?

WrathOfBlade
May 30, 2011

Suspicious Dish posted:

design better apis so that doesn't happen?

You want to elaborate on that at all?

ExcessBLarg!
Sep 1, 2001

obstipator posted:

The concept of sending an object for arguments can actually be a really good idea if you have a lot of optional parameters to pass along. Ruby programmers tend to rave about this a lot.
Ruby has straight-up keyword arguments (as opposed to just supporting an implicit options hash) since 2.0. I think R is probably the best example of the flexibility (and necessity) of optional keyword arguments. Some of the plotting functions have like 20 optional arguments.

WrathOfBlade posted:

You want to elaborate on that at all?
Fluent interfaces are a reasonable alternative.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



HappyHippo posted:

Of course you can and should, but it's always better to reduce the number of places where confusion or inconsistency can seep in. Especially since you don't gain anything by trying to emulate function overloading in a language where it really doesn't work.

You get an interface that's more idiomatic/familiar to the average JS developer which isn't nothing.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

WrathOfBlade posted:

You want to elaborate on that at all?

Give methods that do different things different names, and not just different signatures?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
if you really need eight dozen permutations of simple parameters, you need to rethink your api surface and what you really want to expose to consumers

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

Munkeymon posted:

You get an interface that's more idiomatic/familiar to the average JS developer which isn't nothing.

Since when is faking function overloading more idiomatic?

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



HappyHippo posted:

Since when is faking function overloading more idiomatic?

Since jQuery became popular as far as I can tell.

E: come to think of it, several classes and methods in the spec do different things based on what you pass to them as well, so it was pretty well established before jQ.

Munkeymon fucked around with this message at 21:39 on Jun 1, 2015

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Munkeymon posted:

Since jQuery became popular as far as I can tell.

E: come to think of it, several classes and methods in the spec do different things based on what you pass to them as well, so it was pretty well established before jQ.

If you don't count cases where there are simply optional parameters, then there aren't very many that I can think of. One of them is my fault. :blush:

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Subjunctive posted:

If you don't count cases where there are simply optional parameters, then there aren't very many that I can think of. One of them is my fault. :blush:

I'm counting optional parameters in with fake function overloading since that's basically the same thing depending on what other language you're comparing JS to.

huhu
Feb 24, 2006
code:
for(var i = myArray.length - 1; i >= 0; i--){
  myNewArray.push(myArray[i]);
}
Is there a lazier way to write myArray.length - 1?

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

huhu posted:

code:

for(var i = myArray.length - 1; i >= 0; i--){
  myNewArray.push(myArray[i]);
}
Is there a lazier way to write myArray.length - 1?

Lazier than writing it?

huhu
Feb 24, 2006

Subjunctive posted:

Lazier than writing it?

Is "lazy" not the word for why stuff like i++ exists? I'd prefer not to have to write -1 if possible. I feel like there's a better way to write it.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
nope, just write -1.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

huhu posted:

Is "lazy" not the word for why stuff like i++ exists? I'd prefer not to have to write -1 if possible. I feel like there's a better way to write it.

Sorry, I thought we were in another thread and you were making fun of something in the code, and I didn't understand why.

Code looks good, if you have to iterate downward.

ExcessBLarg!
Sep 1, 2001

huhu posted:

Is "lazy" not the word for why stuff like i++ exists?
"i++" exists because it's a distinct operator (post-increment) and in compiled languages (e.g., C) often translates to an increment instruction in assembly. Modern C compilers should observe that "i+=1" and even "i=i+1" are the same thing and optimize them accordingly, but this wasn't always the case. It exists in JavaScript because of it's prevalence and familiarity to users of C-family/inspired languages.

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

ExcessBLarg! posted:

"i++" exists because it's a distinct operator (post-increment) and in compiled languages (e.g., C) often translates to an increment instruction in assembly. Modern C compilers should observe that "i+=1" and even "i=i+1" are the same thing and optimize them accordingly, but this wasn't always the case. It exists in JavaScript because of it's prevalence and familiarity to users of C-family/inspired languages.
It also makes more sense if you understand that there's also a pre-increment operator (++i) and the two are used differently. Where the post-increment operator evaluates to the value of the variable before modification, then increments the variable, the pre-increment operator does the reverse, incrementing before it evaluates to the updated value. In other words, these two are algorithmically identical:

code:
i = 0;
a[i] = 42;
i = i + 1;

--

i = 0;
a[i++] = 42;
versus the pre-increment operator:

code:
i = 0;
i = i + 1;
a[i] = 42;

--

i = 0;
a[++i] = 42;

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

huhu posted:

Is "lazy" not the word for why stuff like i++ exists? I'd prefer not to have to write -1 if possible. I feel like there's a better way to write it.

You want to access the last index of your array, and that number is always 1 less than the length, because the first item has an index of 0. The -1 is always there because it's the way you convert between the two ways of counting

There might be something else you can use in JavaScript (some kind of getLastIndex function) but the way you've done it is pretty standard in programming, and it's lightweight too

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

In this case you could write it as a reduce/fold too.

JavaScript code:

var newArray = oldArray.reduceRight([], function (accum, value) {
    accum.push(value); return accum;
});

or copy with slice and then reverse.

(Phone posting, code might not be exact.)

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Clearly this is a scenario for the "goes to" operator:

code:
var i = arr.length
while(i --> 0)
  doThing(i)

don't actually do this

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:
wrong thread

Tad Naff fucked around with this message at 07:26 on Jun 4, 2015

MasterSlowPoke
Oct 9, 2005

Our courage will pull us through
Looks like deep paranoia level sanitizing. Isn't Java strongly typed?

Adbot
ADBOT LOVES YOU

necrotic
Aug 2, 2005
I owe my brother big time for this!

MasterSlowPoke posted:

Looks like deep paranoia level sanitizing. Isn't Java strongly typed?

Yes. Javascript is not, though. Guess you were referring to the now-removed post above?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply