ferrosin.blogg.se

Elements of programming interviews javascript
Elements of programming interviews javascript













elements of programming interviews javascript

Or, if you’re using jQuery: console.log((bar != null) & (typeof bar = "object") & (! $.isArray(bar))) ĮS5 makes the array case quite simple, including its own null check: console.log(Array.isArray(bar)) However, there’s one other alternative that returns false for nulls, arrays, and functions, but true for objects: console.log((bar != null) & (bar.constructor = Object))

elements of programming interviews javascript

In most cases, this is the desired behavior, since arrays are indeed objects, but in situations where you want to also false for arrays, you could amend the above solution to be: console.log((bar != null) & (typeof bar = "object") & (toString.call(bar) != "")) Second, the above solution will return true if bar is an array (e.g., if var bar = ). In most cases, this is the desired behavior, but in situations where you want to also return true for functions, you could amend the above solution to be: console.log((bar != null) & ((typeof bar = "object") || (typeof bar = "function"))) To be entirely thorough in our answer, there are two other things worth noting:įirst, the above solution will return false if bar is a function.

#ELEMENTS OF PROGRAMMING INTERVIEWS JAVASCRIPT CODE#

Therefore, the following code will, to the surprise of most developers, log true (not false) to the console: var bar = null Ĭonsole.log(typeof bar = "object") // logs true!Īs long as one is aware of this, the problem can easily be avoided by also checking if bar is null: console.log((bar != null) & (typeof bar = "object")) // logs false Although typeof bar = "object" is a reliable way of checking if bar is an object, the surprising gotcha in JavaScript is that null is also considered an object!















Elements of programming interviews javascript