Tampilkan postingan dengan label Java Script Basic. Tampilkan semua postingan
Tampilkan postingan dengan label Java Script Basic. Tampilkan semua postingan

Minggu, 30 September 2012

JavaScript Variables

 JavaScript Variables


Variables are "containers" for storing information:

JavaScript Data Types

var answer1="He is called 'Johnny'";
var answer2='He is called "Johnny"';
var pi=3.14;

var x=123;

var y=123e5;
var z=123e-5;

var cars=new Array("Saab","Volvo","BMW");
var person={firstname:"John", lastname:"Doe", id:5566};



Like School Algebra

Remember algebra from school?
x=5
y=6
z=x+y
Do you remember that letters (like x) can be used to hold a value (like 5), and that you can use the information above to calculate the value of z to be 11?
These letters are called variables, and variables can be used to hold values (x=5) or expressions (z=x+y).
lamp Think of variables as names or labels given to values.


JavaScript Variables

As with algebra, JavaScript variables are used to hold values or expressions.
Variable can have a short names, like x and y, or more descriptive names, like age, sum, or, totalvolume.
JavaScript variables can also be used to hold text values, like: name="John Doe".
Here are the rules for JavaScript variable names:
  • Variable names are case sensitive (y and Y are two different variables)
  • Variable names must begin with a letter, the $ character, or the underscore character
lamp Both JavaScript statements and JavaScript variables are case-sensitive.


Declaring (Creating) JavaScript Variables

Creating a variable in JavaScript is most often referred to as "declaring" a variable.
You declare JavaScript variables with the var keyword:
var carname;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:

carname="Volvo"; 

However, you can also assign a value to the variable when you declare it:
 
var carname="Volvo";

In the example below we create a variable called carname, assigns the value "Volvo" to it, and put the value inside the HTML paragraph with id="demo":

Example

<p id="demo"></p>
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;



lamp It's a good programming practice to declare all the variables you will need, in one place, at the beginning of your code.


JavaScript Data Types

There are many types of JavaScript variables, but for now, just think of two types: text and numbers.
When you assign a text value to a variable, put double or single quotes around the value.
When you assign a numeric value to a variable, do not put quotes around the value. If you put quotes around a numeric value, it will be treated as text.

One Statement, Many Variables

You can declare many variables in one statement. Just start the statement with var and separate the variables by comma:

var name="Doe", age=30, job="carpenter"; 
 
Your declaration can also span multiple lines:

var name="Doe",
age=30,
job="carpenter";


Value = undefined

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.
The variable carname will have the value undefined after the execution of the following statement:
var carname;


Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable, it will not lose its value:.
The value of the variable carname will still have the value "Volvo" after the execution of the following two statements:
var carname="Volvo";
var carname;


JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:

Example

y=5;
x=y+2;


You will learn more about JavaScript operators in a later chapter of this tutorial.

JavaScript Statements

JavaScript Statements

JavaScript statements are "commands" to the browser. The purpose of the statements is to tell the browser what to do.
This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML element with id="demo":

document.getElementById("demo").innerHTML="Hello Dolly";


Semicolon ;

Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement.
Using semicolons also makes it possible to write many statements on one line.
lamp Ending statements with semicolon is optional in JavaScript. You might see examples without semicolons.


JavaScript Code

JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
This example will manipulate two HTML elements:

Example

document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";




JavaScript Code Blocks

JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket, and end with a right curly bracket.
The purpose of a block is to make the sequence of statements execute together.
A good example of statements grouped together in blocks, are JavaScript functions.
This example will run a function that will manipulate two HTML elements:

Example

function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}


You will learn more about functions in later chapters.

JavaScript is Case Sensitive

JavaScript is case sensitive.
Watch your capitalization closely when you write JavaScript statements:
A function getElementById is not the same as getElementbyID.

A variable named myVariable is not the same as MyVariable.

White Space

JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent:
var name="Hege";
var name = "Hege";


Break up a Code Line

You can break up a code line within a text string with a backslash. The example below will be displayed properly:
document.write("Hello \
World!");
However, you cannot break up a code line like this:
document.write \
("Hello World!");

Sabtu, 29 September 2012

JavaScript Objects

JavaScript Objects

JavaScript has several built-in objects, like String, Date, Array, and more.
An object is just a special kind of data, with properties and methods.

Objects Properties

Properties are the values associated with an object.
The syntax for accessing the property of an object is:

objectName.propertyName

This example uses the length property of the String object to find the length of a string:

var message="Hello World!";
var x=message.length;

The value of x, after execution of the code above will be:

12

Real Life Illustration

A person is an object.
The persons' properties include name, height, weight, age, skin tone, eye color, etc.
All persons have these properties, but the values of those properties differ from person to person.

Objects Have Methods

Methods are the actions that can be performed on objects.
You can call a method with the following syntax:

objectName.methodName()

This example uses the toUpperCase() method of the String object, to convert a text to uppercase:

var message="Hello world!";
var x=message.toUpperCase();

The value of x, after execution of the code above will be:

HELLO WORLD!

Real Life Illustration

A person is an object.
The persons' methods could be eat(), sleep(), work(), play(), etc.
All persons have these methods.

Creating JavaScript Objects

With JavaScript you can define and create your own objects.
There are 2 different ways to create a new object:
  • 1. Define and create a direct instance of an object.
  • 2. Use a function to define an object, then create new object instances.

Creating a Direct Instance

This example creates a new instance of an object, and adds four properties to it:
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
Alternative syntax (using object literals):

Example

personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};



Using an Object Constructor

This example uses a function to construct the object:

Example

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}

The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand.

Adding Methods to JavaScript Objects

Methods are just functions attached to objects.
Defining methods to an object is done inside the constructor function:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.changeName=changeName;

function changeName(name)
{
this.lastname=name;
}
}
The changeName() function assigns the value of name to the person's lastname property.

Now You Can Try:

myMother.changeName("Doe");

JavaScript knows which person you are talking about by "substituting" this with myMother.

Creating JavaScript Object Instances

Once you have a object constructor, you can create new instances of the object, like this:
var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");


Adding Properties to JavaScript Objects

You can add new properties to an existing object by simply giving it a value.
Assume that the personObj already exists - you can give it new properties named firstname, lastname, age, and eyecolor as follows:



The value of x, after execution of the code above will be: