DEV Community

Discussion on: Functional Programming in Javascript - Imperative and Declarative

Collapse
 
pentacular profile image
pentacular • Edited

I don't think this is declarative programming.

I think that what you're describing is a combination of procedural abstraction and a tacit (point free) style.

Here's your example of imperative.

var string = "hi there , I'm a web developer";
var removeSpace = "";
for (var i = 0; i < i.string.length; i++) {
  if (string[i] === " ") removeSpace += "-";
  else removeSpace += string[i]; 
}

And here's your example of declarative.

const string = "Hi there, I'm a web developer ";
const removeSpaces = string.replace(//g,"-");
console.log(removeSpaces);

But let's take your first example and wrap it in a procedure and consider the difference.

const removeSpaces = (string) => {
  var removeSpace = "";
  for (var i = 0; i < i.string.length; i++) {
    if (string[i] === " ") removeSpace += "-";
    else removeSpace += string[i]; 
  }
  return removeSpace;
};

const string = "Hi there, I'm a web developer ";
const result = removeSpaces(string);
console.log(result);

All that's happened here is that we've wrapped the 'imperative' code up in a procedure, and the claim is that this has made it 'declarative'.

Which means that your definition of 'declarative' is really just 'using procedural abstraction to obscure the imperative implementation'.

The definition you give is:

Now talking of Declarative, its when your application is structured in a way that prioritizes describing what should happen over defining how it should happen.

Which also describes procedural abstraction.

Instead of saying "Do A, then B, then C, then D", you're saying "Do X (where X is 'look up the instructions, and then do A, then B, then C, then D)" -- there's really no fundamental difference here at all -- they're equally imperative, one just has a bit more abstraction than the other.

Declarative programming is programming by making declarations, rather than issuing instructions.

For example we might declare

X is an even integer.
X is larger than five.
X is smaller than seven.

and then the computer could figure out that X must be six.

I think the following lecture from Berkeley gives a good summary of the differences.

inst.eecs.berkeley.edu/~cs61a/sp14...

Collapse
 
pramila_15 profile image
Pramila Dalavai

Thanks for pointing out

Collapse
 
pentacular profile image
pentacular

You're welcome.