JavaScript introduction


by - posted

JavaScript introduction

javascript introductionThe JavaScript introduction will give you a quick and easy approach to basic JavaScript programming. A minimum know-how of HTML is recommended, read more on my blog post HTML introduction.

JavaScript is a programming language used to make Web pages interactive. It is a so called scripting language. The JavaScript code is loaded, then interpreted in the client’s browser.
JavaScript can be disabled in the browser!

JS code in a HTML file

The JS code is executed where it is placed in the HTML file.

Valid HTML

<script>

document.write("Hello world");

</script>

Valid XHTML

<script type="text/javascript">
//<![CDATA[

document.write("Hello world");

//]]>
</script>

When there is no “CDATA”, characters like <  & (in the code) trigger en error message by validating the XHTML page !

JS code in an JS-file

The current state-of-the-art is to put scripts in the <head> tag and use the async and/or defer attributes. This allows your scripts to be downloaded asap without blocking your browser.

– async script will be executed asynchronously as soon as it is available
– defer script is executed when the document has finished parsing
– async defer script falls back to the defer behavior if async is not supported

The JS code is in the file yourFilename.js.  The file can be for example in the /js directory.

The HTML file

<!DOCTYPE html>
<html>

<head>
<script type="text/javascript" src="js/yourFilename.js" async defer></script>
</head>

<body>

here comes your HTML code

</body>
</html>

The JS file (yourFilename.js)

/*
version 17/03/2017
by myself
*

if(screen.width<=850)
{
document.write("to see the page normally press the minus key until the page looks normally ...");
}/

Comments

Single line

// this is a comment

Multi line

/* this is
a multi line
comment
*/

Variables

Variable names must begin with a letter. Variable names are case sensitive. It’s a good programming practice to declare all the variables you will need at the beginning of your code !

Declaring a variable : var firstName;

Assigning a variable : firstName = "Marc"; or var firstName = "Marc";

JavaScript variables are all objects. When you declare a variable, you create a new object.

Lifetime

– The lifetime of a JavaScript variable starts as soon as it is declared.
– Local variables are deleted when the function is completed.
– Global variables are deleted when you close the web page.

Scope

– Local

A variable declared – using var – inside a function becomes “local” and can only be accessed from within that function. var abc = 12.35;

– Global

Variables declared outside a function become “global” and all scripts and functions on the web page can access it.

If you assign a value to a variable that has not yet been declared, the variable will automatically be declared as a global variable. Example : carname="Volvo"; will declare the variable carname as a global variable, even if it is executed inside a function.

Data types

JavaScript has dynamic types, the same variables can be used as different types.

Numbers

JavaScript has only one type of numbers. Numbers can be written with or without decimals.

Strings

A string can be any text inside quotes. You can use single or double quotes.

Booleans

Booleans can only have two values: true or false.

var x=true;
var y=false;

Null

You can erase the contents of a variable by assigning it the null value : var cars = null;
Notice that in JavaScript, null is not the same as 0 (as it is in C and C++). Also note that the typeof operator in JavaScript reports null values as being of type object, not of type null.

Undefined

Variable declared without a value will have the data type undefined : var firstName;

Declaring data types

var carname = "Volvo"; // new String
var x = 12; // new Number
var y = true; // new Boolean
var cars =; ["Audi", "Peugeot", "Toyota"] // new Array
var person = {FirstName:"Marc", LastName:"Schwager", gender:"male"}; //  new Object

Operators

Arithmetic operators

Addition : c = a + b
Subtraction : c = a – b
Multiplication : c = a * b
Division : c = a / b
Modulus : c = a % b
Increment : c++
Decrement : c–

Comparison operators

equal  :  a == b
equal of value and type  :  a===b
not equal  :  a != b
not equal of value and type  :  a!==b
greater than  :  a > b
less than  :  a < b
greater than or equal to  :  a>=b
less than or equal to  :  a<=b

Logical operators

AND  :  a && b    True if both a and b are true
OR  :  a || b       True if either or both a and b are true
NOT  :  ! a

Assignment operators

Assignment operators are used to assign values to JavaScript variables.

Operator – used as – meaning
=         a=b         a becomes the value of b
+=       x+=y        x=x+y
-=        x-=y         x=x-y
*=       x*=y        x=x*y
/=        x/=y         x=x/y
%=      x%=y        x=x%y

Conditional operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition : variablename=(condition)?value1:value2

Output

1) Basic output

<!DOCTYPE html>
<html>
<body>

<h1>This is a basic JS output example</h1>

<script>
document.write("<p>This will be the JavaScript text on the page</p>");
</script>

</body>
</html>

2) Change the content of a HTML tag

<!DOCTYPE html>
<html>
<body>

<script>
function myFunction()
{
document.getElementById("demo").innerHTML="This replaces the text in the paragraph";
}
</script>

<h1>This is a HTML title</h1>

<p id="demo">This is a paragraph</p>

<button onclick="myFunction()">replace</button>

</body>
</html>

The JS accesses the HTML element with the specified id  and changes its content.

3) Change the whole page content

<!DOCTYPE html>
<html>
<body>

<script>
function myFunction()
{
document.write("This text replaces the previous one");
}
</script>

<h1>This is a HTML title</h1>
<p>Press the button below in order to change the page content</p>

<button onclick="myFunction()">replace</button>

</body>
</html>

The document.write overwrites the entire HTML page content.

