<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hadi Anjum on Medium]]></title>
        <description><![CDATA[Stories by Hadi Anjum on Medium]]></description>
        <link>https://medium.com/@hadianjum60?source=rss-1af36c51a66a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kjkvQy_Ixo_akwb4</url>
            <title>Stories by Hadi Anjum on Medium</title>
            <link>https://medium.com/@hadianjum60?source=rss-1af36c51a66a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 04:10:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hadianjum60/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Basic to Advance JavaScript.]]></title>
            <link>https://medium.com/@hadianjum60/basic-to-advance-javascript-a269f7f772a0?source=rss-1af36c51a66a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a269f7f772a0</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[advanced-javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Hadi Anjum]]></dc:creator>
            <pubDate>Mon, 01 Aug 2022 15:31:41 GMT</pubDate>
            <atom:updated>2022-08-14T10:10:17.942Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What are the different data types present in javascript?</strong></h3><p>To know the type of a JavaScript variable, we can use the type of operator.</p><h4><strong>Primitive types</strong> :</h4><p><strong>String</strong> — It represents a series of characters and is written with quotes. A string can be represented using a single or a double quote.</p><p><strong>Example :</strong></p><pre>var str = “Vivek Singh Bisht”; //using double quotes <br> var str2 = ‘John Doe’; //using single quotes</pre><p><strong>Number</strong> — It represents a number and can be written with or without decimals.</p><p><strong>Example :</strong></p><pre>var x = 3; //without decimal <br> var y = 3.6; //with decimal</pre><p><strong>BigInt </strong>— This data type is used to store numbers that are above the limitation of the Number data type. It can store large integers and is represented by adding “n” to an integer literal.</p><p><strong>Example :</strong></p><pre>var bigInteger = 234567890123456789012345678901234567890;</pre><p><strong>Boolean</strong> — It represents a logical entity and can have only two values: true or false. Booleans are generally used for conditional testing.</p><p>Example :</p><pre>var a = 2; </pre><pre>var b = 3; </pre><pre>var c = 2; (a == b) // returns false(a == c) //returns true</pre><p><strong>Undefined</strong> — When a variable is declared but not assigned, it has the value of undefined and it’s type is also undefined.</p><p>Example :</p><pre>var x; // value of x is undefined </pre><pre>var y = undefined; // we can also set the value of a variable as undefined</pre><p><strong>Null</strong> — It represents a non-existent or invalid value.</p><p>Example :</p><pre>var z = null;</pre><p><strong>Symbol </strong>— It is a new data type introduced in the ES6 version of javascript. It is used to store an anonymous and unique value.</p><p>Example :</p><pre>var symbol1 = Symbol(&#39;symbol&#39;);</pre><h4>typeof of primitive types :</h4><pre>typeof “John Doe” // Returns “string” <br> typeof 3.14 // Returns “number” <br> typeof true // Returns “boolean” <br> typeof 234567890123456789012345678901234567890n // Returns bigint typeof undefined // Returns “undefined” <br> typeof null // Returns “object” (kind of a bug in JavaScript) <br> typeof Symbol(‘symbol’) // Returns Symbol</pre><p><strong>Non-primitive types</strong></p><p>Primitive data types can store only a single value. To store multiple and complex values, non-primitive data types are used. Object — Used to store collection of data.</p><p>Example:</p><pre>// Collection of data in key-value pairs <br> var obj1 = { <br> x: 43, <br> y: “Hello world!”, <br> z: function(){ <br> return this.x; <br> } <br> } // Collection of data as an ordered list <br> var array1 = [5, “Hello”, true, 4.1];</pre><p><strong>Explain Hoisting in javascript.</strong></p><p>Hoisting is a default behaviour of javascript where all the variable and function declarations are moved on top.</p><p>This means that irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global.</p><p>Example 1:</p><pre>hoistedVariable = 3; <br> console.log(hoistedVariable); // outputs 3 even when the variable is declared after it is init ialized <br> var hoistedVariable;</pre><p>Example 2:</p><pre>hoistedFunction(); // Outputs “ Hello world! “ even when the function is declared after calling <br> function hoistedFunction(){ <br> console.log(“ Hello world! “); <br> }</pre><p>Example 3:</p><pre>// Hoisting takes place in the local scope as well <br> function doSomething(){ <br> x = 33; <br> console.log(x); <br> var x; <br> }</pre><p>doSomething(); // Outputs 33 since the local variable “x” is hoisted inside the local scope</p><p><strong>Note</strong> — Variable initializations are not hoisted, only variable declarations are hoisted:</p><pre>var x; <br> console.log(x); // Outputs “undefined” since the initialization of “x” is not hoisted <br> x = 23;</pre><p><strong>Note </strong>— To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:</p><pre>var x = 2; <br> var y = “2”; <br> (x == y) // Returns true since the value of both x and y is the same (x === y) // Returns false since the typeof x is “number” and typeof y is “string”</pre><p><strong>Explain Implicit Type Coercion in javascript.</strong></p><p>Implicit type coercion in javascript is automatic conversion of value from one data type to another. It takes place when the operands of an expression are of different data types.</p><p><strong>String coercion</strong></p><p>String coercion takes place while using the ‘ + ‘ operator. When a number is added to a string, the number type is always converted to the string type. Example 1:</p><pre>var x = 3; <br> var y = “3”; <br> x + y // Returns “33”</pre><p>Example 2:</p><pre>var x = 24; <br> var y = “Hello”; <br> x + y // Returns “24Hello”;</pre><p><strong>Note</strong> — ‘ + ‘ operator when used to add two numbers, outputs a number. The same ‘ + ‘ operator when used to add two strings, outputs the concatenated string:</p><pre>var name = “Vivek”; <br> var surname = “ Bisht”; <br> name + surname // Returns “Vivek Bisht”</pre><p>Let’s understand both the examples where we have added a number to a string,</p><p>When JavaScript sees that the operands of the expression x + y are of different types ( one being a number type and the other being a string type ) , it converts the number type to the string type and then performs the operation. Since after conversion, both the variables are of string type, the ‘ + ‘ operator outputs the concatenated string “33” in the first example and “24Hello” in the second example.</p><p><strong>Note </strong>— Type coercion also takes place when using the ‘ — ‘ operator, but the difference while using ‘ — ‘ operator is that, a string is converted to a number and then subtraction takes place.</p><pre>var x = 3; <br> Var y = “3”; <br> x — y //Returns 0 since the variable y (string type) is converted to a number type</pre><p><strong>Boolean Coercion</strong></p><p>Boolean coercion takes place when using logical operators, ternary operators, if statements and loop checks. To understand boolean coercion in if statements and operators, we need to understand truthy and falsy values.</p><p>Truthy values are those which will be converted (coerced) to true . Falsy values are those which will be converted to false . All values except false, 0, 0n, -0, “”, null, undefined and NaN are truthy values.</p><p><strong>If statements:</strong></p><p>Example:</p><pre>var x = 0; <br> var y = 23;<br> <br> if(x) { console.log(x) } // The code inside this block will not run since the value of x is 0 (Falsy) if(y) { console.log(y) } // The code inside this block will run since the value of y is 23 ( Truthy)</pre><p><strong>Logical operators:</strong></p><p>Logical operators in javascript, unlike operators in other programming languages, do not return true or false. They always return one of the operands.</p><p><strong>OR ( | | ) operator </strong>— If the first value is truthy, then the first value is returned. Otherwise, always the second value gets returned.</p><p><strong>AND ( &amp;&amp; ) operator</strong> — If both the values are truthy, always the second value is returned. If the first value is falsy then the first value is returned or if the second value is falsy then the second value is returned.</p><p>Example:</p><pre>var x = 220; <br> var y = “Hello”; <br> var z = undefined; <br> x | | y // Returns 220 since the first value is truthy <br> x | | z // Returns 220 since the first value is truthy <br> x &amp;&amp; y // Returns “Hello” since both the values are truthy <br> y &amp;&amp; z // Returns undefined since the second value is falsy <br> if( x &amp;&amp; y ){ <br> console.log(“Code runs” ); // This block runs because x &amp;&amp; y returns “Hello” (Truthy) <br> } <br> if( x || z ){ console.log(“Code runs”); // This block runs because x || y returns 220(Truthy) <br> }</pre><p><strong>Equality Coercion</strong></p><p>Equality coercion takes place when using ‘ == ‘ operator. As we have stated before</p><p><strong>The ‘ == ‘ operator compares values and not types</strong></p><p>While the above statement is a simple way to explain == operator, it’s not completely true The reality is that while using the ‘==’ operator, coercion takes place. The ‘==’ operator, converts both the operands to the same type and then compares them.</p><p>Example:</p><pre>var a = 12; <br> var b = “12”; <br> a == b // Returns true because both ‘a’ and ‘b’ are converted to the same type and then co mpared. Hence the operands are equal.</pre><p>Coercion does not take place when using the ‘===’ operator. Both operands are not converted to the same type in the case of ‘===’ operator.</p><p>Example:</p><pre>var a = 226; <br> var b = “226”; <br> a === b // Returns false because coercion does not take place and the operands are of dif ferent types. Hence they are not equal.</pre><p><strong>Is javascript a statically typed or a dynamically typed language?</strong></p><p>JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to statically typed language, where the type of a variable is checked during compile-time.</p><p>Since javascript is a loosely(dynamically) typed language, variables in JS are not associated with any type. A variable can hold the value of any data type. For example, a variable which is assigned a number type can be converted to a string type:</p><pre>var a = 23; </pre><pre>var a = &quot;Hello World!&quot;;</pre><h3>What is NaN property in JavaScript?</h3><p>NaN property represents “<strong>Not-a-Number</strong>” value. It indicates a value which is not a legal number.</p><p>typeof of a <strong>NaN</strong> will return a <strong>Number </strong>.</p><p>To check if a value is NaN, we use the isNaN() function,</p><p><strong>Note</strong>- isNaN() function converts the given value to a Number type, and then equates to NaN</p><pre>isNaN(&quot;Hello&quot;) // Returns true isNaN(345) // Returns false isNaN(&#39;1&#39;) // Returns false, since &#39;1&#39; is converted to Number type which results in 0 ( a nu mber) </pre><pre>isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number) </pre><pre>isNaN(false) // Returns false </pre><pre>isNaN(undefined) // Returns true</pre><h3>Explain passed by value and passed by reference.</h3><p><strong>In JavaScript, primitive data types are passed by value and non-primitive data types are passed by reference.</strong></p><p>For understanding passed by value and passed by reference, we need to understand what happens when we create a variable and assign a value to it,</p><pre>var x = 2;</pre><p>In the above example, we created a variable x and assigned it a value “2”. In the background, the “=” (assign operator) allocates some space in the memory, stores the value “2” and returns the location of the allocated memory space. Therefore, the variable x in the above code points to the location of the memory space instead of pointing to the value 2 directly.</p><p>Assign operator behaves differently when dealing with primitive and non primitive data types,</p><p><strong>Assign operator dealing with primitive types:</strong></p><pre>var y = 234; </pre><pre>var z = y;</pre><p>In the above example, assign operator knows that the value assigned to y is a primitive type (number type in this case), so when the second line code executes, where the value of y is assigned to z, the assign operator takes the value of y (234) and allocates a new space in the memory and returns the address. Therefore, variable z is not pointing to the location of variable y, instead it is pointing to a new location in the memory.</p><pre>var y = #8454; // y pointing to address of the value 234 </pre><pre>var z = y;  </pre><pre>var z = #5411; // z pointing to a completely new address of the value 234// Changing the value of y </pre><pre>y = 23; </pre><pre>console.log(z); // Returns 234, since z points to a new address in the memory so change s in y will not effect z</pre><p>From the above example, we can see that primitive data types when passed to another variable, are passed by value. Instead of just assigning the same address to another variable, the value is passed and new space of memory is created.</p><p><strong>Assign operator dealing with non-primitive types:</strong></p><pre>var obj = { name: &quot;Vivek&quot;, surname: &quot;Bisht&quot; }; </pre><pre>var obj2 = obj;</pre><p>In the above example, the assign operator, directly passes the location of the variable obj to the variable obj2. In other words, the reference of the variable obj is passed to the variable obj2.</p><pre>var obj = #8711; // obj pointing to address of { name: &quot;Vivek&quot;, surname: &quot;Bisht&quot; }</pre><pre>var obj2 = obj;  </pre><pre>var obj2 = #8711; // obj2 pointing to the same address   </pre><pre>// changing the value of obj1  </pre><pre>obj1.name = &quot;Akki&quot;;  </pre><pre>console.log(obj2);  </pre><pre>// Returns {name:&quot;Akki&quot;, surname:&quot;Bisht&quot;} since both the variables are pointing to the same address.</pre><p>From the above example, we can see that while passing non-primitive data types, the assign operator directly passes the address (reference). Therefore, non-primitive data types are always <strong>passed by reference.</strong></p><h3>What is an Immediately Invoked Function in JavaScript?</h3><p>An Immediately Invoked Function ( known as IIFE and pronounced as IIFY) is a function that runs as soon as it is defined.</p><p>Syntax of IIFE :</p><pre>(function(){  </pre><pre>// Do something; </pre><pre>})();</pre><p>To understand IIFE, we need to understand the two sets of parentheses which are added while creating an IIFE :</p><p>First set of parenthesis:</p><pre>(function (){  </pre><pre>   //Do something; </pre><pre>})</pre><p>While executing javascript code, whenever the compiler sees the word “function”, it assumes that we are declaring a function in the code. Therefore, if we do not use the first set of parentheses, the compiler throws an error because it thinks we are declaring a function, and by the syntax of declaring a function, a function should always have a name.</p><pre>function() {  </pre><pre>   //Do something; </pre><pre>} // Compiler gives an error since the syntax of declaring a function is wrong in the code abov e.</pre><p>To remove this error, we add the first set of parenthesis that tells the compiler that the function is not a function declaration, instead, it’s a function expression.</p><p>Second set of parenthesis:</p><pre>(function (){  </pre><pre>   //Do something; </pre><pre>})();</pre><p>From the definition of an IIFE, we know that our code should run as soon as it is defined. A function runs only when it is invoked. If we do not invoke the function, the function declaration is returned:</p><pre>(function (){  </pre><pre>// Do something; </pre><pre>}) // Returns the function declaration</pre><p>Therefore to invoke the function, we use the second set of parenthesis. .</p><h3>Explain Higher Order Functions in javascript.</h3><p>Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. Higher order functions are a result of functions being first-class citizens in javascript.</p><p>Examples of higher order functions:</p><pre>function higherOrder(fn) {  </pre><pre>  fn(); </pre><pre>}  </pre><pre>higherOrder(function() { console.log(&quot;Hello world&quot;) });function higherOrder2() {  </pre><pre>  return function() {  </pre><pre>     return &quot;Do something&quot;;  </pre><pre>  } </pre><pre>}  </pre><pre>var x = higherOrder2(); </pre><pre>x() // Returns &quot;Do something&quot;</pre><h3>Explain “this” keyword.</h3><p>The “this” keyword refers to the object that the function is a property of.</p><p>The value of “this” keyword will always depend on the object that is invoking the function.</p><p>Confused? Let’s understand the above statements by examples:</p><pre>function doSomething() {  </pre><pre>   console.log(this); </pre><pre>}  </pre><pre>doSomething();</pre><p>What do you think the output of the above code will be?</p><p>Note — Observe the line where we are invoking the function. Check the definition again:</p><p><strong>The “this” keyword refers to the object that the function is a property of.</strong></p><p>In the above code, function is a property of which object? Since the function is invoked in the global context, the function is a property of the global object.</p><p>Therefore, the output of the above code will be the global object. Since we ran the above code inside the browser, the global object is the window object.</p><p>Example 2:</p><pre>var obj = { </pre><pre> name: &quot;vivek&quot;,  </pre><pre> getName: function(){  </pre><pre>   console.log(this.name); </pre><pre>  } </pre><pre>}  obj.getName();</pre><p>In the above code, at the time of invocation, the getName function is a property of the object obj , therefore, the this keyword will refer to the object obj , and hence the output will be “vivek”.</p><p>Example 3:</p><pre>var obj = {  </pre><pre>   name: &quot;vivek&quot;,  </pre><pre>   getName: function(){  </pre><pre>   console.log(this.name);  </pre><pre>  }  </pre><pre>}  </pre><pre>var getName = obj.getName;  </pre><pre>var obj2 = {</pre><pre>    name:&quot;akshay&quot;, </pre><pre>    getName </pre><pre>}; </pre><pre>obj2.getName();</pre><p>Can you guess the output here?</p><p>The output will be “akshay”.</p><p>Although the getName function is declared inside the object obj , at the time of invocation, getName() is a property of obj2 , therefore the “this” keyword will refer to obj2 . The silly way to understanding the this keyword is, whenever the function is invoked, check the object before the dot . The value of this . keyword will always be the object before the dot . If there is no object before the dot like in example1, the value of this keyword will be the global object.</p><p>Example 4:</p><pre>var obj1 = {  </pre><pre>    address : &quot;Mumbai,India&quot;,  </pre><pre>    getAddress: function(){  </pre><pre>       console.log(this.address);  </pre><pre>} </pre><pre>}</pre><pre>  var getAddress = obj1.getAddress; </pre><pre>  var obj2 = {name:&quot;akshay&quot;}; </pre><pre>  obj2.getAddress();</pre><p>Can you guess the output?</p><p>The output will be an error.</p><p>Although in the code above, the this keyword refers to the object obj2 , obj2 does not have the property “address”‘, hence the getAddress function throws an error.</p><h3>Explain Scope and Scope Chain in javascript.</h3><p>Scope in JS, determines the accessibility of variables and functions at various parts in one’s code.</p><p>In general terms, the scope will let us know at a given part of code, what are the variables and functions that we can or cannot access. There are three types of scopes in JS:</p><p>1. Global scope</p><p>2. Local or Function Scope</p><p>3. Block Scope</p><h3>Global Scope:</h3><p>Variables or functions declared in the global namespace have global scope, which means all the variables and functions having global scope can be accessed from anywhere inside the code.</p><pre>var globalVariable = &quot;Hello world&quot;; </pre><pre>function sendMessage(){  </pre><pre>   return globalVariable; // can access globalVariable since it&#39;s      written in global space </pre><pre>} function sendMessage2(){  </pre><pre>     return sendMessage(); // Can access sendMessage function since it&#39;s written in global sp ace </pre><pre>  } </pre><pre>sendMessage2(); // Returns “Hello world”</pre><h3>Function Scope</h3><p>Any variables or functions declared inside a function have local/function scope, which means that all the variables and functions declared inside a function, can be accessed from within the function and not outside of it.</p><pre>function awesomeFunction(){  </pre><pre>   var a = 2;  </pre><pre>   var multiplyBy2 = function(){  </pre><pre>     console.log(a*2); // Can access variable &quot;a&quot; since a and multiplyBy2 both are written i nside the same function  </pre><pre>  } </pre><pre>} </pre><pre>console.log(a); // Throws reference error since a is written in local scope and cannot be ac cessed outside multiplyBy2(); // Throws reference error since multiplyBy2 is written in local scope</pre><h3>Block Scope</h3><p>Block scope is related to the variables declared using let and const. Variables declared with var do not have block scope.</p><p>Block scope tells us that any variable declared inside a block { }, can be accessed only inside that block and cannot be accessed outside of it.</p><pre>{  </pre><pre>   let x = 45; </pre><pre>} </pre><pre>console.log(x); // Gives reference error since x cannot be accessed outside of the block for(let i=0; i</pre><h3>Scope Chain</h3><p>JavaScript engine also uses Scope to find variables. Let’s understand that using an example:</p><pre>var y = 24; </pre><pre>function favFunction(){  </pre><pre>   var x = 667;  </pre><pre>   var anotherFavFunction = function(){  </pre><pre>   console.log(x); // Does not find x inside anotherFavFunction, so looks for variable insi de favFunction, outputs 667  </pre><pre>}</pre><pre>  var yetAnotherFavFunction = function(){  </pre><pre>   console.log(y); // Does not find y inside yetAnotherFavFunction, so looks for variable i nside favFunction and does not find it, so looks for variable in global scope, finds it and outp uts 24 </pre><pre> }  anotherFavFunction(); </pre><pre> yetAnotherFavFunction(); } </pre><pre>favFunction();</pre><p>As you can see in the code above, if the javascript engine does not find the variable in local scope, it tries to check for the variable in the outer scope. If the variable does not exist in the outer scope, it tries to find the variable in the global scope.</p><p>If the variable is not found in the global space as well, reference error is thrown.</p><h3>What is recursion in a programming language?</h3><p>Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.</p><pre>function add(number) {</pre><pre>if (number &lt;= 0) {</pre><pre>return 0;</pre><pre>} else {</pre><pre>return number + add(number - 1);</pre><pre>}</pre><pre>}</pre><pre>add(3) =&gt; 3 + add(2)</pre><pre>3 + 2 + add(1)</pre><pre>3 + 2 + 1 + add(0)</pre><pre>3 + 2 + 1 + 0 = 6</pre><p>Example of a recursive function:</p><p>The following function calculates the sum of all the elements in an array by using recursion:</p><pre>function computeSum(arr){</pre><pre>  if(arr.length === 1){</pre><pre>    return arr[0];</pre><pre>}</pre><pre> else{</pre><pre>   return arr.pop() + computeSum(arr);</pre><pre> }</pre><pre>}</pre><pre>computeSum([7, 8, 9, 99]); // Returns 123</pre><h3>What is DOM?</h3><p>DOM stands for Document Object Model.</p><p>DOM is a programming interface for HTML and XML documents.</p><p>When the browser tries to render a HTML document, it creates an object based on the HTML document called DOM. Using this DOM, we can manipulate or change various elements inside the HTML document. Example of how HTML code gets converted to DOM:</p><h3>Differences between declaring variables using var, let and const.</h3><p>Before the ES6 version of javascript, only the keyword var was used to declare variables. With the ES6 Version, keywords let and const were introduced to declare variables.</p><p>Let’s understand the differences with examples:</p><p>Let’s understand the differences with examples:</p><pre>var variable1 = 23;let variable2 = 89;function catchValues(){console.log(variable1);console.log(variable2);// Both the variables can be accessed anywhere since they are declared in the global scope}window.variable1; // Returns the value 23</pre><pre>window.variable2; // Returns undefined</pre><p>The variables declared with the let keyword in the global scope behave just like the variable declared with the var keyword in the global scope. Variables declared in the global scope with var and let keywords can be accessed from anywhere in the code.</p><p>But, there is one difference! Variables that are declared with the var keyword in the global scope are added to the window/global object. Therefore, they can be accessed using window.variableName. Whereas, the variables declared with the let keyword are not added to the global object, therefore, trying to access such variables using window.variableName results in an error.</p><p><strong>var vs let in functional scope</strong></p><pre>function varVsLetFunction(){let awesomeCar1 = &quot;Audi&quot;;var awesomeCar2 = &quot;Mercedes&quot;;}console.log(awesomeCar1); // Throws an errorconsole.log(awesomeCar2); // Throws an error</pre><p>Variables declared in a functional/local scope using var and let keywords behave exactly the same, meaning , they cannot be accessed from outside of the scope.</p><pre>{var variable3 = [1, 2, 3, 4];}console.log(variable3); // Outputs [1,2,3,4]{let variable4 = [6, 55, -1, 2];}console.log(variable4); // Throws errorfor(let i = 0; i &lt; 2; i++){//Do something}console.log(i); // Throws errorfor(var j = 0; j &lt; 2; i++){// Do something}console.log(j) // Outputs 2</pre><p>In javascript, a block means the code written inside the curly braces {} . Variables declared with var keyword do not have block scope. It means a variable declared in block scope {} with the var keyword is the same as declaring the variable in the global scope. Variables declared with let keyword inside the block scope cannot be accessed from outside of the block. Const keyword Variables with the const keyword behave exactly like a variable declared with the let keyword with only one difference, any variable declared with the const keyword cannot be reassigned.</p><p>Example:</p><pre>const x = {name:&quot;Vivek&quot;};x = {address: &quot;India&quot;}; // Throws an errorx.name = &quot;Nikhil&quot;; // No error is thrownconst y = 23;y = 44; // Throws an error</pre><p>In the code above, although we can change the value of a property inside the variable declared with const keyword, we cannot completely reassign the variable itself.</p><h3>Guess the outputs of the following codes:</h3><pre>// Code 1:function func1(){setTimeout(()=&gt;{console.log(x);console.log(y);},3000);var x = 2;let y = 12;}func1();// Code 2:function func2(){for(var i = 0; i &lt; 3; i++){setTimeout(()=&gt; console.log(i),2000);}}func2();// Code 3:(function(){setTimeout(()=&gt; console.log(1),2000);console.log(2);setTimeout(()=&gt; console.log(3),0);console.log(4);})();</pre><p>Answers:</p><p>Code 1 — Outputs 2 and 12 . Since, even though let variables are not hoisted, due to async nature of javascript, the complete function code runs before the setTimeout function. Therefore, it has access to both x and y.</p><p>Code 2 — Outputs 3 , three times since variable declared with var keyword does not have block scope. Also, inside the for loop, the variable i is incremented first and then checked.</p><p>Code 3 — Output in the following order:</p><pre>2</pre><pre>4</pre><pre>3</pre><pre>1 // After two seconds</pre><p>Even though the second timeout function has a waiting time of zero seconds, the javascript engine always evaluates the setTimeout function using the Web API and therefore, the complete function executes before the setTimeout function can execute.</p><h3>Guess the outputs of the following code:</h3><pre>// Code 1:let x= {}, y = {name:&quot;Ronny&quot;},z = {name:&quot;John&quot;};x[y] = {name:&quot;Vivek&quot;};x[z] = {name:&quot;Akki&quot;};console.log(x[y]);// Code 2:function runFunc(){console.log(&quot;1&quot; + 1);console.log(&quot;A&quot; - 1);console.log(2 + &quot;-2&quot; + &quot;2&quot;);console.log(&quot;Hello&quot; - &quot;World&quot; + 78);console.log(&quot;Hello&quot;+ &quot;78&quot;);}runFunc();// Code 3:let a = 0;let b = false; </pre><pre>console.log((a == b)); </pre><pre>console.log((a === b));</pre><p>Answers:</p><p>Code 1 — Output will be {name: “Akki”}. Adding objects as properties of another object should be done carefully. Writing x[y] = {name:”Vivek”} , is same as writing x[‘object Object’] = {name:”Vivek”} , While setting a property of an object, javascript coerces the parameter into a string. Therefore, since y is an object, it will be converted to ‘object Object’. Both x[y] and x[z] are referencing the same property. Code 2 — Outputs in the following order:</p><pre>11 </pre><pre>Nan </pre><pre>2-22 </pre><pre>NaN </pre><pre>Hello78</pre><p><strong>Code 3</strong> — Output in the following order due to equality coercion:</p><pre>true </pre><pre>false</pre><h3>Guess the output of the following code:</h3><pre>var x = 23;(function(){var x = 43;(function random(){x++;console.log(x);var x = 21;})();})();</pre><p>Answer:</p><p>Output is NaN . random() function has functional scope, since x is declared and hoisted in the functional scope.</p><p>Rewriting the random function will give a better idea about the output:</p><pre>function random(){var x; // x is hoistedx++; // x is not a number since it is not initialized yetconsole.log(x); // Outputs NaNx = 21; // Initialization of x}</pre><h3>Guess the outputs of the following code:</h3><p><strong>Note</strong> — Code 2 and Code 3 require you to modify the code, instead of guessing the output.</p><pre>// Code 1(function(a){return (function(){console.log(a);a = 23;})()})(45);// Code 2// Each time bigFunc is called, an array of size 700 is being created,// Modify the code so that we don&#39;t create the same array again and againfunction bigFunc(element){let newArray = new Array(700).fill(&#39;♥&#39;);return newArray[element];</pre><p>Answers — Code 1 — Outputs 45 . Even though a is defined in the outer function, due to closure the inner functions have access to it. Code 2 — This code can be modified by using closures,</p><pre>function bigFunc(){let newArray = new Array(700).fill(&#39;♥&#39;);return (element) =&gt; newArray[element];}let getElement = bigFunc(); // Array is created only oncegetElement(599);getElement(670);</pre><p>Code 3 — Can be modified in two ways:</p><p>Using let keyword:</p><pre>function randomFunc(){for(let i = 0; i &lt; 2; i++){setTimeout(()=&gt; console.log(i),1000);}</pre><pre>}</pre><pre>randomFunc();</pre><p>Using closure:</p><pre>function randomFunc(){for(var i = 0; i &lt; 2; i++){(function(i){setTimeout(()=&gt;console.log(i),1000);})(i);}}randomFunc();</pre><h3>Implement a function that returns an updated array with r right rotations on an array of integers a .</h3><p>Example:</p><p>Given the following array:</p><p>[2,3,4,5,7]</p><p>Perform 3 right rotations:</p><p>First rotation : [7,2,3,4,5] , Second rotation : [5,7,2,3,4] and, Third rotation: [4,5,7,2,3]</p><p>return [4,5,7,2,3]</p><p>Answer:</p><pre>function rotateRight(arr,rotations){if(rotations == 0) return arr;for(let i = 0; i &lt; rotations;i++){let element = arr.pop();arr.unshift(element);}return arr;}rotateRight([2, 3, 4, 5, 7], 3); // Return [4,5,7,2,3]rotateRight([44, 1, 22, 111], 5); // Returns [111,44,1,22]</pre><p>Here is some basic concept of JavaScript with a Practice example. I hope you like this article like, share, and give any suggestions.</p><p><strong>Advance javaScript:</strong></p><p>JavaScript is a dynamic programming language that’s used for web development, web applications, game development, and lots more. It allows you to implement dynamic features on web pages that cannot be done with only HTML and CSS.</p><p>Many browsers use JavaScript as a scripting language for doing dynamic things on the web. Any time you see a click-to-show dropdown menu, extra content added to a page and dynamically changing element colors on a page, to name a few features, you’re seeing the effects of JavaScript.</p><h3>Adding interactive behavior to web pages</h3><p>JavaScript allows users to interact with web pages. There are almost no limits to the things you can do with JavaScript on a web page — these are just a few examples:</p><p>· Show or hide more information with the click of a button</p><p>· Change the color of a button when the mouse hovers over it</p><p>· Slide through a carousel of images on the homepage</p><p>· Zooming in or zooming out on an image</p><p>· Displaying a timer or count-down on a website</p><p>· Playing audio and video in a web page</p><p>· Displaying animations</p><p>· Using a drop-down hamburger menu</p><h3>Creating web and mobile apps</h3><p>Developers can use various JavaScript frameworks for developing and building web and mobile apps. JavaScript frameworks are collections of JavaScript code libraries that provide developers with pre-written code to use for routine programming features and tasks — literally a framework to build websites or web applications around.</p><p>Popular JavaScript front-end frameworks include React, React Native, Angular, and Vue. Many companies use Node.js, a JavaScript runtime environment built on Google Chrome’s JavaScript V8 engine. A few famous examples include Paypal, LinkedIn, Netflix, and Uber!</p><h3>Building web servers and developing server applications</h3><p>Beyond websites and apps, developers can also use JavaScript to build simple web servers and develop the back-end infrastructure using Node.js.</p><h3>Game development</h3><p>Of course, you can also use JavaScript to create browser games. These are a great way for beginning developers to practice their JavaScript skills.</p><p><strong>Now start discussing javaScript advancement like as javaScript advance concept:</strong></p><h3>Object-Oriented Code</h3><p><strong>A style of Object-oriented programming (OOP) in which inheritance occurs via defining classes of objects, instead of inheritance occurring via the objects alone</strong>. The most popular model of OOP is class-based. But as I mentioned, JavaScript isn’t a classed-based language — it is a prototype-based language.</p><pre>var user = {</pre><pre>    name: &quot;jhon&quot;,</pre><pre>    getName: function (letter) { alert(letter); }</pre><pre>};</pre><p>One reason using objects to hold data is useful is that, as mentioned, human brains are very good at categorizing things: a boat; a chair; a moose. Creating objects in code helps you to think about how the different parts of your code fit and hopefully work together.</p><p>In a large application, you may have a great number of objects interacting with each other. Remember that objects are a grouping together of properties (like the name) and methods? This grouping of data and behavior into one entity is called <strong>encapsulation</strong>.</p><p>A powerful tool available to you when building applications using objects is called <strong>inheritance</strong>. This is where an object <strong>inherits</strong> properties and methods from another object. An object can alter the properties and methods it inherits and add additional properties and methods too.</p><h3>How do objects inherit?</h3><p>JavaScript uses <strong>prototypal inheritance</strong>. This means that, when an object inherits from another, the parent object is known as the child’s <strong>prototype</strong>.</p><p>There are a couple of other things to know: every object maintains a reference to its prototype and every object inherits from the <a href="https://blog.devgenius.io/basic-javascript-javascript-for-beginners-5bff43a0570b?source=your_stories_page-------------------------------------&amp;gi=ddacbdb778ce">global object</a> object.</p><p>When you ask for a property of an object, JavaScript looks for the property on that object. If it doesn’t find it there, it follows the link to the object’s prototype and looks for the property there. It continues this, up the <strong>prototype chain</strong> until it finds it, or it returns undefined.</p><p>In other words, an object inherits properties and methods by maintaining a link to another object from which it wants to inherit. Multiple objects can inherit from one single object, but one single object cannot inherit from multiple other objects, although it can inherit from an object that inherits from another.</p><h3>In practice</h3><p>There are many ways to achieve inheritance in JavaScript. The most commonly used is the <strong>constructor pattern</strong>. In this pattern, a function called a <strong>constructor</strong> is used to create new objects. Constructors are used in combination with the new keyword to create objects.</p><p>Here’s an example constructor. Note the capital letter on Person — this is an important convention. Generally, in JavaScript, if it’s got a capital first letter, it’s a constructor and should be used with the new keyword.</p><pre>var Person = function (name) {</pre><pre>    this.name = name;</pre><pre>};</pre><p>Now you can use the new keyword to create Person objects:</p><pre>var doe = new Person(&#39;jhon&#39;);</pre><p>This produces an object like this:</p><pre>{</pre><pre>    name: &quot;Jhon&quot;</pre><pre>}</pre><p>In the constructor pattern, you manually create the object from which the new objects will inherit by adding properties and methods to the prototype property of the <strong>constructor function</strong>. Like this:</p><pre>Person.prototype.say = function (letter) {</pre><pre>    alert(this.name + &#39; says &quot;&#39; + letter + &#39;&quot;&#39;);</pre><pre>};</pre><p>Now, objects created from the constructor will have the getName method.</p><pre>var jhon = new Person(&quot;jhon&quot;);</pre><pre>jhon.getName(&quot;Hello&quot;);</pre><h3>Creating Elements by using JavaScript</h3><p>Creating elements using HTML tags isn’t the only way to do it — in fact, it’s possible to create, modify and insert elements from JavaScript.</p><p>Here’s an example that creates a div, adds some text to it and appends it as the last element in the body:</p><pre>var div = document.createElement(&#39;div&#39;);</pre><pre>div.textContent = &quot;Sup, y&#39;all?&quot;;</pre><pre>div.setAttribute(&#39;class&#39;, &#39;note&#39;);</pre><pre>document.body.appendChild(div);</pre><p>So document.createElement is used with an HTML tag to create the element. The textContent is then modified and then the class attribute is modified using setAttribute. This could also be used to add a data attribute or any other kind of attribute like you can in HTML! Finally, the element is appended to the body using the <a href="https://htmldog.com/references/html/tags/body/">body</a> element’s appendChild method.</p><p>It’s essentially equivalent to &lt;div class=&quot;note&quot;&gt;Sup, y&#39;all?&lt;/div&gt;.</p><p>In fact, all elements have the appendChild method, so having done the above it’s possible to do the following:</p><pre>var span = document.createElement(&#39;span&#39;);</pre><pre>span.textContent = &quot;Hello!&quot;;</pre><pre>div.appendChild(span);</pre><p>The span will be added to the end of the div element.</p><h3>Removing an element</h3><p>Removing elements is just as fun. Each DOM element has a property that’s actually the DOM element’s parent. To remove an element, you call the removeChild method of the parent, passing the child element you want to remove. Something like this:</p><pre>div.parentNode.removeChild(div);</pre><p>Simple, eh?</p><h3>Creating with jQuery</h3><p>The other alternative is to use jQuery’s element creation syntax. This example does the same as the above examples combined:</p><pre>var div = $(&#39;&lt;div/&gt;&#39;).text(&quot;Sup, y&#39;all?&quot;).appendTo(document.body);</pre><pre>$(&#39;&lt;span/&gt;&#39;).text(&#39;Hello!&#39;).appendTo(div);</pre><h3>Canvas</h3><p>The HTML 5 specification has introduced a slew of new and exciting technologies to the web. Here we’ll expand on just one: the <strong>Canvas</strong> API. It’s for drawing pretty, whizzy things.</p><p>The first thing to know is that <a href="https://htmldog.com/references/html/tags/canvas/">canvas</a> is a new element in the HTML 5 specification. To begin drawing on the <a href="https://htmldog.com/references/html/tags/canvas/">canvas</a>, you grab hold of it and retrieve a particular context — either 2d or webgl:</p><pre>var canvas = document.querySelector(&#39;canvas&#39;),</pre><pre>    ctx = canvas.getContext(&#39;2d&#39;);</pre><p>From there you can begin drawing, filling and stroking shapes and text on the canvas. Here’s an example that draws a simple square on a canvas.</p><pre>&lt;canvas&gt;&lt;/canvas&gt;&lt;script&gt;</pre><pre>    var canvas = document.querySelector(&#39;canvas&#39;),</pre><pre>        ctx = canvas.getContext(&#39;2d&#39;);</pre><pre>    ctx.fillRect(10, 10, 10, 10);</pre><pre>&lt;/script&gt;</pre><p>Try this out on a page to see a little black square!</p><p>The getContext function retrieved the correct context, which is an object whose methods are used to draw, fill and generally modify the canvas. Above we’re using, which takes the <strong>x</strong> and <strong>y</strong> position of the top left corner of the rectangle as the first two arguments, and the <strong>width</strong> and <strong>height</strong> dimensions as the latter two.</p><h3>Animation</h3><p><a href="https://htmldog.com/references/html/tags/canvas/">canvas</a> works a bit like a real canvas — pixels are drawn and layered on top of each other until you erase — <strong>clear</strong> — them. This means that if you want to animate something moving across a canvas you have to repeatedly <strong>clear</strong> the canvas (or a section of it) and redraw the scene.</p><p>In the next example we’ve animating the square bouncing around the <a href="https://htmldog.com/references/html/tags/canvas/">canvas</a>, which automatically resizes to fill the screen. loop is the business part of the code. The clearRect function is used to clear the entire canvas before each frame.</p><pre>var canvas = document.querySelector(&#39;canvas&#39;),<br><br>    ctx = canvas.getContext(&#39;2d&#39;);var resize = function () {<br><br>  canvas.width = window.innerWidth;<br><br>  canvas.height = window.innerHeight;<br><br>};window.addEventListener(&#39;resize&#39;, resize);window.addEventListener(&#39;load&#39;, function () {  resize();  var pos, vel;<br><br>  pos = {<br><br>    x: 10,<br><br>    y: 10<br><br>  };<br><br>  vel = {<br><br>    x: 1,<br><br>    y: 1<br><br>  };  var loop = function () {<br><br>    ctx.clearRect(0, 0, canvas.width, canvas.height);<br><br>    pos.x += vel.x;<br><br>    pos.y += vel.y;<br><br>    if (pos.x &lt; 5 || pos.x &gt; canvas.width - 5) {<br><br>      vel.x *= -1;<br><br>    }<br><br>    if (pos.y &lt; 5 || pos.y &gt; canvas.height - 5) {<br><br>      vel.y *= -1;<br><br>    }<br><br>    ctx.fillRect(pos.x - 5, pos.y - 5, 10, 10);<br><br>  };  setInterval(loop, 1000 / 60);<br><br>});</pre><pre>    ctx.fillRect(pos.x - 5, pos.y - 5, 10, 10);</pre><pre>  };  setInterval(loop, 1000 / 60);</pre><pre>});</pre><p>There are lots to explore with canvas, this was just a very shallow look at it. There are many specialized resources on the web so, to find out more, Google is your best friend.</p><h3>Local Storage</h3><p>When building more complex JavaScript applications that run in a user’s browser it’s very useful to be able to store information in the browser, so that the information can be shared across different pages and browsing sessions.</p><p>In the recent past this would have only been possible with <strong>cookies</strong> — text files saved to a user’s computer — but the way of managing these with JavaScript was not good. Now there’s a new technology called <strong>local storage</strong> that does a similar thing, but with an easier-to-use interface.</p><p>Unlike cookies, local storage can only be read client-side — that is, by the browser and your JavaScript. If you want to share some data with a server, cookies may be a better option.</p><p>To save some data, use localStorage.setItem.</p><pre>localStorage.setItem(&#39;name&#39;, &#39;tom&#39;);</pre><p>The first argument is the identifier you’ll later use to get the data out again. The second is the data you want to store.</p><p>Getting back out again is simple — just pass the identifier to localStorage.getItem.</p><pre>var name = localStorage.getItem(&#39;name&#39;);</pre><p>Local storage can only save strings, so storing objects requires that they be turned into strings using JSON.stringify - you can’t ask local storage to store an object directly because it’ll store “[object Object]”, which isn’t right at all!</p><p>That also means the object must be run through JSON.parse on the way out of local storage. You can see this in the example below.</p><pre>// Object examplelocalStorage.setItem(&#39;user&#39;, JSON.stringify({<br><br>    username: &#39;htmldog&#39;,<br><br>    api_key: &#39;abc123xyz789&#39;<br><br>}));var user = JSON.parse(localStorage.getItem(&#39;user&#39;));</pre><p>Browser support for local storage is not 100% but it’s pretty good — you can expect it to work in all modern browsers, IE 8 and above, and in most mobile browsers too.</p><h3>Errors and Exceptions</h3><p>Errors are often used to notify another piece of code that something went wrong when trying to carry out a task and that error may then be passed on to the user.</p><p>When errors are created — <strong>thrown</strong> — they interrupt the code that’s currently being run unless they are <strong>caught</strong>.</p><p>For example, you can force an error to be thrown by giving JSON.parse invalid data:</p><pre>JSON.parse(&quot;a&quot;);</pre><p>Errors are often used to notify another piece of code that something went wrong when trying to carry out a task and that error may then be passed on to the user.</p><p>When errors are created — <strong>thrown</strong> — they interrupt the code that’s currently being run unless they are <strong>caught</strong>.</p><p>For example, you can force an error to be thrown by giving JSON.parse invalid data:</p><pre>JSON.parse(&quot;a&quot;);</pre><p>If an error is thrown in the try block it doesn’t prevent continued code execution - the error is passed into the catch block for you to deal with. Here, for example, you could tell the user that the JSON that was passed in was invalid.</p><p>The error passed to the catch block (like a function) is an object with a message property you can use to see what went wrong.</p><p>In almost all cases you’ll want to ensure your code handles errors gracefully. It’s worth learning when errors are likely to occur so that you can defend your code against them.</p><h3>Creating errors</h3><p>It’s possible to generate your own errors for someone else to deal with. This is done using the throw keyword:</p><pre>throw new Error(&quot;I hungry. Fridge empty.&quot;);</pre><h3>Defensive code</h3><p>Errors are most common at the front line where data from outside your code is brought in, and so those are the areas you need to be most careful.</p><p><strong>Try-catch</strong> blocks are one way of handling errors, but you can also check the <strong>type</strong> of some data and provide sensible defaults if you do receive ill-formatted data. Being defensive in your code is a good way of avoiding errors.</p><h3>JavaScript Regular Expressions</h3><p><strong>Regular expressions</strong> are another type of data in JavaScript, used to <strong>search and match strings</strong> to identify if a string is a valid domain name or to replace all instances of a word within a string, for example.</p><p>Regular expressions have their own syntax and often you’ll need to consult a regular expression reference if you’re doing something complex. Just search the Internet for what you need!</p><p>The following is a very high-level overview of a complex area, going through some simple examples to show how to do it in JavaScript.</p><h3>Creating regular expressions</h3><p>Like with objects and arrays, there is a <strong>regular expression literal</strong> syntax designated by two forward slashes. Everything between is the expression:</p><pre>var regex = /^[a-z\s]+$/;</pre><p>This expression matches strings that are made of lowercase letters and whitespace from beginning to end. The caret (“^”) indicates the start of the string, and the brackets indicate that anything between the opening and closing brace — letter a to z (“a-z”), lowercase, and white-space, indicated by the special “\s” character — can be repeated one or more times up to the end of the string, indicated by the dollar (“$”) symbol.</p><p>Strings have a few useful methods that accept regular expressions; here’s a look at match and replace:</p><pre>var lowerCaseString = &#39;some characters&#39;;if (lowerCaseString.match(regex)) {<br><br>    alert(&#39;Yes, all lowercase&#39;);<br><br>}</pre><p>match produces a truthy value if the regular expression <strong>matches</strong> the string (lowerCaseString) match is called on. The string matches, so execution drops into the if statement to show an alert.</p><p>Regular expressions can also be used to replace text:</p><pre>var text = &quot;There is everything and nothing.&quot;;text = text.replace(/(every|no)thing/g, &#39;something&#39;);// text is now &quot;something and something&quot;</pre><p>This expression matches the word “everything” and the word “nothing” and replaces all occurrences of them with the word “something”. Notice the “g” after the closing forward-slash (“/”) of the regular expression — this is the <strong>global flag</strong> that means the expression should match <strong>all</strong> occurrences, rather than just the first, which is what it does by default.</p><p>Flags always go after the closing slash. The other flag you might need to use is the <strong>case-insensitive flag</strong>. By default, regular expressions care about the difference between uppercase and lowercase letters, but this can be changed using the “i” flag.</p><pre>var text = &quot;Everything and nothing.&quot;;text = text.replace(/(every|no)thing/gi, &quot;something&quot;);</pre><h3>JavaScript Closures</h3><p>A <strong>closure</strong> is a function that returns a function. The function that is returned (the <strong>inner</strong> function) is created inside the called function (the <strong>outer</strong>) so — due to the scoping rules we’ve seen — the <strong>inner</strong> has access to the variables and arguments of the <strong>outer</strong>.</p><p>Closures are a powerful tool but can be tricky to understand. Mastering them, however, will allow you to write some very elegant code.</p><p>Here’s an example:</p><pre>var saver = function (value) {<br><br>    return function () {<br><br>        return value;<br><br>    };<br><br>};var retriever = saver(10);alert(retriever());10</pre><p>The saver function returns a function that, when called, retrieves the value that was passed into the saver. The <strong>inner</strong> can do so because it was created in the scope of the <strong>outer</strong> and functions created in a particular scope retain access to variables in the scope even if they are called outside of it.</p><p>One way to use closures is for creating functions that act differently depending on what was passed to the outer function. For example, here’s an additional function. The value passed to the outer function is used to add to values passed to the inner.</p><pre>var add = function (a) {<br><br>    return function (b) {<br><br>        return a + b;<br><br>    };<br><br>};var addFive = add(5);alert(addFive(10));15</pre><p>The inner, here saved as additive, has access to a when it is called because it was created in the same scope as a. The inner adds a and b and returns the result.</p><p>In the above example, the inner is saved as addFive because it adds 5 to anything passed to it. A different adding function, using strings, could be created in the same way:</p><pre>var hello = add(&#39;Hello &#39;);alert(hello(&#39;tom&#39;));Hello tom</pre><h3>Closures to Extend Variable Scope</h3><p>Closures in JavaScript are a fairly straightforward concept and have been discussed online in a number of in-depth articles. The fact that they are straightforward doesn’t necessarily mean they’re simple, however, as seen by the extensive articles that cover the subject. Simply put, closures allow a variable scope to be extended past the common scope restrictions of functions.</p><p>I like the way Jeremy Keith describes closures in his book <a href="http://bulletproofajax.com/"><em>Bulletproof Ajax</em></a>:</p><p>“Think of closures as a kind of regional scope: broader than local but not as broad as global.”</p><p>To create a closure, you nest a function inside of a function. That inner function has access to all variables in its parent function’s scope. This comes in handy when creating methods and properties in object-oriented scripts.</p><p>Here is a simple example that demonstrates the use of a closure:</p><pre>function myObject() { this.property1 = &quot;value1&quot;; this.property2 = &quot;value2&quot;; var newValue = this.property1; <strong> this.performMethod = function() { myMethodValue = newValue; return myMethodValue; };</strong> } var myObjectInstance = new myObject(); <strong>alert(myObjectInstance.performMethod());</strong></pre><p>The key portions of the script are the nested anonymous function are highlighted in green and the method call in the alert function (last line). Because the method in the alert is actually calling a nested function, that method is able to read the value of the variable called, even though that variable is not within the scope of the anonymous function or method. Developers use closures all the time, probably unknowingly, since closure is created any time an anonymous function is nested inside another function and utilizes variables from the parent function’s scope.</p><p>The power of the closure is revealed when that method (the inner function) is called, and values that normally wouldn’t be accessible are within a “regional” scope and are thus able to be used as any other value. See the references below for some deeper explanations of closures and their relation to scope. I also highly recommend you pick up a good advanced JavaScript book that offers a good discussion of the concepts associated with closures.</p><h3>Further Reading</h3><p>· Explaining JavaScript scope and closures (Robert Nyman)</p><p>· Closures in JavaScript (James Padolsey)</p><p>· JavasCript Closures at Jibbering.com</p><p>· JavaScript Closures for Dummies</p><h3>Object Literals to Pass Optional Arguments</h3><p>Here is a handy coding tip to keep in mind when dealing with functions that can accept a large number of optional arguments. Instead of passing the large number of arguments in the conventional fashion, which could unnecessarily complicate the function, you can pass just one argument which ends up being a collection of arguments declared in an object literal. Let’s look, first of all, at how we might do this in a typical manner, so we can see the contrast:</p><pre>function showStatistics(name, team, position, average, homeruns, rbi) { document.write(&quot;&lt;p&gt;&lt;strong&gt;Name:&lt;/strong&gt; &quot; + arguments[0] + &quot;&lt;br /&gt;&quot;); document.write(&quot;&lt;strong&gt;Team:&lt;/strong&gt; &quot; + arguments[1] + &quot;&lt;br /&gt;&quot;); if (typeof arguments[2] === &quot;string&quot;) { document.write(&quot;&lt;strong&gt;Position:&lt;/strong&gt; &quot; + position + &quot;&lt;br /&gt;&quot;); } if (typeof arguments[3] === &quot;number&quot;) { document.write(&quot;&lt;strong&gt;Batting Average:&lt;/strong&gt; &quot; + average + &quot;&lt;br /&gt;&quot;); } if (typeof arguments[4] === &quot;number&quot;) { document.write(&quot;&lt;strong&gt;Home Runs:&lt;/strong&gt; &quot; + homeruns + &quot;&lt;br /&gt;&quot;); } if (typeof arguments[5] === &quot;number&quot;) { document.write(&quot;&lt;strong&gt;Runs Batted In:&lt;/strong&gt; &quot; + rbi + &quot;&lt;/p&gt;&quot;); } } showStatistics(&quot;Mark Teixeira&quot;); showStatistics(&quot;Mark Teixeira&quot;, &quot;New York Yankees&quot;); showStatistics(&quot;Mark Teixeira&quot;, &quot;New York Yankees&quot;, &quot;1st Base&quot;, .284, 32, 101);</pre><p>The function above can take up to 6 arguments.</p><p>The first two arguments are mandatory, so inside the function, we don’t check for their existence. The last 4 arguments are not mandatory, so we only display their values if they exist. We call the function 3 different times (last 3 lines), with different numbers of arguments each time.</p><p>You can see that if the number of passed arguments was in the dozens, or more, the code could look a little messy, and would be harder to maintain, or read. Now let’s look at the same code using object literals to pass the arguments:</p><pre>function <strong>showStatistics(args)</strong> { document.write(&quot;&lt;p&gt;&lt;strong&gt;Name:&lt;/strong&gt; &quot; + args.name + &quot;&lt;br /&gt;&quot;); document.write(&quot;&lt;strong&gt;Team:&lt;/strong&gt; &quot; + args.team + &quot;&lt;br /&gt;&quot;); if (typeof args.position === &quot;string&quot;) { document.write(&quot;&lt;strong&gt;Position:&lt;/strong&gt; &quot; + args.position + &quot;&lt;br /&gt;&quot;); } if (typeof args.average === &quot;number&quot;) { document.write(&quot;&lt;strong&gt;Average:&lt;/strong&gt; &quot; + args.average + &quot;&lt;br /&gt;&quot;); } if (typeof args.homeruns === &quot;number&quot;) { document.write(&quot;&lt;strong&gt;Home Runs:&lt;/strong&gt; &quot; + args.homeruns + &quot;&lt;br /&gt;&quot;); } if (typeof args.rbi === &quot;number&quot;) { document.write(&quot;&lt;strong&gt;Runs Batted In:&lt;/strong&gt; &quot; + args.rbi + &quot;&lt;/p&gt;&quot;); } } <strong>showStatistics</strong>({ name: &quot;Mark Teixeira&quot; }); <strong>showStatistics</strong>({ name: &quot;Mark Teixeira&quot;, team: &quot;New York Yankees&quot; }); <strong>showStatistics</strong>({ name: &quot;Mark Teixeira&quot;, team: &quot;New York Yankees&quot;, position: &quot;1st Base&quot;, average: .284, homeruns: 32, rbi: 101 });</pre><p>Technically, this second method of passing the arguments might require a little bit more code, but with a large collection of arguments, there are a few advantages. First, the function itself is simplified because it accepts only one argument (args), which is a collection of all the values passed from the object literal (name, team, position, etc).</p><p>Plus, the actual argument values are easy to read, and can easily be understood, updated, or modified, since the correlation between the values and the argument references are more direct. If the function required only a small number of arguments, then this method would not be necessary, and might actually have the opposite effect. So, use this technique sparingly, and only in situations where you foresee the collection of arguments being hard to maintain over time.</p><h3>Further Reading</h3><p>· JavaScript Object Literal</p><p>· JavaScript Object Literals Simplified</p><p>· <a href="http://www.javascriptkit.com/javatutors/oopjs.shtml">JavaScript and Object-Oriented Programming (OOP)</a></p><h3>Contextual Targeting of DOM Elements</h3><p>There are sometimes instances where you need to traverse the DOM and gain access to a specific element, or group of elements, but due to certain restrictions, you may not have direct access to the elements via a CSS class name or ID in the HTML code. This might be because of user-generated content produced through a rich text editor, or dynamic content pulled from a database. Whatever the case, it’s not impossible to access those unidentified DOM elements via JavaScript.</p><p>Using what I call “contextual targeting”, you can gain access to, and modify, almost any element in the DOM. As long as you have a map of the general template that contains the element you want to target, you can access that element and manipulate it the same way you would an element that has a class name or ID. Let’s create some basic HTML code that will serve as our example page:</p><pre>&lt;div id=&quot;header&quot;&gt; &lt;h1&gt;Site Title&lt;/h1&gt; &lt;/div&gt; &lt;div id=&quot;sidebar&quot;&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Testing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Testing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Testing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Testing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Testing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Testing&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id=&quot;content&quot;&gt; &lt;h2&gt;Page Title&lt;/h2&gt; &lt;p&gt;&lt;a href=&quot;#&quot;&gt;Lorum Ipsum link here&lt;/a&gt;. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.&lt;/p&gt; &lt;p&gt;&lt;span style=&quot;color: red;&quot;&gt;Pellentesque habitant morbi&lt;/span&gt; tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.&lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;footer&quot;&gt; &lt;p&gt;Copyright | &lt;a href=&quot;#&quot;&gt;contact&lt;/a&gt; | &lt;a href=&quot;#&quot;&gt;policy&lt;/a&gt; | &lt;a href=&quot;#&quot;&gt;privacy&lt;/a&gt;&lt;/p&gt; &lt;/div&gt;</pre><p>Using the HTML code above, if we wanted to target all the anchor tags on the page, we could collect them and manipulate them like this:</p><pre>var myLinkCollection = document.<strong>getElementsByTagName(&quot;a&quot;)</strong>; for (i=0;i&lt;myLinkCollection.length;i++) { // do something with the anchor tags here }</pre><p>If we wanted to target only the anchor tags in the footer, however, we would target them based on their context, or surrounding elements, like this:</p><pre>var myFooterElement = document<strong>.getElementById(&quot;footer&quot;)</strong>; var myLinksInFooter = myFooterElement<strong>.getElementsByTagName(&quot;a&quot;)</strong>; for (i=0;i&lt;myLinksInFooter.length;i++) { // do something with footer anchor tags here }</pre><p>The first line grabs a reference to the footer element. The second line collects all &lt;a&gt; tags inside the footer.</p><p>Then we loop through them and do what we want with them. Thus, they are accessible even though they are not grouped via class names. You can accomplish the same thing by using node properties, as shown below.</p><pre>var myLinkCollection = document.<strong>getElementsByTagName</strong>(&quot;a&quot;); for (i=0;i&lt;myLinkCollection.length;i++) { if (<strong>myLinkCollection[i].parentNode.parentNode.id</strong> === &quot;footer&quot;) { // do something with footer anchor tags here } }</pre><p>Similar code could be used to target the lone anchor tag inside the “content” section. We could also limit our anchor tag search to include only tags that have the href attribute set, so as to avoid finding any in-page links. We do this by using the getAttribute method:</p><pre>var myLinkCollection = document.getElementsByTagName(&quot;a&quot;); for (i=0;i&lt;myLinkCollection.length;i++) { if (myLinkCollection[i].<strong>getAttribute(&quot;href&quot;)</strong>) { // do something with the anchor tags here } }</pre><p>Finally, you’ll notice that there is a &lt;span&gt; tag with an inline style. The inline style could have been generated through a content management system, so you may not have the ability to edit it directly. You can target all &lt;span&gt; elements with inline styles like this:</p><pre>var myLinkCollection = document.<strong>getElementsByTagName(&quot;span&quot;)</strong>; for (i=0;i&lt;myLinkCollection.length;i++) { if (myLinkCollection[i].getAttribute(&quot;style&quot;)) { // do something with all anchors that have inline styles } }</pre><p>The possibilities are endless with contextual targeting, and there are even more options available if you’re using a JavaScript library that normalizes browser differences and simplifies DOM manipulation.</p><h3>Further Reading:</h3><p>· <a href="http://reference.sitepoint.com/javascript/Document/getElementsByTagName">getElementsByTagName at Sitepoint’s JavaScript Reference</a></p><p>· getElementsByTagName at W3Schools</p><h3>Using Namespaces to Prevent Conflicts</h3><p>If you’re doing an extensive amount of raw JavaScript coding and suspect that additions could be made to the same pages you’re working on, you can prevent any future conflicts with your code by giving your code its own namespace. Object-oriented JavaScript implements namespace-like principles due to the fact that properties and methods are declared inside of objects, thus there are less likely to be conflicts. A conflict could arise, however, through object names.</p><p>And very likely, the conflict will occur “silently”, thus you may not be alerted to the issue immediately. You can prevent all conflicts by creating a unique namespace. Let’s use the showStatistics function to demonstrate how we can encapsulate code into its own namespace:</p><pre>if (typeof MY == &quot;undefined&quot;) { <br><br>MY = new Object(); MY.CUSTOM = new Object(); <br><br>} <br><br>MY.CUSTOM.namespace = function() { <br><br>function showStatistics(args) { <br><br>document.write(&quot;&lt;p&gt;&lt;strong&gt;Name:&lt;/strong&gt; &quot; + args.name + &quot;&lt;br /&gt;&quot;); document.write(&quot;&lt;strong&gt;Team:&lt;/strong&gt; &quot; + args.team + &quot;&lt;br /&gt;&quot;); if (typeof args.position === &quot;string&quot;) { <br><br>document.write(&quot;&lt;strong&gt;Position:&lt;/strong&gt; &quot; + args.position + &quot;&lt;br /&gt;&quot;); } if (typeof args.average === &quot;number&quot;) <br><br>{ document.write(&quot;&lt;strong&gt;Average:&lt;/strong&gt; &quot; + args.average + &quot;&lt;br /&gt;&quot;); } if (typeof args.homeruns === &quot;number&quot;) <br><br>{ document.write(&quot;&lt;strong&gt;Home Runs:&lt;/strong&gt; &quot; + args.homeruns + &quot;&lt;br /&gt;&quot;); } if (typeof args.rbi === &quot;number&quot;) <br><br>{ document.write(&quot;&lt;strong&gt;Runs Batted In:&lt;/strong&gt; &quot; + args.rbi + &quot;&lt;/p&gt;&quot;); } <br><br>} <br><br>showStatistics({ name: &quot;Mark Teixeira&quot;, team: &quot;New York Yankees&quot;, position: &quot;1st Base&quot;, average: .284, homeruns: 32, rbi: 101 }); } MY.CUSTOM.namespace();</pre><p>The first few lines create the namespace by checking to see if the “MY” object already exists.</p><p>This object can be whatever you want it to be. Just pick a name that you don’t think will ever be used again. After the MY the object is created, we are then able to create the “CUSTOM” object as a property of the MY object.</p><p>Then our namespace function becomes a method of the MY.CUSTOM object. Keep in mind that “MY“, “CUSTOM” and “namespace” can each be your own custom names. I chose these for demonstration purposes.</p><p>They could be CHEESEBURGER.ONIONS.pickles if you want! The showStatistics the function is exactly the same as in the example earlier that utilizes an object literal to pass in the values. But in this case, the entire function, including the object literal, is encapsulated inside my.custom.namespace.</p><p>The last line invokes the entire function using dot notation, and the function runs exactly the same as it normally would, except that it is protected from conflicting with another function called “showStatistics“.</p><h3>Further Reading:</h3><p>· <a href="http://javascript.about.com/od/objectorientedjavascript/a/oop14.htm">Object-Oriented JavaScript: Namespaces (About.com)</a></p><p>· Namespacing your JavaScript (Dustin Diaz)</p><h3>Hybrid Application Development</h3><p>You can create powerful JavaScript applications if you use a combination of a JavaScript library and raw JavaScript code. Many JavaScript libraries are used to implement “pretty” animations and other customizable effects–sometimes via plugins– that often don’t require much to be added to them other than some custom values. On the other hand, there may be situations where you’ll want to accomplish something specifically requested by a client.</p><p>Maybe it’s something not available in a library and that requires extensive coding, possibly utilizing Ajax and a variety of DOM methods. There is no point in reinventing the wheel. You can implement your favorite JavaScript library and take advantage of its simplified Ajax calls, DOM methods, and normalization of browser differences.</p><p>Thus, you can have the advantages of the library, while still creating custom scripts that are specific to your project.</p><h3>Further Reading:</h3><p>· <a href="http://en.wikipedia.org/wiki/List_of_JavaScript_libraries">List of JavaScript libraries at Wikipedia</a></p><p>· <a href="http://www.smashingmagazine.com/2009/03/02/40-stand-alone-javascript-libraries-for-specific-purposes/">40 Useful JavaScript Libraries (Smashing Magazine)</a></p><p>· <a href="http://javascriptlibraries.com/">JavaScript Libraries: A directory of tools shaping the new web</a></p><h3>Rendering Readable HTML</h3><p>Finally, this is a technique to use in situations that require dozens of lines of HTML code being generated dynamically via JavaScript. Take the following example:</p><pre>var pageContainer = document.getElementById(&quot;container&quot;); var pageTitle = &quot;Content Title&quot;; var authorBio = &quot;Mr. Lorum Ipsum&quot;; var pageContent = &quot;Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here.&quot;; var footerContent = &quot;Copyright 2009&quot;; var HTMLCode = &#39;<br><br>&lt;h1&gt;&#39; + pageTitle + &#39;&lt;/h1&gt;<br><br> &lt;div id=&quot;content&quot;&gt;<br><br> &lt;p&gt;&#39; + pageContent + &#39;&lt;/p&gt;<br><br> &lt;div id=&quot;author_bio&quot;&gt;<br><br> &lt;p&gt;&#39; + authorBio +&#39;&lt;/p&gt;<br><br> &lt;/div&gt;<br><br> &lt;/div&gt;<br><br> &lt;div id=&quot;footer&quot;&gt; &lt;p&gt;&#39; + footerContent + &#39;&lt;/p&gt;<br><br> &lt;/div&gt;<br><br>&#39;; pageContainer.innerHTML = HTMLCode;</pre><p>The line to take note of above is the one that declares the value of the HTML code variable. It renders just fine in the generated source code since it utilizes the “newline” character, so it looks like perfectly good HTML.</p><p>But if this line of code were any longer it would be extremely difficult to read and maintain in the .js file. Here is the same code as above, but implementing a much more organized method of displaying the HTML:</p><pre>var pageContainer = document.getElementById(&quot;container&quot;); var pageTitle = &quot;Content Title&quot;; var authorBio = &quot;Mr. Lorum Ipsum&quot;; var pageContent = &quot;Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here.&quot;; var HTMLCode = &#39;<br><br>&#39; + &#39;&lt;h1&gt;&#39; + pageTitle + &#39;&lt;/h1&gt;<br><br>&#39; &#39;&lt;div id=&quot;content&quot;&gt;<br><br>&#39; + &#39;&lt;p&gt;&#39; + pageContent + &#39;&lt;/p&gt;<br><br>&#39; + &#39;&lt;div id=&quot;author_bio&quot;&gt;<br><br>&#39; + &#39;&lt;p&gt;&#39; + authorBio + &#39;&lt;/p&gt;<br><br>&#39; + &#39;&lt;/div&gt;<br><br>&#39; &#39;&lt;/div&gt;<br><br>&#39; + &#39;&lt;div id=&quot;footer&quot;&gt;&#39; + &#39;&lt;p&gt;&#39; + footerContent + &#39;&lt;/p&gt;<br><br>&#39; + &#39;&lt;/div&gt;<br><br>&#39;; pageContainer.innerHTML = HTMLCode;</pre><p>Now the code is much more readable and conforms to the manner in which HTML is rendered on an actual HTML page. It even includes proper HTML indenting and still uses the new line character to properly format the outputted HTML.</p><h3>JavaScript Debugging Techniques in IE 6</h3><p>Microsoft’s Internet Explorer 6 is almost universally hated by web developers. It’s hard to work with and support, but with a few solid techniques, you can make the process less painful. What “just works” in the majority of browsers will almost always require hours of tweaks and workarounds to get it working in IE6. With more and more users switching over to newer alternatives such as IE8, Safari and Firefox hopefully support for IE6 can be dropped sooner rather than later. In the meantime though many of us have to make sure our sites work in this awful browser.</p><p>To make things worse, IE6 is extremely bad at helping developers diagnose problems.</p><p>When a JavaScript error occurs, IE6’s default behaviour is to display a small error icon in the status bar. Extremely easy to miss!</p><p>Double-clicking on this icon will display a popup, and if you then click the “Show Details” button you’ll get the actual details of the JavaScript error.</p><p>Unfortunately, the detailed error message can be quite cryptic, and probably not too much help in diagnosing the actual problem. Your best bet is to make a note of the line and column number of the problem and then look that up in the source code. Fortunately, with the help of Visual Studio and by changing a few IE settings, we can make it much easier on ourselves.</p><h3>Setting things up</h3><p>To enable JavaScript debugging in IE we need to change some default settings, which can be accessed from the Tools&gt; Internet Options menu, and then the Advanced tab. The image below shows the default IE6 settings, with the three settings we’re interested in highlighted.</p><p>Script debugging in IE needs be enabled, which requires us to disable the first option out of the three.</p><p>If you also want to debug scripts in other contexts (such as Outlook) then disable the second option. Enable the third option if you’d like the JavaScript error dialog to pop up automatically instead of being displayed as a small icon in the status bar.</p><p>After changing those settings and restarting IE, we’re ready to start debugging.</p><p>All of the following examples show Visual Studio 2005, but the same applied to 2008. You can also use the free Web Developer Express Edition if you don’t own a full copy of Visual Studio. Instead of IE prompting you to open the debugger, as it does in the examples below, you’ll first need to create a project and then start the debugger yourself. From that point on everything is the same.</p><h3>Basic debugging</h3><p>Let’s start with a simple example. The code below tries to call a function that doesn’t exist:</p><pre>&lt;script type=&quot;text/JavaScript&quot;&gt; functionDoesNotExist(); &lt;/script&gt;</pre><p>Now when we load that up into the browser instead of the tiny icon in the status bar IE will prompt us to open a debugger.</p><p>Selecting Visual Studio and clicking the yes button will open Visual Studio and highlight the code that is the cause of the problem.</p><p>For relatively simple errors, such as the one in the example above, just seeing the actual cause of the error highlighted is probably enough for us to work out what has gone wrong, and how to fix it. In more complex cases, however, we’ll need more information. This where the Visual Studio debugging features come in really handy.</p><p>In the code below we have a function, performAction, which takes a function as an argument and calls that function once it’s done. You’ll commonly see this sort of thing in JavaScript with asynchronous functions such as <a href="https://developer.mozilla.org/en/DOM/window.setTimeout">setTimeout</a> and jQuery’s <a href="http://docs.jquery.com/Ajax/jQuery.get">Get</a>. There is a problem with the code below though: We’re accidentally passing in a string to performAction rather than a function.</p><pre>&lt;script type=&quot;text/JavaScript&quot;&gt; /** * Perform an imaginary action, and then * call the callback function once we&#39;re done */ function performAction(callback) { // Perform an action here // ... // We&#39;re done, call the callback callback(); } // Call performAction with an anonymous // callback function which contains an error var myFunc = &quot;this is a string, not a function!&quot;; performAction(myFunc); &lt;/script&gt;</pre><p>If we load up the code in IE and then debug it in Visual Studio as we have before we’ll see that the code “callback();” is highlighted, and is therefore the cause of problem. It won’t be obvious why this line is causing the problem though, not unless we know what the value of callback is. If callback was actually a function then there wouldn’t be a problem at all.</p><p>The problem has only arisen because we accidentally passed in a string. This is where the “locals” window comes in handy. It lists all local variables along with their value and type.</p><p>To display this window go to the <em>Debug</em> menu, then <em>Windows</em>, and then select <em>Locals</em>.</p><p>With the locals window displayed it’s clear that the problem is that callback is a string, rather than a function. The locals window doesn’t just support basic types such as integers and strings.</p><p>If you’ve got a local object you can look at all of its properties and see the value and type of each of them, as we’ll see in the next example.</p><h3>The ‘debugger’ keyword</h3><p>The ‘debugger’ keyword, also supported by the Firefox JavaScript debugger Firebug, can really help us to track down problems. Below is a slightly modified version of the previous example, where this time the callback function is passed an object that should include a status and message property. The message property has been misspelled though:</p><pre>&lt;script type=&quot;text/JavaScript&quot;&gt; /** * Perform an imaginary action, and then * call the callback function once we&#39;re done */ function performAction(callback) { // Perform an action here // ... // We&#39;re done, call the callback callback({success: true, mesage: &#39;The action was performed!&#39;}); } // Call performAction with an anonymous // callback function which contains an error performAction(function(response) { alert(response.message); }); &lt;/script&gt;</pre><p>Because ‘message’ has been misspelled as ‘message’ in the perform action function when we run this code in IE we’ll see a popup alert with the message “undefined”, rather than the actual message we were hoping to see.</p><p>In a large project it can be difficult to track down why a property we expect to exist is undefined. Instead of trawling through lots of code we can simply add the line “debugger;” above the alert statement.</p><p>IE will then automatically prompt us to debug the code in Visual Studio when it hits that line. From the local’s window, we can see that the ‘message’ property has been misspelled.</p><p>Using the call stack window, which can be accessed in the same way we accessed the locals window, shown at the bottom right of the above screenshot we can work out exactly where this problem occurred.</p><p>If we double click on the ‘performAction’ line, the previous statement in the call stack, we’ll see the source of the error.</p><p>While debugger statements can be a useful tool in helping you track down problems you should be careful not to leave them in your production code!</p><h3>More advanced debugging</h3><p>So far we’ve covered some basic examples, such as calling non-existent functions and undefined properties. Using the locals and call stack windows it was relatively straight forward to track these issues down. There are times when the techniques we’ve discussed so far can’t help though.</p><p>We can’t see what global variables exist or what value they have with the locals window, for example, and the call stack doesn’t always handle remotely loaded or dynamically executed code very well. For these situations we must turn to the immediate window. It is by far the most powerful debugging tool that Visual Studio has to offer, allowing us to evaluate JavaScript expressions on the fly.</p><p>The immediate window can be accessed in the same way that we accessed the other windows. Clicking inside the window will give it focus. We can then type JavaScript statements directly into the window and see the result.</p><p>For example, type “window” followed by enter and you’ll get a print out of everything in the global scope.</p><p>When combined with the JavaScript <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/Arguments">arguments</a> variable we can look in detail at all the current function arguments and the calling function. While the code in the next example isn’t something you’re likely to see in a real project, it does help to demonstrate techniques that can be extremely useful.</p><pre>&lt;script type=&quot;text/JavaScript&quot;&gt; /** * This function takes a variable number of arguments. */ function performAction() { // We&#39;re just interested in the immediate // window, start the debugger debugger; } // Call performAction with 4 different arguments, each of a different type performAction(&#39;argument 1&#39;, 2, {argument: 3}, function() { return 4; }); &lt;/script&gt;</pre><p>We’ll load this up into IE and then go straight to the immediate window once we’ve opened up the debugger. If we type “arguments” followed by enter we’ll see the following information displayed:</p><pre>arguments {...} [0]: &quot;argument 1&quot; [1]: 2 [2]: {...} caller: null length: 4</pre><p>The “{…}” tells us that arguments is an object. We also see this next to [2], so we know that the third argument (in array position 2) is an object.</p><p>We can see what properties this object has by simply typing its name into the window:</p><pre>arguments[2] {...} argument: 3</pre><p>The fourth argument wasn’t listed in the original output because it’s a function. We know it exists though because the length property tells us that there are 4 arguments. We can also confirm it is there using typeof:</p><pre>typeof arguments[3] &quot;function&quot;</pre><p>Unfortunately the immediate window isn’t quite so helpful with functions as it is objects, and if we type in the name of the function we just see “{…}” rather than any details of the function itself.</p><p>Fortunately there is a handy workaround. If we type “alert(arguments[3]);” then the function code will be displayed in an alert dialog:</p><p>Hopefully, these examples have conveyed just how powerful the immediate window is.</p><h3>10 Promising JavaScript Frameworks</h3><p>Popular JavaScript frameworks/libraries like jQuery, MooTools, Prototype and YUI (to name a few of the <a href="http://royal.pingdom.com/?p=305">most popular JavaScript frameworks out there</a>) definitely have a solid foothold in the JavaScript framework arena. But for the more adventurous developers looking for new or alternative frameworks/libraries — there are some excellent frameworks outside the popular ones that are worth checking out. It’s always good to consider all of your options before settling on a JavaScript framework that’s right for you and/or your team — and though there’s definitely a lot of compelling reasons to stick to the big names — it won’t hurt you any to <em>at least try</em> the alternatives.</p><p>This article showcases <strong>10 alternative and capable JavaScript frameworks/libraries to explore</strong>. Links to some of their demos (when available) are included in the entry so that you can see the framework in action.</p><h3>1. SproutCore</h3><p><em>SproutCore</em> distinguishes itself by emphasizing its usage for bringing desktop application functionalities on the web. It’s got a healthy amount of easy-to-follow guides to get you going quickly and its own <a href="http://groups.google.com/group/sproutcore">Google Group</a> for your questions and for interacting with other SproutCore developers. <strong>SproutCore demonstrations: Photos, Sample Controls</strong></p><h3>2. Spry</h3><p><em>Spry</em> is Adobe’s Ajax framework. One of the many distinctive features of Spry is its tight integration with Adobe products (such as Dreamweaver, Flash and AIR). Just like any Adobe product, there’s already a ton of documentation to help you get started with Spry quickly.</p><p><strong>Spry demonstrations: Photo Gallery, RSS Reader, Form Validation Widgets</strong></p><h3>3. JavaScriptMVC</h3><p><em>JavaScriptMVC</em> is a featured-packed JavaScript framework. JSMVC applies the <a href="http://en.wikipedia.org/wiki/Model-view-controller">Model-View-Controller</a> (MVC) architectural pattern to JavaScript, separating business logic from the presentation layer — resulting in increased modularity and ease-of-modification for either one of the components. It has a built-in automated testing unit (because “JavaScript testing sucks”) and even emails you when a user encounters an error.</p><p><strong>JavaScriptMVC demonstrations: Error Demo, History Demo, Todo Demo</strong></p><h3>4. <a href="http://qooxdoo.org/">qooxdoo</a></h3><p><em>qooxdoo</em> is an Ajax application framework that uses object-oriented JavaScript. It’s a framework that allows you to build a web application using JavaScript without worrying about HTML, CSS, and the DOM. It’s also a fully-featured graphical user interface toolkit (much like YUI) giving the developer built-in support for keyboard navigation, tabbed interfaces, and drag and drop capabilities — among other components.</p><p><strong>Qooxdoo demonstrations: demo browser, Feed Reader</strong></p><h3>5. midori</h3><p><em>midori</em> is a light-weight JavaScript framework. At it’s <em>uncompressed state</em>, it weighs in at only 45 KB (in comparison — jQuery in it’s <em>minified state</em> is 54KB). But just because its light doesn’t mean it’s lacking in complex JavaScript functions — midori offers common functions you’d expect from an JavaScript framework such as cross-browser Ajax functions, the ability to use CSS selectors (as opposed to midori-specific syntax) for matching elements in the DOM, and animated effects.</p><p><strong>midori demonstrations: drag and drop, popups, toggle</strong></p><h3>6. Archetype JavaScript Framework</h3><p>The <em>Archetype JavaScript Framework</em> is a robust JavaScript framework that shares a lot of things in common with <a href="http://prototypejs.org/">Prototype</a>. Archetype has a dependency management system which initializes needed components for particular web pages(what components and CSS file to load — for example). Archetype also emphasizes code readability and coding best practices by being hard-lined about HTML/CSS/JavaScript separation (i.e.</p><p>“unobtrusive JavaScript”) . <strong>Archetype demonstration: Slidy Presentation</strong></p><h3>7. June Framework</h3><p>The <em>June Framework </em>was inspired by the <a href="http://www.sitepoint.com/blogs/2007/08/29/simply-javascript-the-core-library/">Core library</a> and uses the Module design pattern. For those using MS Visual Studio 2008, you’ll love the documentation that comes with the June Framework because it utilizes Visual Studio’s intellisense format (code hints/auto-completion while you write). <strong>June Framework demonstrations: setOpacity, highlight, getKeyName</strong></p><h3>8. <a href="http://www.uize.com/">UIZE</a></h3><p><em>UIZE</em> (pronounced “you eyes”) is another JavaScript framework the emphasizes the creation of full-on rich internet applications (RIA) as opposed to basic effects and widgets/components on a web page. It already comes packed with “ready-to-go” widgets such as a date picker, a table sorter, progress bar, and color picker. <strong>UIZE demonstrations: </strong><a href="http://www.uize.com/examples/slideshow-with-wipes.html"><strong>Slideshow With Wipes</strong></a><strong>, </strong><a href="http://www.uize.com/examples/marquee-and-image-port.html"><strong>Marquee and Image Port</strong></a></p><h3>9. SimpleJS</h3><p><em>SimpleJS</em> is a simple and lightweight, but feature-packed JavaScript framework with Ajax helper functions and animation effects. It uses a “plugins” system much like jQuery and MooTools to extend the framework. It’s the perfect solution for developers who don’t need much outside of basic Ajax functions and effects.</p><p><strong>SimpleJS demonstration: </strong>you can view the demos in the left side bar of the website under “Functions”.</p><h3>10. Fleegix.js</h3><p><em>Fleegix.js</em> has an excellent “events system” that helps you listen, manipulate, and fire off DOM event (such as mouseover’s, onclick, etc.). It includes a function for serializing JavaScript objects into JSON format (fleegix.jason.serialize) and — because every other JavaScript framework has it — an awesome effects module to help you add rich, animated JavaScript animation onto your web page or web application.</p><p>Thanks for reading I hope you like my article.</p><p>Havae a nice day 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a269f7f772a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>