JavaScript Best Practices

Avoid global variables,  avoid new,  avoid  ==,  avoid eval() Avoid Global Variables Minimize the use of global variables. This includes all data types, objects, and functions. Global variables and functions can be overwritten by other scripts. Use local variables instead, and learn how to use closures. Always Declare Local Variables All variables used in a function […]

JavaScript Hoisting

Hoisting is JavaScript’s default behavior of moving declarations to the top. JavaScript Declarations are Hoisted In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared. Example 1 gives the same result as Example 2: Example 1 x = 5; // Assign 5 to x […]

JavaScript Sorting Arrays

The sort() method sorts an array alphabetically: Example var fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; fruits.sort();        // Sorts the elements of fruits Try it Yourself » Reversing an Array The reverse() method reverses the elements in an array. You can use it to sort an array in descending order: Example var fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; fruits.sort();        // First sort the elements of fruits fruits.reverse();     // Then reverse the […]

JavaScript Numbers

JavaScript has only one type of number. Numbers can be written with or without decimals. Example var x = 3.14;    // A number with decimals var y = 3;       // A number without decimals Try it yourself » Extra large or extra small numbers can be written with scientific (exponent) notation: Example var x = 123e5;    // 12300000 var y = 123e-5;   // 0.00123 JavaScript Numbers are […]

JavaScript Scope

Scope determines the accessibility (visibility) of variables. JavaScript Function Scope In JavaScript there are two types of scope: Local scope Global scope JavaScript has function scope: Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function. Local JavaScript […]

JavaScript Output

JavaScript Display Possibilities JavaScript can “display” data in different ways: Writing into an HTML element, using innerHTML. Writing into the HTML output using document.write(). Writing into an alert box, using window.alert(). Writing into the browser console, using console.log(). Using innerHTML To access an HTML element, JavaScript can use the document.getElementById(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content: […]

HTML JavaScript

JavaScript makes HTML pages more dynamic and interactive. Example My First JavaScript Click me to display Date and Time Try it Yourself » The HTML <script> Tag The <script> tag is used to define a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript […]