Cannot read property ‘style’ of undefined — Uncaught Type Error

Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question. If that script executes in the <head> section of the code, document.getElementsByClassName(…) will return an empty array because the DOM is not loaded yet. You’re getting the Type Error because you’re referencing search_span[0], but search_span[0] … Read more

Create an empty object in JavaScript with {} or new Object()?

Objects There is no benefit to using new Object(); – whereas {}; can make your code more compact, and more readable. For defining empty objects they’re technically the same. The {} syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline – like so: Arrays For arrays, there’s similarly almost no benefit to ever using new Array(); over []; – … Read more

Length of a JavaScript object

Updated answer Here’s an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes: This doesn’t have to modify any existing prototype since Object.keys() is now built-in. Edit: Objects can have symbolic properties that can not be returned via Object.key method. So … Read more

Check if a value is an object in JavaScript

UPDATE: This answer is incomplete and gives misleading results. For example, null is also considered of type object in JavaScript, not to mention several other edge cases. Follow the recommendation below and move on to other “most upvoted (and correct!) answer”: Original answer: Try using typeof(var) and/or var instanceof something. EDIT: This answer gives an idea of how to examine variable’s properties, but … Read more

How to iterate over a JavaScript object?

For most objects, use for .. in : With ES6, if you need both keys and values simultaneously, do To avoid logging inherited properties, check with hasOwnProperty : You don’t need to check hasOwnProperty when iterating on keys if you’re using a simple object (for example one you made yourself with {}). This MDN documentation explains more generally how to deal with objects … Read more

How can I merge properties of two JavaScript objects dynamically?

ECMAScript 2018 Standard Method You would use object spread: merged is now the union of obj1 and obj2. Properties in obj2 will overwrite those in obj1. Here is also the MDN documentation for this syntax. If you’re using babel you’ll need the babel-plugin-transform-object-rest-spread plugin for it to work. ECMAScript 2015 (ES6) Standard Method Method for ES5 and Earlier Note that this will simply add all attributes of obj2 to obj1 which … Read more