4) Alert box

<!DOCTYPE html>
<html>
<body>

<h1>This is a HTML title</h1>

<script>
alert('This text will be in the "box" - click OK to quit');
</script>

</body>
</html>

User Input

1) Pure JavaScript

<!DOCTYPE html>
<html>
<body>

<script>
var name = prompt("What is your name", "Type you name here");
document.write("Hi " + name + "\n you are a JavaScript geek");
</script>

</body>
</html>

2) HTML form element (as input)

<!DOCTYPE html>
<html>
<body>

<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname" value="Marc"><br>
</form>

<p>Click the "Print it" button to display the value of the element in the form.</p>

<button onclick="myFunction()">Print it</button>

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

<script>
function myFunction() {
var x = document.getElementById("myForm").elements[0].value;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The IF condition

When JavaScript encounters an IF statement, it checks the condition.
If it is found to be true, the statements enclosed within the first curly braces are executed.
If it is found to be false statements enclosed within the second curly braces are executed.

Syntax

if (condition)
{
execute if condition is true
}
else
{
execute if condition is not true
}

The else if construct

if (condition 1)
{
execute if condition 1 is true
}
else if (condition 2)
{
execute if condition 2 is true
}
else
{
execute if both conditions are not true
}

The SWITCH condition

The switch condition is used to perform different actions based on different conditions.
Use the default keyword to specify what to do if there is no match.

Syntax

switch(x)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
.
.
case n:
execute code block n
.
.
default:
code to be executed if x is different from case 1, 2 to n
}

The FOR loop

When the JavaScript interpreter comes across a FOR loop, it executes the initialization statements and then checks the condition. Only when the condition returns “true”, the interpreter enters the loop. After the first iteration, the updation statements are executed and then the condition is evaluated again. This continues till the condition returns “false” and the loop stops.

Syntax

for (Initialization statements; Condition; Updation statements)
{
...
statements
...
}

Example

for (b = 20; b <= 10; b++)
{
// repeat the statements, between the curly braces, until termination
}

The WHILE loop

As long as the condition evaluates to “true”, the program execution will continue to loop through the statements.

Syntax

while (condition)
{
statements
}

The DO WHILE loop

You can consider the DO WHILE loop as a modified version of the while loop. Here, the condition is placed at the end of the loop and the loop is executed at least once.

Syntax

do
{
statements
}
while (condition);

Break and continue statements for loops

JavaScript provides commands through which iterations of a loop can be skipped or stopped. These commands are most commonly used along with an IF statement inside the loop.

– continue: causes the iteration to be skipped
– break: causes the loop to stop and program execution to begin at the statement immediately following the loop.

Example for continue

Displays only the even numbers between 1 to 20 (skipping the odd numbers).

for (var x = 0; x <=20; x++)
{
if (x%2)
{
continue;
}
document.write(x + "\n");
}

Example for break

Loop iteration stops when the value of variable t equals 8.

var t = 1;
while (t <= 10)
{
if (t == 8)
{
break;
}
document.write(t + "\n");
t++;
}

Arrays

Array indexes are zero-based, which means the first item is [0], second is [1] and so on.
The following code creates an Array called cars:

var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";

Array values are accessed through their index names. We can use a for loop in order to access the values.

Objects

JavaScript variables are all objects. When you declare a variable you create a new object.
An object is delimited by curly braces. Inside the braces the object’s properties are defined as name and value pairs (name : value).
The properties are separated by commas. The object (person) in the example below has 3 properties: firstname, lastname, and id.

This code :
var person={firstname:"John", lastname:"Doe", id:5566};

gives the same result as this code :
var person=
{
firstname : "John",
lastname  : "Doe",
id        :  5566
};

You can address the object properties in two ways:
name=person.lastname;
name=person["lastname"];

The object properties

The object properties describe the characteristics of an object.

The object methods

Methods are what an object can do and this is defined by functions.

Functions

A function is a block of code that will be executed when it is called.

Example :

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() // this is the function declaration
{
alert("Hello World!");
}
</script>
</head>

<body>
<button onclick="myFunction()">Try it</button>  <!--  the function is called here -->
</body>
</html>

A function has to be called after it’s declaration, this will then be valid JavaScript.

Arguments

When you call a function, you can pass along some values to it. These values are called “arguments” or “parameters” : myFunction(argument1,argument2)

These arguments can be used inside the function.

function myFunction(var1,var2)
{
some code
}

The variables and the arguments must be in the expected order. The first variable is given the value of the first passed argument.

Return values

Sometimes you want your function to return a value back to where the call was made.
This is possible by using the return statement.
When using the return statement, the function will stop executing and return the specified value.

function myFunction()
{
var x=5;
return x;
}

Event handlers

Event handlers are small JavaScript codes placed inside an HTML tag. They help in handling (catching) events.

Examples :

– onmouseover
– onmouseout
– onmousedown
– onmouseup
– onclick
– onload
– onunload
– onchange

Libraries, Frameworks

– jQuery
– React
– Bootstrap
– Foundation
– Node.JS
– etc

Validators, code checkers

Firefox

– JavaScript Console or Error Console (under the “Tools” menu)
– Firebug add-on

Chrome

Online tools

http://www.jslint.com/
http://www.javascriptlint.com/online_lint.php

If you enjoyed this article, you can :
– get post updates by connecting to our RSS feed
– get post updates by subscribing to our e-mail list
– share on social media :