JavaScript Basics

Image - JavaScript Basics
Image – JavaScript Basics

In JavaScript basics, understand how websites load and are grouped into three layers. The first layer is the website content with the HTML that wraps around it. Next comes the CSS which styles the HTML for presentation. The third interacts with HTML and CSS to change what the user can see and do inside a website. The first two layers load when the page loads. When and after the page is loading the third layer runs in the background continuously. JavaScript can make changes to a website without refreshing the browser. HTML & CSS cannot do everything but writing JavaScript helps to add features such as web forms, shopping carts, interactive maps, calendar, and more to your website. In programming, making decisions with the code is called Control flow. Work your way through the basics and get a grasp on Control Flow, Conditionals, Functions, and Arrays & Loops.

Javascript integrates with HTML and has many frameworks and libraries such as Angular, Backbone.js, JQuery, Node.js, React, etc. JS can be applied to many software developments such as Client-side & Server-side applications, web, mobile & desktop applications, web & mobile apps, etc.

JavaScript Basics

Script Tag

A JavaScript added to a webpage uses a script tag. It runs in the browser with HTML and CSS. JavaScripts added to script tags are either internally or externally.

Internal

The script element is added directly inside the script tag is called internal.

<script> alert("Hello, All."); </script> 

External

JavaScript files with .js extension such as ‘main.js’ is through a resource link with the ‘src’ attribute. Such a link points to the file with a .js extension such as main.js, des.js, etc and is in the same directory of the HTML file.

    <script src="des.js"></script>

Console

Most of the browsers have a JavaScript debugger. The Console provides you an opportunity to investigate the possibilities of modifying existing HTML pages. It is not possible to change the HTML document in the console. On reloading the page it will return to a blank document.

fig1-Javascript Basics~Firefox Browser Console
fig1-Javascript Basics~Firefox Browser Console

Go to the Firefox browser and open the menu located at the top right fig 1 next to the address bar. In the display box, click on ‘Web Developer’ fig 4. In the dropdown click on ‘Web Console’.

fig2-Javascript Basics~Firefox Console
fig2-Javascript Basics~Firefox Console

With the Console open start working with modifying your pages. As an example open a blank HTML file using TextEdit (Mac) and go to Console. Write the JavaScript code fig 2 to get the output in the left pane.

d = new Date();      // indicates date in the console
 output.document.body.innerHTML = "<h1> Date is " + d + "</h1>" // indicates date in the left pane.
document.body.style.backgroundColor = "red"; // styles background color to red.
document.body.style.color = "maroon"; // styles text to maroon.
fig3-Firefox Inspect Element
fig3-Firefox Inspect Element

Clicking on any HTML page will open the dialogue menu box. From the display menu, click on Inspect Element. The above Console Output in fig 2 is as displayed by the ‘Inspect Element’ fig 3.

fig4-Firefox Web Developer
fig4-Firefox Web Developer

A webpage loaded in the browser creates a DOM – Document Object Model. In the DOM the HTML elements is a hierarchical tree of objects. View it within the Inspector Panel in Firefox. Explore other options available within the Firefox Web Developer fig 4 such as Network, Responsive Design, etc.

Data types

The three essential types are String, Number and Booleans. Other types are null, undefined, symbol, object, etc.

var myString = ‘Sap Canvas’;          // any word(s) or numbers surrounded by either single/ double quotes.
var myNumber = 13;                    // any number (including decimals) without quotes.
var myBoolean = true                  // either true or false with no quotations.
fig5-Javascript Basics~String | Math Operators
fig5-Javascript Basics~String | Math Operators
console.log(‘My favourite game is cricket’);
console.log(365+30);
console.log(31/92);
console.log(0.33695652173913043*100);
console.log(92%31);                 // Modulus-returns remainder 30.
fig6-Math.random | Math.floor (Build-in-Objects)
fig6-Math.random | Math.floor (Build-in-Objects)
Math.random()*25;   // returns a random number between 0 and 25. 
console.log(Math.random()*100);     // returns a random number between 0 and 100. 
console.log(Math.floor(Math.random()*100));   // make the output a whole number.

// used for single line comment

/* used for multiline comment */

