Introduction to Javascript

Irving N. Llamas Covarrubias

https://www.irvingnor.wordpress.com

HTML

CSS

 

Content

Presentation

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>
body {
    background-color: #d0e4fe;
}

h1 {
    color: orange;
    text-align: center;
}

p {
    font-family: "Times New Roman";
    font-size: 20px;
}

Javascript

Behavior

document.write("Hello world");
var a = 3;
alert(3);

alert("Hello world!!!");

Javascript is:

Scripting language

  • Only work in a web browser

  • cannot access local files

  • cannot directly access database

  • cannot access hardware (USB, etc..)

Is a client-side language

    -Some web server languages [PHP, ASP. NET, Ruby on Rails]

 

Other uses

*Applications

            - Acrobat

            -Photoshop

 *Server-side

            -Node.js

            -Google Apps Script

Issues with javascript

 

  • Can be disabled

  •  

  • Variety of browsers [Handle the code differently]

Some History

 

*Developed in 1995  Bryan, in Netscape and was called LiveScript.

 

*Rename Live Script to JavaScript 1996 [Netscape 2]

 

*[IE 3] JScript

 

 

ECMAScript

First appeared 1997

 

Major implementations:

SpiderMonkey,  

V8,

 ActionScript

JScript

,QtScript

InScript

ECMAScript 3 [1999]

 

ECMAScript 5 published [2009]

 

It's not Java

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

}

It’s more Scheme/Lisp-style functional

(define hello-world
   (lambda ()
         (begin
	(write ‘Hello-World)
            (newline)
	(hello-world))))
(DEFUN HELLO ()
  "HELLO WORLD"
) 

Scheme

Lisp

JavaScript

It's case sensitive

alert("Hello world!!!");
Alert("Hello world!!!");

Comment code

//This is a comment


/*

This
is
a
comment


*/

alert("Hello world!!!");

In head or body tags

Embedding JavaScript

<!DOCTYPE html>
<html>
<head>
<script>
    alert("Hello world!!!");
</script>
</head>

<body>

<script>
    var a = 3;
    document.write(a);
</script>

</body>
</html>

External file

<!DOCTYPE html>
<html>
    <head>
        <title>Example</title>

    </head>
    <body>
        <H1>Text...</H1><br/>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed venenatis lectus elit, sed efficitur libero dictum sed. Mauris pellentesque finibus massa. Morbi eu elementum massa. Curabitur massa lorem, tincidunt nec orci sit amet, consequat pellentesque nulla. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam pellentesque lacus finibus cursus congue. Vivamus ullamcorper dui eu massa commodo, sit amet convallis turpis tempor. Aenean et porta justo.</p>
        <script src="myScript.js"></script>
    </body>
</html>

In HTML5 it's ok if you don't specify the type attribute

Statements

A group of words, numbers and operators that performs a specific task is a statement.

a = a * 2;

The characters a and b are called variables.

Variables

*Are like simple boxes you can store any of your stuff in. 

 

*Hold values to be used by the program.

Using Chrome console

Open Developer Tools and bring focus to the console

 

Ctrl + Shift + J

Input

Operators

Operators are how we perform actions on variables and values.

var a = 20;

a = a + 1;
a = a * 2;

Assigment

 

Math

Addition           +

Substraction    -

Multiplication  *

Division            /

a = 2;
a = 3 + 4;

Compound assigment

+=

-=

*=

/=

Increment/Decrement

++ (increment)

--   (decrement)

a = a + 2;

a += 2;
a = a + 1;

a++;

Object property access

Means object value called obj with a property of the name a.

Equality

==    (loose-equals)

===  (strict-equals)

!=     (loose not-equals)

!==   (strict not-equals)

obj.a;

obj["a"];
a == b;

a !=== b;

Comparison

<     (less than)

>     (greater than)

<=   (less than or loose-equals)

>=   (greater than or loose-equals)

Logical

&&   (and)

||     (or)

a <= b
a || b;

Values & Types

When you need to ...

   *do math, you want a number

 

   *print a value on the screen, you need a string(one o more characters, words or sentences.)

 

    *make a decision in yout program, you need a boolean (true or false).

"I am a string";
'I am also a string';
//The only difference is stylistic

42;

true;

false;

Converting between types

Convert number to string, this conversion is called "coercion"

var a = "42";
var b = Number( a );

console.log( a );   // "42"
console.log( b );   // 42

When comparing the string "99.99" to the number 99.99, most people agree they are equivalent. But they're not exactly the same.

Variables

Static typing:

 

   Hold a specific type of value, such as number or string.

Dynamic typing:

 

   Allows a variable to hold any type of value at any time.

var amount = 99.99;
amount = amount * 2;

console.log(amount);       //199.98

//Convert amount to a string, and
//add "$" on the beginning
amount = "$" + String( amount );


console.log(amount);        //"$199.98"

Constants - Not change through the program.

By convention, JavaScript variables as constants are usually capitalized, with underscores _ between multiple words.

var TAX_RATE = 0.08;    //8% sales tax   in ES6 const TAX_RATE = 0.08;
var amount = 99.99;

amount = amount * 2;

amount = amount + (amount * TAX_RATE);

console.log( amount );                 //215.9784
console.log( amount.toFixed( 2 ) );    //"215.98"

Conditionals

const ACCESSORY_PRICE = 9.99;

var bank_balance = 302.13;
var amount = 99.99;

amount = amount * 2;

if( amount < bank_balance)
{
    console.log("I'll take the accessory!!!");
    amount = amount + ACCESSORY_PRICE;
}
else
{
    console.log("No, thanks");
}

Loops

 

Repeating a set of actions until a certain condition fails.

Loops can take different forms, but they all satisfy this basic behavior.

while

do...while

var numOfCustomers = 10;

while( numOfCustomers > 0 )
{
    console.log( "How may I help you?" );
    numOfCustomers--;
}
var numOfCustomers = 10;

do
{
    console.log( "How may I help you?" );
    numOfCustomers--;
}while( numOfCustomers > 0 );

The only practical difference between these loops is wheter the conditional is tested before or after the first iteration.

for

for(var i = 0; i <= 9 ; i++)
{
    console.log( i );
}

//0 1 2 3 4 5 6 7 8 9

Functions

Is generally a named section of the code that can be "called" by name, and the code inside it will be run each time.

function printAmount()
{
    console.log( amount.toFixed( 2 ) );
}

var amount = 99.99;

printAmount(); // 99.99

amount *= 2;

printAmount(); // 199.98

Functions can optionally take arguments, values you pass in. And they can also optionally return a value back.

function printAmount(amt)
{
    console.log( amt.toFixed( 2 ) );
}

function formatAmount()
{
    return "$" + amount.toFixed( 2 );
}

var amount = 99.99;

printAmount( amount * 2 );    // 199.98

amount = formatAmount();

console.log( amount );        //$99.99

Functions are often used for code that you plan to call multiple times, but they can be useful just to organize related bits of code into name collections, even if you only plan to call them once.

const TAX_RATE = 0.08;

function calculateFinalPurchaseAmount( amt )
{
    amt = amt + ( amt * TAX_RATE );
    return amt;
}

var amount = 99.99;
amount = calculateFinalPurchaseAmount( amount );
console.log( amount.toFixed( 2 ) ); //107.99

Scope

If you ask the phone store employee for a phone model that her store doesn't carry, she will not be able to sell you the phone you want. She only has access to the phones in her store's inventory.

function one()
{
    var a = 1;
    console.log( a );
}

function two()
{
    var a = 2;
    console.log( a );
}

one();       //1
two();       //2
function outer()
{
    var a = 1;
    
    function inner()
    {
        var b = 2;
        console.log( a + b );    // 3

    }

    inner();
    //We can only access 'a' here
    console.log( a );        // 1

}

Practice

Write a program

  • Calculate the total price of your phone purchase.
  • After you've calculated your purchase amount, add in the tax, then print out the calculated purchase amount, properly formatted.
  • Finally, check the amount against your bank account balance to see if you can afford it or not.
  • Set up constants for "tax_rate","phone_price", "accessory price" and "spending threshold".
  • Define functions for calculating the tax and for formatting the price with a "$" and rounding to two decimal places.
  • Incorporate inpuy into this program. Perhaps with the prompt.

Solution

const SPENDING_THREHOLD = 200;
const TAX_RATE = 0.08;
const PHONE_PRICE = 99.99;
const ACCESSORY_PRICE = 9.99;

var bank_balance = 303.91; //prompt("What's your bank balance?");
var amount  = 0;

function calculateTax(amount)
{
    return amount * TAX_RATE;
}
function formatAmount(amount)
{
    return "$" + amount.toFixed("2");
}
//Keep buying phones while you still have money
while( amount < bank_balance )
{   
    //buy a new phone
    amount = amount + PHONE_PRICE;
    
    //Can we afford the accessory?
    if( amount < SPENDING_THRESHOLD )
    {   
        amount += ACCESSORY_PRICE;
    }
}
//don't forget to pay the government, too
amount = amount + calculateTax( amount );

console.log( "You purchase: " +  formatAmount( amount ));
//You purchase: $334.76

//can you actually afford this purchase?
if( amount > bank_balance )
{
    console.log( "You can't afford this purchase. :(");

}//You can't afford this purchase. :(

Values & Types

JavaScript has typed values, not typed variables.

string

number

boolean

null and undefined

object

symbol (new to ES6)

var a;
typeof a;    //undefined
a = "hello world";
typeof a;     //string

a = 42;
typeof a;    //number

a = true;
typeof a;    //boolean

a = null;
typeof a;    //object, weird, bug

a = undefined;
typeof a;    //undefined

a = {b: "c"};
typeof a;    //Object

Objects

Refers to a compound value where you can set properties that each hold their own values of any type.

var obj = {
    a: "hello world",
    b: 42,
    c: true
};

obj.a;
obj.b;
obj.c;

obj["a"];
obj["b"];
obj["c"];

Arrays

Hold values not particularly in name properties/keys, but rather in numerically indexed positions.

var arr =
[
    "hello world",
    42,
    true
];

arr[0];    //hello world
arr[1];    //42
arr[2];    //true
arr.length;//3

//Start counting at zero.

Functions

Hold values not particularly in name properties/keys, but rather in numerically indexed positions.

function foo()
{
    return 42;
}

foo.bar = "hello world";


typeof foo;    //function
typeof foo();  //number
typeof foo.bar;//string

Built-In Type Methods

The built-in types and subtypes have behaviors exposed as properties and meths that are quite powerful and useful.

var a = "hello world";
var b = 3.14159;

a.length;           //11
a.toUpperCase();    //"HELLO WORLD"
b.toFixed(4);       //3.1416

Reference

To make this presentation I used the book called "You Don't Know JS(book series)". The book that I used was Up & Going.

https://github.com/getify/You-Dont-Know-JS

Introduction to Javascript

By Irving Norehem Llamas Covarrubias