A removed comment by Amy gives the solution. You are creating a variable named undefined
, and it doesn't work if you do your snippets in the global scope:
var undefined = 'hello';
var test = undefined;
console.log(typeof test);
But it effectively works if you do it in a local scope where undefined doesn't refer to the global variable anymore:
(()=>{
var undefined = 'hello';
var test = undefined;
console.log(typeof test);
})()
To prevent this mistake, you can use the 'use strict';
directive:
'use strict';
var undefined = 'hello';
var test = undefined;
console.log(typeof test);
If you are writing code where you can't control where it will be executed (e.g. library, embed, etc) it is a good pattern to use a IIFE which makes it so you can guarantee that undefined will always be correct/usable. Here is an example:
(function(undefined){
// undefined will equal `undefined` because we didn't pass in an argument to the IIFE
console.log(undefined); // always `undefined`, even if undefined !== `undefined`outside of the IIFE scope
})(); // No argument supplied
All my tests were made using Firefox 72.0b10 (64 bits) on Ubuntu, and the result for the first snippet may differ on an older browser.