JavaScript Building Blocks

JavaScript Building Blocks

I'm going to discuss JavaScript building-blocks for beginners.

JavaScript Write

JavaScript can write to a web document.
  • If you are writing to a document using double-quote encapsulation, you must escape all double-quotes in your content with a backslash ( \ ) symbol.
  • If you are writing to a document using single-quote encapsulation, you must escape all single-quotes in your content with a backslash ( \ ) symbol.
Write content using double-quote encapsulation
  1. <script type="text/javascript">  
  2.     document.write("<h3>Joe's BBQ Shack</h3>");  
  3.     document.write("<p>I named my restaurant \"Joe's BBQ Shack\"</p>");  
  4. </script> 
Write content using single-quote encapsulation
  1. <script type="text/javascript">  
  2.     document.write('<h3>Joe\'s BBQ Shack</h3>');  
  3.     document.write('<p>I named my restaurant "Joe\'s BBQ Shack"</p>');  
  4. </script> 
Combining strings using the "+" addition operator
  1. <script type="text/javascript">  
  2.     document.write("We can " + "combine strings " + "usimg the addition operator.");  
  3. </script> 

JavaScript Comments

Comments are used for human reading only usually. They are not processed by the browser software.
  • They are handy for leaving yourself notes in large scripts, or for disabling entire sections of code for troubleshooting faulty code.
  • They can be placed anywhere in your JavaScript.
  1. <script type="text/javascript">  
  2.     // This is a single line comment  
  3.     /* This is a single line comment */  
  4.     /* This multiline comment will not be processed by the browser software when the script runs*/  
  5. </script> 

JavaScript Variables

Think of a variable as a container in which you can place any literal values into, or assign it to represent an object that you have created.
The variable value can be changed or have operations performed on them. Every variable you create in JavaScript is associated to an object or data type that you can access the properties and methods of.
  1. <script type="text/javascript">  
  2.     var a = 5;  
  3.     var b = 3;  
  4.     var c = a + b;  
  5.     document.write("Answer to the problem is: " + c);  
  6.     document.write("<hr / >");  
  7.     var person1 = "Bill";  
  8.     var person2 = "Sara";  
  9.     var myText = person1 + " went to school with " + person2;  
  10.     document.write(myText);  
  11. </script> 
Alter a variable's value at any point in your script:
  1. <script type="text/javascript">  
  2.     var a = 5; // initialize the variable near the top of script  
  3.     a = 10; // alter the variable value any time you need to in script  
  4.     var b = 3;  
  5.     var c = a + b;  
  6.     document.write("Answer to the problem is: " + c);  
  7.     document.write("<hr / >");  
  8.     var person1 = "Bill";  
  9.     var person2 = "Sara";  
  10.     var myText = person1 + " went to school with " + person2;  
  11.     document.write(myText);  
  12. </script> 
Variables can also represent  JavaScript objects you might work with.
  1. <script type="text/javascript">  
  2.     var now = new Date();  
  3.     document.write(now);  
  4. </script> 

JavaScript Objects

Objects are the data types of JavaScript. Each variable that you create or literal value that you work with is an object that has specific methods and properties that you can access when working with that type of data, which is one of the biggest aspects of understanding any modern scripting language.
JavaScript also allows a script author to create custom objects to extend the language. JavaScript supports automatic data type casting for objects. This simply means that we do not have to explicitly define each variable's data type as we create them unless our script demands it.
JavaScript will interpret the value and assign it a data type (data object) automatically if one is not specified by you.
Objects, Properties, and Methods Explained
Once the object is created in your script (which we have tons of examples for), you can then access or manipulate its properties and perform any methods associated with that object's data type.
Here is a good way to view Objects, accessing their Properties, and perform their Methods.
  • Object = Gun
  • Properties | color = "Black" | maker = "Bushmaster" | type = "Assault Rifle"
  • Methods = shoot(), safety(), reload()
NOTE: Many times the property values of an object will affect its methods in various ways.
JavaScript Standard Objects
  • String Object- For working with string data in JavaScript.
  • Array Object- For compartmentalized data processing.
  • Date Object- For date and time programming.
  • Math Object- For mathematical calculations in JavaScript.
  • Number Object- For working with numeric data in JavaScript.
  • RegExp Object- For matching the text against a pattern.
  • Boolean Object- For representing false and true values.
  • Function Object- For calling dormant segments of your code to run.
  • object Object- Extend JavaScript by creating your own custom objects

JavaScript Functions

Functions are segments of your script that do not run until they are called to execute in your document.
  • They can be executed by HTML events or JavaScript events, and they will only run when that event fires off.
  • The various examples below lend good insight into the aspects of function creation.
Any user-initiated event can make your function run
  1. <script type="text/javascript">  
  2.     function myFunction()  
  3.     {  
  4.         var status = document.getElementById("status");  
  5.         status.innerHTML = "Sonia Vishvkarma";  
  6.     }  
  7. </script>  
  8. <p>  
  9.     <input type="button" value="Click Me" onclick="myFunction()">  
  10. </p>  
  11. <h3 id="status"></h3> 
An event of the window or document can make your function run
  1. <script type="text/javascript">  
  2.     function myFunction()  
  3.     {  
  4.         var status = document.getElementById("status");  
  5.         status.innerHTML = "The page finishing loading made my function run.";  
  6.     }  
  7.     window.onload = myFunction;  
  8. </script>  
  9. <h3 id="status"></h3> 
Make your functions more powerful by adding arguments
Arguments are an aspect of function creation that makes your functions much more dynamic, useful and reusable.
You can apply one or more arguments to your functions if applying multiple arguments be sure to separate each by a comma.
  1. <script type="text/javascript">  
  2.     function myFunction()  
  3.     {  
  4.         var status = document.getElementById("status");  
  5.         status.innerHTML = "The page finishing loading made my function run.";  
  6.     }  
  7.     window.onload = myFunction;  
  8. </script>  
  9. <h3 id="status"></h3> 

JavaScript Conditions

Condition statements are used to evaluate things and add logic to your scripts.
To create a wide variety of logic for your conditional evaluations, check out all of the Comparison Operators JavaScript comes equipped with.
Full understanding of the Comparison Operators is essential for conditional programming.
  • if-else...
  • switch....break
  • ternary
Where any condition returns a value of "true", the if / else statements will stop processing and execute code nested in that winning condition.
The if statement always goes on top and starts the evaluations. The if statement can also be used by itself without the else and else if.
The optional multiple else if statements go in between the if and the else and allow you to evaluate many more conditions in that particular evaluation group.
The else statement always goes on the bottom and is relevant when no conditions are met (final clause).
  1. <script type="text/javascript">  
  2.     var a = 5;  
  3.     var b = 3;  
  4.     if (a < b)  
  5.     {  
  6.         document.write(a+" is less than "+b);  
  7.     }  
  8.     else if (a > b)  
  9.     {  
  10.         document.write(a+" is greater than "+b);  
  11.     }  
  12.     else  
  13.     {  
  14.         document.write(a+" must therefore be equal to "+b);  
  15.     }  
  16. </script> 
switch statements evaluate for a match against the argument you pass through it and a specific set of values.
Break stops the switch statement from further processing if a match is found if you leave it out the switch statement will continue.
Default is similar to the else statement in which it is a final clause when no match is found.
  1. <script>  
  2.     var country = "USA";  
  3.     switch (country)  
  4.     {  
  5.         case "UK":  
  6.             document.write("UK citizens are known for being drunk.");  
  7.             break;  
  8.         case "USA":  
  9.             document.write("USA citizens are known for being dumb.");  
  10.             break;  
  11.         default:  
  12.             document.write("No match for value: "+country);  
  13.     }  
  14. </script> 
The ternary conditional operator( ? ) is not a statement but it creates conditional logic just the same so I am including it here.
It will return the value on the left of the colon ( : ) if the expression is true, and return the value on the right of the colon if the expression is false.
  1. <script>  
  2.     var a = 5;  
  3.     var b = 3;  
  4.     var result = (a > b) ? "That is true" : "That is false";  
  5.     document.write(result);  
  6. </script> 

JavaScript Loops

Loops are JavaScript statements that allow you to process code in a looping fashion.
You can also use them to process any custom code repeatedly, or iterate over arrays and object properties. Loops run lightning-fast and are extremely useful for information processing and animations.
All a programmer has to watch out for when scripting loops is creating infinite (never-ending) or extremely large loops that will exceed the document's processing threshold.
These are the standard loop mechanisms JavaScript comes equipped with: 
  • for
  • for. in
  • while
  • do. while
The following is a very basic example of a scripting loop to process items of an array:
  1. <script>  
  2.     var techArray = new Array("HTML","CSS","Javascript","PHP");  
  3.     for (var tech in techArray)  
  4.     {  
  5.         document.write(techArray[tech] + " is awesome!<br />");  
  6.     }  
  7. </script> 

JavaScript Alert Box

A JavaScript alert is a general-purpose information box that stops the document from processing until the user acknowledges it by pressing "OK".
In this code example, we will combine some HTML event handling into our JavaScript so that the window will not appear until you press the HTML button.
  1. <script type="text/javascript">  
  2.     function alertUser(str)  
  3.     {  
  4.         alert(str); // make the popup appear  
  5.     }  
  6. </script>  
  7. <input type="button" value="Crick Me!" onclick="alertUser('Welcome !')"

JavaScript Confirm Box

A JavaScript confirm box is a way to make sure your users explicitly confirm an action, especially handy for making sure the user wants to actually continue with an action where things might be deleted or altered in a big way. 
  1. <script type="text/javascript">  
  2.     function runCheck()  
  3.     {  
  4.         var c = confirm("Are you sure you want to do that?");  
  5.         var status = document.getElementById("status");  
  6.         if (c == true)  
  7.         {  
  8.             status.innerHTML = "You confirmed, thanks";  
  9.         }  
  10.         else  
  11.         {  
  12.             status.innerHTML = "You cancelled the action";  
  13.         }  
  14.     }  
  15. </script>  
  16. <input type="button" value="Perform Action" onclick="runCheck()">  
  17. <h2 id="status"></h2> 

JavaScript Prompt Box

A JavaScript prompt window (aka "prompt box") is used to request a value from the user. You can use this to prompt a user for their password before continuing with a secure action.
Prompt takes two parameters. The first parameter is the message you want the user to read about the value they are supplying.
The second parameter is an optional default value that will be pre-filled into the text field of the prompt window.
prompt('your message to the user', 'prefilled string')
  1. <script type="text/javascript">  
  2.     function myPrompt()  
  3.     {  
  4.         var promptValue = prompt('Supply us with a value below:''');  
  5.         if (promptValue != null)  
  6.         {  
  7.             document.getElementById("status").innerHTML = promptValue;  
  8.         }  
  9.     }  
  10. </script>  
  11. <p>  
  12.     <input type="button" value="Supply Value" onclick="myPrompt()">  
  13. </p>  
  14. <h3 id="status">  
  15.     status...  
  16. </h3> 


Through this article, you will become familiar with the basics of JavaScript.