================= Lambda JavaScript ================= Writing Real Programs... with JavaScript!? *Andrew Montalenti, CTO* .. rst-class:: logo .. image:: ./_static/parsely.png :width: 40% :align: right JavaScript iteration ==================== .. sourcecode:: JavaScript var nums = [45, 23, 51, 32, 5]; for (var i = 0; i < nums.length; i++) { console.log(i, nums[i]); } // 0 45 // 1 23 // 2 51 // 3 32 // 4 5 But, what's going on here? ========================== .. sourcecode:: JavaScript window.nums = window.Array(45, 23, 51, 32, 5); for (window.i = 0; window.i < window.nums.length; window.i++) { window.console.log(window.i, window.nums[window.i]); } Some first JS rules =================== ``[1, 2, 3]`` is like ``Array(1, 2, 3)``; what Python calls a "list", JS calls an "Array". To iterate an array, you must get an index (``i``) and index into it (``nums[i]``). Making variables with ``var`` outside of a function sets or overrides a *global variable*. This even applies to constructs that seem to have block scope, like ``for`` loops. Fixing it with function scope ============================= .. sourcecode:: JavaScript (function() { // creates a "temporary" local function scope var nums = [1, 2, 3]; for (var i = 0; i < nums.length; i++) { console.log(i, nums[i]); } z = "some value"; // warning! })(); // now back in global scope console.log(typeof nums === 'undefined'); console.log(typeof i === 'undefined'); console.log(typeof z === 'undefined'); // 0 1 // 1 2 // 2 3 // true // true // false Some more JS rules ================== Check whether a variable was set with ``'undefined'``, e.g. .. sourcecode:: JavaScript console.log(typeof nums === 'undefined'); // true console.log(typeof z === 'undefined'); // false The pattern ``(function() { ... })();`` creates a local scope by using a "self-executing function", aka IIFE, or "immediately invoked function expression". This weird-looking pattern can be explained here: .. sourcecode:: JavaScript var someFunction = function() { /* this part defines => */ var nums = [1, 2, 3]; console.log(nums); }; someFunction /* this part invokes => */ (); Now, some style rules ===================== When writing JS code, you need to heed the following: - When JavaScript applications are combined via `` .. ifslides:: .. raw:: html