Reader Level:
Articles

JavaScript Building Blocks

By Sonia Bhadouria Vishvkarma on October 18, 2012
I'm going to discuss JavaScript building-blocks for beginners.
  • 1
  • 0
  • 2686

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

<script type="text/javascript">

    document.write("<h3>Joe's BBQ Shack</h3>");

    document.write("<p>I named my restaurant \"Joe's BBQ Shack\"</p>");

</script


Write content using single-quote encapsulation

<script type="text/javascript">

    document.write('<h3>Joe\'s BBQ Shack</h3>');

    document.write('<p>I named my restaurant "Joe\'s BBQ Shack"</p>');

</script>

write-content-double-single-quote-in-javascript.png

 

Combining strings using the "+" addition operator

 

<script type="text/javascript">

    document.write("We can " + "combine strings " + "usimg the addition operator.");

</script>

 

addition-operator-in-javascript.png

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.

<script type="text/javascript">

    // This is a single line comment

    /* This is a single line comment */

    /* This multiline comment will not be processed by the browser software when the script runs*/

</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.

<script type="text/javascript">

    var a = 5;

    var b = 3;

    var c = a + b;

    document.write("Answer to the problem is: " + c);

    document.write("<hr / >");

    var person1 = "Bill";

    var person2 = "Sara";

    var myText = person1 + " went to school with " + person2;

    document.write(myText);

</script>


variables-in-javascript.png

Alter a variable's value at any point in your script:

<script type="text/javascript">

    var a = 5; // initialize the variable near the top of script

    a = 10; // alter the variable value any time you need to in script

    var b = 3;

    var c = a + b;

    document.write("Answer to the problem is: " + c);

    document.write("<hr / >");

    var person1 = "Bill";

    var person2 = "Sara";

    var myText = person1 + " went to school with " + person2;

    document.write(myText);

</script>


alter-variables-in-javascript.png

Variables can also represent  JavaScript objects you might work with.

<script type="text/javascript">

    var now = new Date();

    document.write(now);

</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. Which 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 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

 

<script type="text/javascript">

    function myFunction()

    {

        var status = document.getElementById("status");

        status.innerHTML = "Sonia Vishvkarma";

    }

</script>

<p>

    <input type="button" value="Click Me" onclick="myFunction()">

</p>

<h3 id="status"></h3>

 

user-initiated-event-in-javascript.png

An event of the window or document can make your function run 

<script type="text/javascript">

    function myFunction()

    {

        var status = document.getElementById("status");

        status.innerHTML = "The page finishing loading made my function run.";

    }

    window.onload = myFunction;

</script>

<h3 id="status"></h3>


event-window-in-javascript.png

Make your functions more powerful by adding arguments

Arguments are an aspect of function creation that make 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.

<script type="text/javascript">

    function myFunction()

    {

        var status = document.getElementById("status");

        status.innerHTML = "The page finishing loading made my function run.";

    }

    window.onload = myFunction;

</script>

<h3 id="status"></h3>


arguments-in-javascript.png

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

if else...

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).

<script type="text/javascript">

    var a = 5;

    var b = 3;

    if (a < b)

    {

        document.write(a+" is less than "+b);

    }

    else if (a > b)

    {

        document.write(a+" is greater than "+b);

    }

    else

    {

        document.write(a+" must therefore be equal to "+b);

    }

</script>


if-else-in-javascript.png

switch...break

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. 

<script>

    var country = "USA";

    switch (country)

    {

        case "UK":

            document.write("UK citizens are known for being drunk.");

            break;

        case "USA":

            document.write("USA citizens are known for being dumb.");

            break;

        default:

            document.write("No match for value: "+country);

    }

</script>


switch-break-in-javascript.png

ternary

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.

<script>

    var a = 5;

    var b = 3;

    var result = (a > b) ? "That is true" : "That is false";

    document.write(result);

</script>


ternary-in-javascript.png

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:

<script>

    var techArray = new Array("HTML","CSS","Javascript","PHP");

    for (var tech in techArray)

    {

        document.write(techArray[tech] + " is awesome!<br />");

    }

</script>


loops-in-javascripe.png

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. 

<script type="text/javascript">

    function alertUser(str)

    {

        alert(str); // make the popup appear

    }

</script>

<input type="button" value="Crick Me!" onclick="alertUser('Welcome !')">


alert-1-in-javascript.png

alert-2-in-javascript.png

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. 

<script type="text/javascript">

    function runCheck()

    {

        var c = confirm("Are you sure you want to do that?");

        var status = document.getElementById("status");

        if (c == true)

        {

            status.innerHTML = "You confirmed, thanks";

        }

        else

        {

            status.innerHTML = "You cancelled the action";

        }

    }

</script>

<input type="button" value="Perform Action" onclick="runCheck()">

<h2 id="status"></h2>

 

confirm-1-javascript.png

confirm-2-in-javascript.png

confirm-3-in-javascript.png

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')

<script type="text/javascript">

    function myPrompt()

    {

        var promptValue = prompt('Supply us with a value below:', '');

        if (promptValue != null)

        {

            document.getElementById("status").innerHTML = promptValue;

        }

    }

</script>

<p>

    <input type="button" value="Supply Value" onclick="myPrompt()">

</p>

<h3 id="status">

    status...

</h3>

prompt-box-1-in-javascript.png
prompt-box-2-in-javascript.png

prompt-box-3-in-javascript.png

prompt-box-4-in-javascript.png

Summary

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

COMMENT USING

Trending up