What is the difference between imperative programming and declarative

    Background


    Not so long ago I was in an active job search and browsed a bunch of sites with vacancies / projects. On some of them, “passing” questions can be viewed even before the response.

    Most were quite ordinary, such as “how many years have you been using the X framework?”, But one seemed interesting to me (I even responded there, but # didn’t).

    This was actually a question from the title. And I decided to figure it out. And the best way to understand is, as you know, to explain. So welcome to cat.

    What are the differences?


    In order to describe the differences, you must first understand what it is in principle. In a free retelling.

    Imperative style


    This is a programming style in which you describe how to achieve the desired result. For example, I write:

    - put a frying pan on the fire;
    - take two eggs (chicken);
    - stab with each knife;
    - pour the contents into the pan;
    - throw out the shell;
    ...

    This is a declarative style, but with an admixture of imperative.

    Declarative style


    This is the style in which you describe what kind of result you need.

    Then I just write:

    - prepare the scrambled eggs

    And the recipient of such a message already understands himself what steps should be taken for this.

    Why is the example from the part about imperative actually mixed with declarativeness? Well, at least because the recipient must know what a pan and eggs are.

    JS example


    My favorite example is this: an array of numbers is given, you need to write a function that returns an array of numbers, where each number from the original array doubles. Those. [1, 2, 3] -> [2, 3, 6]

    Imperative style:

    function double (arr) {
      let results = [];
      for (let i = 0; i < arr.length; i++){
        results.push(arr[i] * 2);
      }
      return results;
    }
    

    Declarative style:

    function double (arr) {
      return arr.map((item) => item * 2);
    }
    

    All high-level programming languages ​​allow you to write in a mixed style and, in fact, even these two examples do not show a clear separation.

    It is probably right to call one style “more declarative,” and the other “more imperative.”

    Also popular now: