JavaScript: variables, types and equality

let, const and var with their scope, primitive types and typeof, implicit conversions, == versus === and the falsy values.

  • 24 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

  • let and const: what is it?

    Show the answer

    The two modern variable declarations, limited to the block where they are written; the first allows reassigning, the second forbids it.

    const freezes the link between the name and the value, not the content: const t = []; t.push(1) works, t = [] causes TypeError: Assignment to constant variable.

  • What does this program print?

    ```javascript
    console.log(typeof (1 + '2'), typeof ('3' * '4'), typeof null);
    `

    • string number object
    • number number null
    • string string object
    • string number null
    Show the answer

    string number object

    1 + '2' concatenates and gives the string '12'. '3' * '4' converts to numbers and gives 12. typeof null is 'object', a historical error kept so as not to break the web.

  • JavaScript's primitive types are string, number, boolean, undefined, null, symbol and …; everything else (arrays, functions, objects) is of type …, a function being a callable object, even though typeof answers 'function' for it.

    Show the answer

    JavaScript's primitive types are string, number, boolean, undefined, null, symbol and bigint; everything else (arrays, functions, objects) is of type object, a function being a callable object, even though typeof answers 'function' for it.

    A primitive value cannot be changed: a method such as toUpperCase() returns a new string. An object, however, is changed in place.

  • var: what is it?

    Show the answer

    The old variable declaration, limited to the function and not the block, which exists (holding undefined) before its declaration line.

    A var written inside an if stays visible after it, which hides bugs. With let, reading q before the line let q = 1; raises ReferenceError: Cannot access 'q' before initialization.

  • What happens when this program runs?

    ```javascript
    const prix = 10;
    prix = 12;
    console.log(prix);
    `

    • It prints 12, since const only forbids changing the type
    • It stops at line 2 with TypeError: Assignment to constant variable.
    • It prints 10, line 2 being ignored without an error
    • It does not start: SyntaxError as soon as the file is read
    Show the answer

    It stops at line 2 with TypeError: Assignment to constant variable.

    Reassigning a constant is a runtime error, not a syntax error: line 1 runs, line 2 throws. For a value that must change, declare it with let.