1

This code does not pass the test

Functions:

function setTheme(theme) {
    chartTheme = theme;
}

function getTheme() {
    if (typeof chartTheme === undefined) {
        chartTheme = 'dark';
    }
    return chartTheme;
}

Test:

it('If theme is undefined, expect dark', function() {
    ChartFactory.setTheme(undefined);
    expect(ChartFactory.getTheme()).to.equal('dark');
});

enter image description here

However this does past the test, if I check for "undefined" as a string.

function getTheme() {
    if (typeof chartTheme === 'undefined') {
        chartTheme = 'dark';
    }
    return chartTheme;
}
Leon Gaban
  • 36,509
  • 115
  • 332
  • 529

1 Answers1

2

First of all see Which equals operator (== vs ===) should be used in JavaScript comparisons?

You're using Strict equality operator with undefined. Strict equality check for both the type and value to be equal.

typeof returns string.

Thus,

typeof chartTheme === 'undefined'

returns true.


In other words,

undefined !== 'undefined'

but,

undefined == 'undefined'.
Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Thanks, I guess what I don't understand still is that `undefined` by itself is a type! Guess my code converted the `undefined` passed into the function to a string. Oh well I also just updated my code much more simply with these basic default checks: `theme = theme || 'dark';` – Leon Gaban May 17 '16 at 15:33
  • @LeonGaban Because the value of the variable is not actually defined. So, there should be some value which can tell this. Also, you can use ES6's default parameters as `function setTheme(theme = 'dark') {` instead of `|| 'dark'`. – Tushar May 17 '16 at 15:35
  • Thanks on that ES6 tip! I just tried it tho, but got this error in the terminal `PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR SyntaxError: Expected token ')'` I guess I need some kind of Babel interpreter? – Leon Gaban May 17 '16 at 15:38
  • @LeonGaban probably. Most of the modern browsers support this syntax. See https://kangax.github.io/compat-table/es6/ – Tushar May 17 '16 at 15:39