Compact Tutorial on JavaScript Basic

Home / Compact Tutorial on JavaScript Basic

Compact Tutorial on JavaScript Basic

December 9, 2015 | Article | 1 Comment

We will not cover how to program in JavaScript in detail but rather what to do in JavaScript.

Where to Write?

There are some alternatives to write a piece of JavaScript code: inside a document using <script>, inline on HTML tag, external files.

JavaScript can be written on enclosing pair of tag <script> </script>

<script>
alert("My First JavaScript");
</script>

We can write this on any section of HTML document, for example: <body>, <head>, or both. It is a common practice to put code in the <head> section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

For example, this code is a script embedded to <body> section.

<!DOCTYPE html>
<html>
<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>

</body>
</html>

JavaScript can be embedded to a HTML tag. For a simple code this approach can be used. Here we modified the above code:

<!DOCTYPE html>
<html>
<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>

<button type="button" onclick="document.getElementById('demo').innerHTML='My First JavaScript Function'">Try it</button>

</body>
</html>

Last, we can write a JavaScript code in external files and make the HTML file loads them. This way, several web pages can use it. External JavaScript files have the file extension .js.

To include external script, point to the .js file in the “src” attribute of the <script> tag:

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

Dynamic Type Inference

JavaScript is a scripting language. It is a language which dynamically infer the types of objects, instead of forcing object definition.

For example, in C or C++ you can have a variable which is defined as integer, floating point number, a character, etc. Including user-defined type. When declaring a variable, you have to specify what kind of variable (the type) of it. When you fail to define it, compiler will refuse to process. You should also make sure the type is defined / declared ahead of variable declaration. Here is the example in C++:

int myInt = 9;
float myFloat = 3.14;
char myChar = 'X';

In JavaScript, no such things exists. Instead you can have all defined as a variable, regarding the value.

var myInt = 9;
var myFloat = 3.14;
var myChar = 'x';

Not only primitive type, you can treat object with same manner.

You can also write all variable declaration in one line, separated by comma:

var lastname="Sabertooth", age="21", job="CEO";

or you can span it to multiple lines, but still the declaration is separated by comma:

var lastname="Sabertooth",
age="21",
job="CEO";

Though indentation is not really a matter, it is advised to watch your indentation.

As implication of this behavior, you can assign any value to JavaScript variable. But, in computer programs variable are often declared without no value. The value can be something that will be provided later, like user input. However how we declared an empty variable? Here undefined comes.

The variable carname will have the value undefined after the execution of the following statement:

var carname;

An undefined value is not instance of any type. It is purely declaring the variable as empty.

There is also exists the sibling, null value.

A Statement, Code Blocks

A statements are “commands” to the browsers or interpreters.

A statement can be an expression or simply a function / procedure invocation.Like it’s predecessor, JavaScript can use semicolon ; to separates JavaScript statements. This enables us to write multiple statement on a line. However, write semicolon at the end is optional.

document.write("Xathrya Sabertooth"); document.write(" was here");

The statements are case sensitive. Watch capitalization closely. A function getElementById is not same as getElementByID. A variable named myVariable is not same as MyVariable.Some statements can also be grouped together in blocks. Blocks started with a left curly bracket, and ended with a right curly bracket. Blocks are used for defining function, branching (if-else, switch), repetition (for, do, while), or simply grouping statements.Different in Way of Code

JavaScript also use different paradigm. It is still executed in sequential, means a higher line of code will be executed earlier than code in bottom.

What we means in different paradigm?

Writing JavaScript require ones to know event-driven model. Lot of code or function are act as callback. They are executed when some kind of event has been triggered. The event can vary, such as button click, page load, etc. The event can be associated to specific page element such as button, image, etc.

If you have code in native programming language, for example C/C++, you can feel the difference. In C/C++ you have a main function where all execution alive. In JavaScript, they are persistent and wait for a call. This should be noted!

We Talk About Input/Output

In JavaScript, we can say manipulating I/O is the primary goal. We say input when we grab content of some elements, whether we process it or not. We say output when we write things to document, whether it is processed or not. The output / writing can be create, update, or delete DOM. Remember that JavaScript can manipulate a DOM freely.

I/O can also be considered as communication with other entity, such as remote server in AJAX.

What are Types?

In fact, JavaScript do have types declared. They are strings, number, boolean, and object.

A string is a series of characters. It can be any text inside quotes (single or double quotes). You can also use quotes inside a stirng, as long as they don’t match the start quote.

