Basics of Javascript

Over the past couple of years, Javascript has established itself as one of the 3 most important aspects of creating websites on the Internet. HTML provides the content and structure of web pages, CSS provides the style and presentation, and Javascript powers the interactivity that has come to represent the next wave of web site design and development.

If you have been creating websites for more than just the last few years, you will probably remember a time when Javascript was purely used for dynamic effects on web pages. Websites like Dynamic Drive offered just about every tacky effect you could think of.

Why is Javascript so important?

However, recently Javascript has established itself as much more than a way to add dynamic effects to web pages. Since the launch of GMail, Javascript has become the standard way to build software like experiences in the browser. It is now possible to build rich, interactive user interfaces and powerful synchronous web applications that can be served through the browser.

Part of this renaissance has been due to the growth of hot new frameworks that enable developers to build rich, concurrent and interactive experiences.

Examples include:

  • JQuery – A JavaScript library designed to simplify the client-side scripting of HTML
  • Backbone.js – A MVC framework for Javascript applications
  • Node.js – Event-driven I/O server-side JavaScript environment based on Google’s V8 engine
  • Moo Tools – A lightweight Javascript framework
  • Spine.js – A MVC framework for Javascript

For examples of the powerful and rich user interfaces and experiences that are possible in Javascript, you only have to look at the latest and hottest web companies.

Twitter, foursquare and Wunderkit are just some of the many examples of companies that are using Javascript to make amazing new websites.

Javascript is probably one of the most important tools in any developers toolkit. I believe everyone who works on the Internet should have an understanding of HTML and CSS, but Javascript is quickly establishing itself as the third pillar of those need to know languages.

As a web developer, Javascript will probably be one of the most important languages you will need going forward. It doesn’t matter if a Web Application is built using Ruby, or PHP or Python, Javascript will always be at the foundation of an amazing user interface.

With that in mind, you should really should start getting to grips with Javascript today.

Here is an overview of the basics of Javascript.

Setting up the stage

So the first thing we will do is to set up the stage to work on. Copy and paste the following into a new HTML file.

<!doctype html>  
<html lang="en">  
  
<meta charset="utf-8">  
<script>

</script>  
  


 
  

Now for the rest of the tutorial, you need to be writing your Javascript in between the two script tags.

Alternatively, if you are using a browser with a Javascript console (such as Chrome), you can use that for the majority of this tutorial. In Chrome go to Tools >Javascript Console.

Variables

Variables are how you store pieces of information in Javascript. Imagine a variable as a box. You can place something into the box. In the future you can then replace that thing in the box with something else. Storing and manipulating data and information is basically the core of all programming languages.

When creating a new variable, we tell Javascript that this is a variable by using the “var” keyword. We then give a name for our variable and then set it to something using the equals sign.

For example:

var name = "Philip";  

In the example above, I’m setting the name variable to equal my name. “Philip” is a string, but you can also set variables to equal other things.

For example:

var age = 24;  
var man = true;  
var version = 1.0;  

In the examples above, age is an Integer (whole number), man is a boolean (true of false) and version is a float (a number with a decimal point).

Variables are dynamic in that you don’t need to set their type when you create them.

For example, you could write this series of statements.

var apple = "fruit";  
apple = 99;  
apple = true;  
apple = "green";  

After you store a piece of information into a variable, you can reference it or recall it by just using the variable name you chose.

Global functions

So if you’ve been writing the Javascript into your HTML page up until this point, it will have been pretty boring. However, Javascript has some inbuilt functions that allow you to do some pretty useful stuff.

Alert

The first global function is the alert. The alert function will present an alert message to the screen.

For example:

alert("What up player?");  

Confirm

The slightly more advanced message popup is the confirm box. The confirm box allows you to take your first steps to interacting with your user. The confirm box will present your user with two options, either “Ok” or “Cancel” which represent true or false. You can then use this response to do some interesting things.

For example:

var response = confirm("Yo homes, we chillin’ tonight?");  
if(response == true){  
alert("Sho nuff");  
}else{  
alert("No problem homie, hit me up some other time");  
}  

