JavaScript: functions, arrays and objects

The three ways of writing a function, default parameters, array methods (map, filter, reduce, slice, splice…) and objects, copied by reference.

  • 27 cards
  • 3 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link

A few cards from the deck

  • Arrow function: what is it?

    Show the answer

    A short way of writing a function with an arrow, such as x => x * 2, where the expression's value is returned automatically when there are no braces.

    With braces, return is required: x => { x * 2 } returns nothing (undefined). It is the most common slip.

  • What do a and c hold at the end?

    ```javascript
    const a = [1, 2, 3];
    const b = a;
    b.push(4);
    const c = a.map(x => x * 2).filter(x => x > 4);
    `

    • a = [1, 2, 3, 4] and c = [6, 8]
    • a = [1, 2, 3] and c = [6, 8]
    • a = [1, 2, 3, 4] and c = [6]
    • a = [1, 2, 3] and c = [8]
    Show the answer

    a = [1, 2, 3, 4] and c = [6, 8]

    b = a does not copy: both names refer to the same array, so push on b changes a. Then map gives [2, 4, 6, 8] and filter keeps what exceeds 4: [6, 8].

  • An object property is read with … notation, such as client.nom, or with … notation, such as client['code-postal'], which is needed when the name is not a valid identifier.

    Show the answer

    An object property is read with dot notation, such as client.nom, or with bracket notation, such as client['code-postal'], which is needed when the name is not a valid identifier.

    Brackets also accept a variable: client[field]. A missing property gives undefined, with no error.

  • Default parameter: what is it?

    Show the answer

    A value written in a function's declaration, used when the call gives no argument or gives undefined.

    With function double(n = 2), double() and double(undefined) give 4, but double(null) gives 0: null is a value that was provided.

  • What does this program print?

    ```javascript
    const items = [{ prix: 10 }, { prix: 5 }];
    console.log(items.map(i => { i.prix }));
    `

    • [ 10, 5 ]
    • [ undefined, undefined ]
    • [ { prix: 10 }, { prix: 5 } ]
    • undefined
    Show the answer

    [ undefined, undefined ]

    With braces, the arrow function has a function body: without return, it returns undefined on every turn. Write i => i.prix or i => { return i.prix }.