php vs js
I find php interesting. It’s more terse and expansive than my favorite language; javascript. It reminds me of VB6 a lot; tons of built ins and keywords.
subtle syntax differences continue to frustrate me.
I am torn as to which one is a “better” language. While PHP gives you a lot of
functions to use, javascript aims for minimalism.
PHP seems to require more code to do the same thing as javascript.
this is a result of valuing functions over methods.
i am glad i learned javascript in detail first, because i know what i am missing.
consider an example function, the string reverse procedure.
function reverse($string) {$newstring = "";
for($i = strlen($string); $i > 0; $i--) {$newstring .= $string[$i-1];
}
return $newstring;
}
This is very close to the same procedure in VBA, which a computer science professor demonstrated to me.
So, it seems that this is “the way” to do this. Indeed, with two minor adjustments, the function runs in javascript, giving the output expected:
function reverse($string) {$newstring = "";
for($i = $string.length; $i > 0; $i--) { $newstring += $string[$i-1];}
return $newstring;
}
so, i would not blame anyone for thinking this is a good way to do it in javascript. but it’s not. String concatenation is slow, requiring the string be rebuilt each append. Omitting a var statement creates globals that leak out of the function. Finally, and perhaps this is status quo, but the code is lengthy for what i am used to.
prototypes reduce code length. a lot.
compare a JS-only version of the same function:
function reverse(s) { return s.split("").reverse().join("");}faster to write, faster to execute, less overhead and ram also…
prototypes not only reduce code length, they are easier to program as well.
the code to the right of each dot describes a transformation to be applied to the value left of the dot. The same variable is reused throughout.
this also make it easier to modify.
if i want to also convert the output to UPPERCASE, in php i would need to wrap a function around the output. This forces me to use the mouse or several arrow key presses, balance params, and make changes to two locations.
in js, i can simply add another dot in the middle of the prototype chain, in one location, without balancing or extra keystrokes:
s.toUpperCase().split("").reverse().join(""); i don’t consider this simplistic (though it might be), i consider this concise.