In the example above, we pop a confirm box to get a true or false reply. We then use an if statement to pop an alert depending on the response.

Prompt

The prompt box allows you to request that your user enters some information.

For example:

var name = prompt("Yo dawg, what’s your name");  
alert("What up " + name);  

When the user enter’s their name into the prompt box, the name is stored into the name variable. By default the response is a string.

We then use an alert to display the name back to the user. Notice how we can combine a string “What up ” with a variable by using the + symbol.

String functions

Javascript has some useful functions built in to help you work with strings.

For example:

"Culttt".toLowerCase();  
// returns "culttt  

Take a look at the structure of that last line. First we have the string. Then a full stop then the function name and then open and close parentheses. This is called Dot Notation.

Some other useful string functions include:

"Culttt".toUpperCase(); // Returns "CULTTT"  
"Culttt".charAt(1); // Returns "u"  
"What’s up John".replace("John", "Philip"); // Returns "What’s up Philip"  
"Philip Brown".split(" "); // Returns ["Philip", "Brown"]  

From top to bottom:
toUpperCase() – Returns all characters transformed to uppercase.
charAt() – Returns the character at the defined position. The count begins at 0. So in this example, C = 0, u = 1.
replace() – Replaces the first input with the second.
split() – Split the string based on an input. In this example I’m splitting the string where there is a space.

The final thing I will show you with strings is the length attribute.

"Culttt".length; // Returns 6  

Notice how we don’t use parentheses. This is because length is an attribute of the string and it is one of the most common attributes you will encounter in Javascript. Watch that you don’t put the parentheses on by mistake. This will cause your code to break because it will look for a function called length.

Working with numbers

Using and manipulating numbers is really easy in Javascript.

For example:

2 + 2;  
10 – 7;  
3 * 3;  
100 / 20;  

The % sign is called Modulus and returns the remainder of a calculation.

For example:

var remainder = 5 % 2; // Returns 1  

You can also increment or decrement numbers using the ++ or — symbols.

For example:

10++; // 11  
10–; // 9  

Number related functions

There are a couple of common number related functions that you should be aware of.

Firstly parseInt(); will take a take a string and return the integer. This is useful when you are receiving input from the user, but the user might not give you the right type of data.

For example;

parseInt("99 red balloons); // Returns 99  

This function simply looks for the first thing that could be a number. It is not a flawless way of interpreting input.

Secondly, toString() converts an integer to a string.

For example:

99.toString(); // Returns "99"  

Arrays

Variables are used for saving single items of data. However, in most cases, you will need to save multiple items of data all together.

For example, you might have the following variables:

var firstName = "Philip";  
var secondName = "Brown";  
var age = 24;  
var website = "Culttt";  

This is a horrible way to work with data because I can’t select everything as a “person”.

Arrays allow you to store many different bits of data as a single object.

For example:

var person = ["Philip", "Brown", 24, "Culttt"];  

As you can see, I can now work with this data as a single object. Arrays are created using square brackets and each bit of data is separated by a comma. You can mix any different datatypes in array.

If you want to work with a particular element of the array and you know it’s position, you can use the array name with square brackets and the position to pull that piece of data.

For example:

person[0]; // Returns "Philip"  

Arrays are zero indexed and so the first item is always at position 0.

To find the length of an array, you can use the length attribute that we looked at during strings.

For example:

person.length; // Returns 4  

Finally, reverse() will flip your array. This function does not alter the original array, it will make a copy of your array and show you the copy. If you were to access the original array again, it would still be intact.

For example:

var numbers ["Do", "Re", "Mi"];  
numbers.reverse(); // Returns ["Mi", "Re", "Do"]  

Conclusion

That was a quick overview of variables, arrays and some common functions that you will find useful as you start learning Javascript. Javascript is a great language to start learning because it allows you to do some really interesting stuff right in the browser.

If you are eager to keep on learning, take a look at my Really simple inline Javascript validation post.

If you have any questions, leave a comment and I’ll try and help you out!

Basics of Javascript
Share this