Skip to content

Instantly share code, notes, and snippets.

@sagarkarira
Last active August 27, 2016 11:02
Show Gist options
  • Select an option

  • Save sagarkarira/70251f4a87a6a8247fafa717e0ebe0ce to your computer and use it in GitHub Desktop.

Select an option

Save sagarkarira/70251f4a87a6a8247fafa717e0ebe0ce to your computer and use it in GitHub Desktop.
Fundamentals on typeof and data types in JS
/** So this one is simple. Object are object */
var obj = {};
console.log(obj); //{}
console.log(typeof(obj)); //object
/** Doubt-1 Why does JS returns typeof of function as function.
All functions are objects in JS. Look ahead.
Doubt -2 Why it doesn't print {[Function]} ?
Doubt -3 Are not object have key value pair ? value of function object is [Function] but what is the key ?
*/
var foo = function() {};
console.log(foo); //[Function]
console.log(typeof(foo)); //function
/** I can assign any propery to foo function I told you is an object. */
foo.undef = undefined;
console.log(typeof(foo.undef)); //undefined
/** Assigining null property to foo which is null and which we know is object. */
foo.null = null;
console.log(typeof(foo.null)); //object (Long running JS bug should be null )
/** Assigining arr property to which is an empty array. And array are object too. */
foo.arr = ['Array'];
console.log(typeof(foo.arr)); //object
foo.obj = {};
console.log(typeof(foo.obj));
foo.var = 5;
console.log(typeof(foo.var)); //number
foo.str = "5";
console.log(typeof(foo.var)); //string
foo.bool = true;
console.log(typeof(foo.bool)); //boolean
console.log(foo);
/**
{ [Function]
undef: undefined,
null: null,
arr: ['Array'],
obj: {},
var: 5,
str: '5',
bool: true }
*/
console.log(typeof(foo)); //function
/** Finding key of the object foo */
for (var key in foo) {
console.log("Key of " + foo[key] + " having typeof " + typeof((foo[key])) + " has value " + foo[key] );
}
/**
Key of undefined having typeof undefined has value undefined
Key of null having typeof object has value null
Key of Array having typeof object has value Array
Key of [object Object] having typeof object has value [object Object]
Key of 5 having typeof number has value 5
Key of 5 having typeof string has value 5
Key of true having typeof boolean has value true
*/
/** Doubt -4 function has no key */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment