-1

I am doing an exercise about imperative vs declarative. Unfortunately I don't understand the example or I don't get any results. "Uncaught ReferenceError: range is not defined"

'use strict'
// imperative
let numbers = range(10)
let evenNumbers = []
for (let i = 0; i < numbers.length; i += 1) {
    if (numbers[i] % 2 === 0) {
        evenNumbers.push(numbers[i])
    }
}
console.log(evenNumbers) // => [0, 2, 4, 6, 8]

and:

// declarative
range(10).filter(v => v % 2 === 0) // => [0, 2, 4, 6, 8]
C3PO
  • 13
  • 6

1 Answers1

1

It seems you come from a Python or PHP background, but JavaScript does not have a global range()-function. See this post for an alternative.

Edit: A simple solution in this case would simply be to write:

let numbers = [0,1,2,3,4,5,6,7,8,9]

Sure, it's a bit verbose, but it's also very easy to read, and in a small case like this, it's not problematic. If the purpose of the exercise was the difference between imperative and declarative programming, range(2) vs [0,1,2] should not matter.

Sebastian
  • 1,321
  • 9
  • 21
  • This code from above is in my learning script. Just like that. I've been learning Javascript for 4 weeks. But it totally frustrates me when I don't understand things. Or if you think it makes no sense. – C3PO Mar 25 '21 at 11:03
  • 1
    Could it be that there is a function-definition for `range()` somewhere else? It's not a difficult function to implement, so it could certainly be that a lecturer defined it globally to simplify for the class. As it stands now, no it doesn't make sense, because as you say "`range is not defined`". – Sebastian Mar 25 '21 at 11:06
  • 1
    The example actually related them to another. But it was not evident. Thanks for the help. – C3PO Mar 25 '21 at 13:23
  • 1
    Happy to help! If my answer solved your problem, feel free to accept it as the "right answer" :) Good luck going forward! – Sebastian Mar 25 '21 at 13:43