Can anyone explain to me this JavaScript code that define some variables and loop through them?
-
I'm following this tutorial: http://vimeo.com/16961179 that teaches you how to make views and partials with http://expressjs.com/: var products = [ { id: 1, name : 'Mac Book Pro', description: 'Apple 13 inch Mac Book Pro notebook', price: 1000 }, { id: 2, name : 'iPad', description: 'Apple 64GB 3G iPad', price: 899 } ]; module.exports.all = products; module.exports.find = function(id) { id = parseInt(id, 10); var found = null; productloop: for(product_index in products) { var product = products[product_index]; if (product.id == id) { found = product; break productloop; } }; return found; } In the tutorial, the author doesn't explain much this part. I'm specially confused about the loop part. Can anyone explain it to me (I'm a JavaScript beginner)? I understand the products variable at the top, but it seems like an array which has other arrays inside it.
-
Answer:
The function searches for a product by product id. The loop sets product to each product in the product array, sequentially. It compares that product's id to the one passed in to the function. If it's equal, it breaks out of the loop (yay goto) and returns the product (truthy). If it exits the loop normally, that means the product was never found, and it will return null (falsey).
alexchenco at Stack Overflow Visit the source
Other answers
Would it be more readable for you expressed thus: var products = [ { id: 1, name : 'Mac Book Pro', description: 'Apple 13 inch Mac Book Pro notebook', price: 1000 }, { id: 2, name : 'iPad', description: 'Apple 64GB 3G iPad', price: 899 } ]; module.exports.all = products; module.exports.find = function(id) { var i, product, nProducts = products.length; id = parseInt(id, 10); for(i = 0; i < nProducts; ++i) { product = products[i]; if (product.id === id) { return product; } } return null; }
Tom
First of all, it's awful code. It could break down at the slightest change. Let's start with the first line. var products = [ Declares a variable in a global context. Try to avoid this. Everything that happens in a global context, can break down. In addition, encapsulation of data helps to increase the modularity of the code, which in turn allows you to reuse code. Let's look at the function find(): module.exports.find = function(id) { id = parseInt(id, 10); var found = null; productloop: for(product_index in products) { var product = products[product_index]; if (product.id == id) { found = product; break productloop; } }; return found; } In JavaScript, blocks do not introduce a scope. There is only function-scope. A variable introduced anywhere in a function is visible everywhere in the function. JavaScript's blocks confuse experienced programmers and lead to errors because the familiar syntax makes a false promise. So this (var product = products[product_index];) declaration does not actually declare a new variable each iteration. Next. product.id == id The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors. In case of function find() operator == does not lead an error, but this is the place where the error may appear when you change the code. Always use === operator. for(product_index in products) The for in statement allows for looping through the names of all of the properties of an object. Unfortunately, it also loops through all of the properties that were inherited through the prototype chain. This has the bad side effect of serving up method functions when the interest is in data properties. If a program is written without awareness of this situation, then it can fail. The body of every for in statement should be wrapped in an if statement that does filtering. It can select for a particular type or range of values, or it can exclude functions, or it can exclude properties from the prototype. For example, for (name in object) { if (object.hasOwnProperty(name)) { .... } } In your code 'products' is an array, so you can be sure that it has no extra properties. But! Products is global variable, so in reality it can be anything. I'm a little rewrite the function and explain what this code does. module.exports.find = function(id) { var found = null, product; id = parseInt(id, 10); for (product_index in products) { if (products.hasOwnProperty(product_index)){ product = products[product_index]; if (product.id === id) { found = product; break; } } }; return found; } It's simple. The function takes a product ID as an argument (function(id)), turns it into a number (id = parseInt(id, 10);). Then runs through an array of products one by one with a loop (for(product_index in products)), checking the equality of passed to the function identifier and the identifier of the current product (if (product.id == id)). If they are equal, stops iterate (break;), assign the value of current product to the variable "found" (found = product;) and return the result to the caller of the function (return found;). P.S. I really hardly know English, so please forgive me for possible mistakes.
Microfed
Products is an array containing two objects. Some people might call them "associative arrays" but they are just objects. They have 'properties' (like an id) and 'values': var products = [{ id: 1, name : 'Mac Book Pro', description: 'Apple 13 inch Mac Book Pro notebook', price: 1000 },{ id: 2, name : 'iPad', description: 'Apple 64GB 3G iPad', price: 899 }]; module.exports is the object that your node program will actually see when you do require('./products.js'): module.exports = { // just pass along the whole array all: products, // method to find a product by id find: function(id){ return products.filter(function(product){ return product.id == id })[0] // we return the first element, at index zero } } I replaced the for in loop with the https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter, should make things clearer here. It will loop over the products array and execute the function for each of them - if the result is true, the item is added to the result, otherwise it's ignored. This is what using this module should look like using Express: var products = require('./products.js') app.get('/products', function(req, res){ // get the whole products array products.all // render page... }) app.get('/products/:id', function(req, res){ // get product with id ':id' from URL (http://mysite.com/products/25) var p = products.find(req.params.id) // render page... })
Ricardo Tomasi
Related Q & A:
- How to encrypt JavaScript code?Best solution by Stack Overflow
- Can anyone give me the code for toshiba tv with the URC22B?Best solution by Yahoo! Answers
- Can anyone explain this dream to me?Best solution by Yahoo! Answers
- Can anyone help me get the code for my stereo?Best solution by Yahoo! Answers
- Can anyone help with a code for a ford fiesta radio?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.