fig7-Javascript Basics~Console Log
fig7-Javascript Basics~Console Log
console.log(‘My favourite game is’ + ‘cricket’);  
console.log(‘My favourite game’ + ' is’ + ‘ ‘ + ‘cricket’); 
console.log(‘Cricket’.length);         // prints 7 - dot operator
console.log(‘Cricket'.toUpperCase());      
console.log('    Pull-out whitespace   ‘.trim()); 

JSFiddle

In the above JSFiddle, click on the ‘HTML’ tab in the top menu bar and view the script tags. See the output by clicking on the ‘Result’ tab. View both the ‘HTML’ and ‘Result’ by clicking on the link ‘Edit in JSFiddle’ located at the top right in the menu bar.

if/else statements executes seperate code based on a condition. Add extra conditions with if/else statement, else/if conditions. Switch Statements make complicated if/else statements easy to read but end up with same result as if/else statements.

Compare two variables using operators <, >, <= and =>. They return either true or false.

JavaScript Basics: Control Flow

The control flow is the sequence in which the computer executes statements in a script. Here the code runs from the first line to the last line. Conditionals and loops make the computer run across structures that change the control flow.

fig8-Create variables 1
fig8-Create variables 1

Create Variables

Variables can hold any kind of data.

fig9-Create Variables 2
fig9-Create Variables 2

Create the first variable feb and set it equal to ‘month’. Similarly, create the second variable days and set it equal to 29 and the third variable leapYear and set it equal to a boolean ‘true’. Next, print it to the console using console.log

fig10-Change in Variable's Value.
fig10-Change in Variable’s Value.

The variable value is changed because of the code // chemistryClass = ‘Revised Time: 5:00PM’;

fig11-Insert a Variable into a String
fig11-Insert a Variable into a String

+ operator is used to insert (interpolate) a variable in a string.

JavaScript Basics: Conditional Statements

The conditional statements in JavaScript allow for decision making, based on conditions. The condition stated in the conditional statement can be true or false. The conditional statements execute the code only if the condition is true.

ifelse statement

Syntax 
if (condition) 
{ 
  code to execute if the condition is true 
} 
else 
{ 
  code to execute if condition is false
}

JSFiddle

In the above JSFiddle click on the ‘HTML’ tab to view the script tags. The output can be viewed by going to the ‘Result’ tab. View both the ‘HTML’ and ‘Result’ by clicking the link ‘Edit in JSFiddle’.

else-if statement

Syntax 

if (condition1) 
{ 
code to be executed if condition1 is true 
} 
else if(condition2) 
{ 
code to be executed if condition2 is true 
} 
else 
{
code to be executed if both condition1 and condition2 are false
}

JSFiddle

In JSFiddle click on the ‘HTML’ tab for viewing the script tags. The ‘Result’ tab will show the output. Both the ‘HTML’ and ‘Result’ can be see by clicking the link ‘Edit in JSFiddle’.

JavaScript Basics: Arrays & Loops

An Array is a list to store data and is created with [] brackets. All items within an array are at a numbered position. Access items in an array using its numbered position with syntax such as myArray[0]. The length property shows how many items are there in an array. An array has methods such as push, pop, sort, reverse, etc. The prototype property adds new properties and methods to the Array() object.

JSFiddle

In JSFiddle click on the two tabs ‘HTML’ and ‘Result’ to view the script tag and the output. Both the ‘HTML’ and ‘Result’ are available in the display after clicking the link ‘Edit in JSFiddle’.

Write less repetitive code with Loops. The 2 types of loops are – ‘for’ loop and ‘while’ loop. A ‘for’ loop repeats a block of code a known amount of time. It can be used inside another loop for comparison between two lists.

JSFiddle

In JSFiddle click the tabs ‘HTML’ and ‘Result’ that will show the script tag and the output. Alternatively, both the ‘HTML’ and ‘Result’ are available simultaneously through the link ‘Edit in JSFiddle’.

‘for loop’

Syntax
for(initial condition; test condition; acting on the condition with incremental or decremental)
{
block of code to be executed }

Refer to the HTML tab display page for the above JSFiddle. (1)-var i=0 is the initial condition of the loop which implies the loop starts the count at zero. (2)-i<holidayPlaces.length is the test condition that indicates that the loop will run as long as i is less than the length of the holidayPlaces array. The loop will stop running when i becomes greater than the length of the holidayPlaces array. (3)-i++ is the iterator (acting on the condition with incremental or decremental) indicating each loop will have 1 added to it. (4)-{… } The block of code to be executed is placed inside the parentheses will run each loop, till the loop stops running.

Make the ‘for loop’ run backward by changing
(1)-var i=0 to the length of the holidayPlaces array
(2)-i<holidayPlaces.length to i> or = 0 indicating the loop will stop running when i is greater than or equal to 0.
(3)-i++ to i— indicating each loop will have 1 subtracted from it.

A ‘while’ loop is for looping over a code block an unknown amount of times.

While loop

Syntax
while (condition)
{ code block to be executed untill condition is false. }

JSFiddle

In JS Fiddle, the code for the while loop is in the script tag of the HTML document. To view, the code click the ‘HTML’ tab and view the output by clicking the ‘Result’ tab. Click the online code editor JS Fiddle tab to view both the code and result.

var text = "";
var i = 1;
while (i < 7)
{
text += "<br>The dice trial number outcome can be " + i;
i++;
}
document.getElementById("trial").innerHTML = text;

JavaScript Basics: Functions

A block of code that performs a task is called a function.

Function

Syntax
function functionname()
{
code block to be executed }

Syntax

To create a JavaScript function using the keyword – function separated by the name of the function with parameters within the parentheses. The code should be placed within the curly braces. In JavaScript alert() is a built-in function. In the below example the ‘return statement’ returns the value from the function after performing the operations.

JSFiddle

The script tag and output are best seen by clicking the tabs – ‘HTML’ and ‘Result’=15. Also, see the script tag and the output by going to the link ‘Edit in JSFiddle’.

Function Scope

Scope in JavaScript is of two types. Global Scope means the variable is defined outside the function. Local scope is variables defined inside the function.
In the below example a local variable is added to myPlanet for replacing the value of innerPlanet Mercury with Venus.

var innerPlanet = “Mercury”; 
function myPlanet () 
{ 
var innerPlanet = “Venus”; 
return innerPlanet; 
} 
myPlanet();