var carname="Volvo XC60";
var carname='Volvo XC60';
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';

A number is a generalization of integer and floating point number. JavaScript also support large number using scientific notation.

var x1=34.00;      // Written with decimals
var x2=34;         // Written without decimals
var y=123e5;      // 12300000
var z=123e-5;     // 0.00123

A boolean is a special type which has only two kind of values: true or false. It is often used in condition testing. We will

var x=true;
var y=false;

JavaScript object is delimited by curly braces. Inside the braces the object’s properties are defined as name and value pairs. The properties are separated by commas. Here is how we write a JavaScript object. Note that we can use one line to define all, or single line to define each.

var person={
firstname : "Xathrya", lastname  : "Sabertooth",
id        :  5566,
company   : "Sakraysoft Nanotech"
};

When we declare an object, we will use following syntax:

var Xathrya = new person;

and addressing the properties by two ways:

name = Xathrya.lastname;
name = Xathrya["lastname"];

You can also create a new object for String, Number, and Boolean respectively.

There is also a type which is defined as a collection of value. This type is called as Array(). Like we predict, JavaScript array is unlike C/C++ array. JavaScript can be any value.

var X = new Array();
X[0] = "Xathrya";
X[1] = "Sabertooth";
X[2] = 13510030;

Operators

Assign

Assign is an operator to assign value to a variable. In other world, it write a value to variable. The operator is =

y = 5;
z = 2;
x = y + z;

The x will be 7.

JavaScript can support C-like assignment operators, using itself as first operand and modify the value with second operand. The operators we talk about are: += (add this with), -= (subtract this with), *= (multiply this with), /= (divide this with), %= (mod this with).

For example:

var X = 10;
X += 2;    // X now 12
X -= 3;    // X now 9
X *= 4;    // X now 36
X /= 3;    // X now 12
X %= 8;    // X now 4

Arithmetic

There are various arithmetic operations supported by JavaScript: + (addition), – (subtraction) , * (multiplication), / (division), % (modulus or division remainder), ++ (increment), — (decrement).

var x = 15;
var y;

y = x + 3;   // y now 15 + 3 = 18
y = x - 4;   // y now 15 - 4 = 11
y = x * 2;   // y now 15 * 2 = 30
y = x / 3;   // y now 15 / 3 = 5
y = x % 9;   // y now 15 % 9 = 6

Overall, the operators are similar to C and derived programming language’s operators.

Comparison

Comparison operators are operators used for comparing value of variable. There are three “state” available in Math: less, equal, greater. From this three states, we can have some comparison: < (less than), <= (less than or equal), == (equal), != (not equal), > (greater than), >= (greater than or equal). JavaScript also expand operators, adding two new operator: === (exactly equal to), !== (not equal). All operator will return a boolean value, true or false.

So what is the difference of == to === and != to !===?

Remember that JavaScript is resolve type dynamically. The === means both variable have equal value and equal type. While the !== means the variable has different value or different type.

Here is the example:

var x = 5;

x == 8;      // false
x == 5;      // true

x === "5";   // false
x === 5;     // true

x != 8;      // true

x !== "5";   // true
x !== 5;     // false

x > 8;       // false

x < 8;       // true

x >= 8;      // false

x <= 5;      // true

This operator can be used to evaluate a condition.

String operation

Operator + can also be used to string. It will concatenate two string and produce new string.

txt1 = "Xathrya ";
txt2 = "Sabertooth";
txt3 = txt1 + txt2;    // txt3 = "Xathrya Sabertooth"

When you adding two number, a new summed value will be returned. However, when you “add” string and a number, it will produce a string:

x = 5 + 5;         // x = 10
y = "5" + 5;       // y = "55"
z = "Hello" + 5;   // z = "Hello5"

Logical

These operators act as conjunction to one or more logical expression and then return a boolean value. These operators consists of: && (and), || (or), ! (not).

An && “and” operator need two operand and return true when both expression has value True. In math, it is denoted as ^.

An || “or” operator need two operand and return true unless both expression has value False. In math, it is denoted as v.

A ! not operator need one operand and invert the value. For example if the expression is False, it will produce True. Otherwise, it will product False. In math, it is denoted as ~.

Here we have a complete list:

truthtable

,

About Author

about author

xathrya

A man who is obsessed to low level technology.

1 Comment
  1. JavaScript: String Objects - Xathrya.ID

    […] This article is a supplement for Compact Tutorial on JavaScript Basic. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Social media & sharing icons powered by UltimatelySocial