JAVASCRIPT FUNDAMENTALSAn Introduction to JavaScript
The World Wide Web (www) HTML CSS JAVASCRIPT JavaScript along with HTML and CSS forms a triad of cornerstone technologies for creating web pages and web applications.
1. HTML HTML or HyperText Markup Language is the standard language for describing the structure of a web page using HTML elements (or tags) which are the building blocks of HTML pages. < element attribute = ”value” > Content hoes here </ element > index.html
2. CSS CSS or Cascading Style Sheets is a style sheet language used for describing the presentation of a document written in HTML. It is designed pri - marily to enable the separation of presentation and content, including aspects such as the layout, colors, responsiveness , and fonts. selector { property: value; } #another .selector { property: value; } index.html + style.css
3. JavaScript JavaScript (JS) is a programming language used to make webpages interactive and provide online programs, including video games. All modern web browsers support JavaScript. console. log( true ) ; if ( click ) showDialog() ; startTimer() ; index.html + style.css + script.js
HTML + CSS + JS
JavaScript Interaction & Logic CSS Presentation & Styling HTML Content & Structure index.html style.css script.js
A Basic understanding of the JavaScript Interpreter You can think of the JavaScript interpreter, as a robot that lives inside the browser. It accepts a series of statements, interprets them and executes them one by one. statements actions
A Basic understanding of the JavaScript Interpreter For example, we can write a series of statements, instruct - ing JavaScript to display a modal window whenever the user clicks on a specific button on the page. <script> if ( button.click ){ openModalWindow(); } </script>
A Basic understanding of the JavaScript Interpreter For example, we can write a series of statements, instruct - ing JavaScript to display a modal window whenever the user clicks on a specific button on the page. <script> if ( button.click ){ openModalWindow(); } </script>
A Basic understanding of the JavaScript Interpreter The JavaScript interpreter running inside the browser deals mainly with two kinds of operations: • Input / Output • Data Manipulation (or Processing)
A Basic understanding of the JavaScript Interpreter Dealing with Input means that the interpreter has to deal with user input such as mouse clicks, entering text into as mouse clicks , entering text into input input forms or even speech. . • Input / Output • Data Manipulation (or Processing) Be lgium
A Basic understanding of the JavaScript Interpreter Data manipulation and processing means that JavaScript can read and act on data such as: numbers, user text, the contents of a file or a web page, image data, etc. • Input / Output • Data Manipulation & Processing dv-interaction-auto-complete
Examples of Data Manipulation and Processing “BELGIUM” 42 “Belgium” .toUpperCase() 35 + 7
A Basic understanding of the JavaScript Interpreter In regard to output, JavaScript can modify HTML ele - ments, dynamically create new ones and place them on the web page, modify the CSS, create graphics, manipu - late images, play sounds, etc. Input / Output • Data Manipulation (or Processing)

Chatting with JavaScript

Open your Browser's Console: F12

Ctrl + Shift + J / Cmd + Shift + J

JavaScript CSS index.html <html> <head> <link rel=”stylesheet” href=”style.css” /> <style> p { color: red; } </style> </head> <body> <p style=”color:red;”> Text </p> </body> </html>
JavaScript CSS index.html <html> <head> <link rel=”stylesheet” href=”style.css” /> <style> p { color: red; } </style> </head> <body> <p style=”color:red;”> Text </p> </body> </html> External 1
JavaScript CSS index.html <html> <head> <link rel=”stylesheet” href=”style.css” /> <style> p { color: red; } </style> </head> <body> <p style=”color:red;”> Text </p> </body> </html> Internal 2
JavaScript CSS index.html <html> <head> <link rel=”stylesheet” href=”style.css” /> <style> p { color: red; } </style> </head> <body> <p style=”color:red;” > Text </p> </body> </html> Inline 3
JavaScript CSS index.html <html> <head> <script src=”script.js”></script> <script> alert(’Hello’); </script> </head> <body> <p onclick=”alert(’Hello’);”> Text </p> </body> </html>
JavaScript CSS index.html <html> <head> <script src=”script.js”></script> <script> alert(’Hello’); </script> </head> <body> <p onclick=”alert(’Hello’);”> Text </p> </body> </html> External 1
JavaScript CSS index.html Internal 2 <html> <head> <script src=”script.js”></script> <script> alert(’Hello’); </script> </head> <body> <p onclick=”alert(’Hello’);”> Text </p> </body> </html>
JavaScript CSS index.html <html> <head> <script src=”script.js”></script> <script> alert(’Hello’); </script> </head> <body> <p onclick=”alert(’Hello’);” > Text </p> </body> </html> Inline 3
JavaScript CSS index.html <html> <head> </head> <body> <p onclick=”alert(’Hello’);”> Text </p> ... HTML CONTENT ... <script src=”script.js”></script> <script> alert(’Hello’); </script> </body> </html> Best practice tip: place <script> just before the closing </body> tag. !
Let's introduce ourselves to our first JS command
and test all these methods:
document.write( "Hello JS!" );
document.write( "

HTML is allowed also!

" );

- Internal <head><script>

- Internal </body><script>

- External <script src="app.js">
( app.js is just a text file with a .js extension )

- Inline (Should be avoided!)

* document.write @ Mozilla Developer Network

JavaScript statements Statements , are code instructions terminated by a semi - colon; They are executed one by one, in the same order as they are written: The main ingredients of statements are: Values, Operators, Keywords, Expressions and Comments . 1. doThisFirst(); 2. thenThis(); 3. andThis(); 4. lastlyDoThis();

Basic Data Values in JS:

Primitive Data Types

Strings (Text)

Numbers

Booleans (true, false)

A real life comparison...
Our first JavaScript statement! Once you’ve opened the browser console, type in the fol - lowing statements, terminated by a semicolon; > 2018 - 1995; 1995 was the year that Brendan Eich invented JavaScript! !
This is a basic math operation. (Remember Data Processing?) 2018 and 1995 are JavaScript Values ( Data ) of type: Number . The minus sign ( - ) is an Operator that acts on values (or oper - ands ) and produces a result. > 2018 - 1995; > 23 > typeof 2018; > “number” Use the typeof Operator to get the type of a value. !
Arithmetic Operators include: + Addition - Subtraction * Multiplication / Division ** Exponentiation % Remainder > 1995 + 23; > 2018 > 100 * 1.22; > 122 > 122 / 100; > 1.22 > 2 ** 3 > 8 > 10 + 5; 20 * 2; JavaScript also supports decimals (floating point numbers). !
What if we wanted more than one operation per statement? > 2018 - 1995 * 12; > -21932
We need to take Operator Precedence in consideration: • Multiplication • Division • Remainder • Addition • Subtraction > ( 2018 - 1995 ) * 12; > 276 > ( 20 - 10 ) * ( 30 / 2 ) / 20 - 10 > -2.5 > ( 20 - 10 ) * ( 30 / 2 ) / ( 20 - 10) > 15

More on Operator Precedence

W3Schools.com

( scroll until you find the JavaScript Operator Precedence Values section. )

MDN JS
Apart from Number values we can also enter String values. All text in JavaScript are of type String and are always enclosed inside “double” or ‘single’ quotes. We can also use the ( + ) operator on Strings, which concat - enates two or more of them into one String. > “Text”; > “Some big text. Spaces included :)”; > ‘Single quotes work also’; > ‘My name is’ + ‘ Tim’; > “One, ” + “Two, ” + “Three.”; Try: the typeof Operator on a text string. !

Comments

What are Comments?

Parts of the program that don't get executed

Single line comments:

// This is a single line comment

Multi-line comments:

/* Comments that
span multiple lines
can be placed like this.
*/

It's time to test our skills!

https://bit.ly/2U97u52

*In JavaScript there are 2 basic functions
to output values to the browser:
alert( VALUE );
console.log( VALUE );
Type Coercion: JavaScript tries to automatically convert the Type of some Values in order to perform an operation using the same Data Type . > “JavaScript is ” + 2018 - 1995 + “ years old”; > "NaN years old." 1) “JavaScript is ” + 2018 2) “JavaScript is 2018” - 1995 3) NaN + “ years old” 4) “NaN years old” NaN is a special JS value indicating a Not-A-Number. Fun fact: typeof NaN is “number”! !
What happens when we try to use the + or - operators on Strings and Numbers?
Implicit Coercion (Automatic)
"2" + 2;    
"22"    // String
2 + "2";
"22"   // String
"2" - 1;
1   // Number
2 - "2";
0   // Number
"A" - 2;
NaN
Explicit Coercion (Manual)
let strValue = "2";
let numValue = 2;
let floatValue = "3.1415";
Number( strValue ); 
//=> 2
parseInt( strValue, 10 );
//=> 2
parseFloat( floatValue, 10 );
//=> 3.1415
String( numValue );
//=> "2"
""+2
//=> "2"

Variables

( A dive into our mobile phone's
contacts mechanism )

Visual Representation

(We'll also see multiple entries per contact in the next slides.)

Storing values using Variables Values can be stored in memory and accessed at any point during the execution of our program using Vari - ables . We use the let and const keywords to declare a variable’s name and the assignment ( = ) Operator to assign a value Values stored in Variables can be accessed, just by call - ing their names: let someName = “Name”; let someDate; someDate = 2018; const dateOfBirth = 1995; someName; Returns: “Name” someDate; Returns: 2018 dateOfBirth; Returns: 1995
Storing values using Variables The values of Variables declared with the let keyword can be changed (re-assigned) at any point in the program. The value of variables declared with the const keyword is as - signed once during its declaration, and cannot be changed. let someName = “Name”; let someDate = 2018; const dateOfBirth = 1995; someName = “Other Name”; dateOfBirth = 2018; Uncaught TypeError: Assignment to constant variable Before ES6 all variables were declared with the var keyword. !

Let's see a visualization...

https://bit.ly/2AOczXA

Variable Naming Rules
  • Variables must not begin with a number: let 3sisters = "Chekhov";
  • Only the $ and _ non-alphanumeric characters are allowed
  • Variables names are case sensitive: myname is not the same as myName or MyName

It's time to test our skills!

Meet the Booleans Values of type Boolean , can be either true or false . Booleans can also be the result of Comparison Operators such as === which is used to compare two values: let someBoolean = true ; const anotherName = false ; console.log ( typeof someBoolean ); “boolean” console.log ( “text” === “text” ); true console.log ( 34 === 45 ); false The opposite of === is the !== operator which checks if two values are not the same. !
Arrays: lists of Values Arrays are Values grouped together in lists. They can contain all kinds of Data Types, such as Strings, Numbers, Booleans , including other Arrays . const numberList = [ 0, 1, 2, 3 ]; let listOfNames = [ ‘Abdul’, ‘Kostas’, ‘Chris’ ]; let mixedData = [ ‘Athens’, 2018, false, [ 1,2,3 ] ]; The typeof an Array is ‘object’! !
Arrays: Accessing Values You can access any Array element using the variable’s name followed by the index number within [ brackets ]: 0 1 2 listOfNames[0] ; ‘Abdul’ [ Abdul ,‘Kostas’,‘Chris’] listOfNames[1] ; ‘Kostas’ [‘Abdul’,‘ Kostas ’,‘Chris’] listOfNames[2] ; ‘Chris’ [‘Abdul’,‘Kostas’,‘ Chris ’] listOfNames[3] ; undefined Index count always starts from 0 !
Arrays: Adding & Removing Values You can add and remove values from an Array using the following methods: You can always check the number of elements in an Array using the length property: let numberList = [ 1, 2, 3 ] ; numberList . push ( 4 ); [ 1, 2, 3, 4 ] numberList . pop (); [ 1, 2, 3 _ ] numberList . unshift ( 0 ); [ 0 , 1, 2, 3 ] numberList . shift (); [ _ 1, 2, 3 ] console.log( numberList . length );
Let's check out some visualizations...

https://bit.ly/2Ue8btL

https://bit.ly/2KQCumh

...and come back to our mobile contact list example
with additional entries per contact!

It's time to test our skills!

More on Values: Null & Undefined Undefined is the value that gets returned when we try to access a variable with no assigned value: Null is a special object that can be assigned to a variable and indicates the absence of a value. let numberList; console.log( numberList ); “undefined” let emptyness = null; console.log( emptyness ); null console.log( typeof emptyness ); “object” undefined is returned when we try to get the typeof an undeclared variable: typeof nonExistentVar !

Comparison Operators

Comparison Operators == Checks whether two operands are equal != Checks whether two operands are not equal (Both of these operators, automatically convert the two operands to the same data type) === Checks whether two operands are equal and of the same type !== Checks whether two operands are of the same type and not equal or they are not of the same type 4 == 5 ; false 4 == 4 ; true 4 == “4” ; true ”text” == “text” ; true ”text” != “other” ; true 4 === 4 ; true 4 === “4” ; false 365 !== “text” true
Comparison Operators > Checks whether the left operand is greater than the right one >= Checks whether the left operand is greater than or equal to the right one < Checks whether the left operand is less than the right one <= Checks whether the left operand is less than or equal to the right one 4 > 5 ; false 4 >= 4 ; true 4 >= “4” ; true 4 < 5 ; true 2 >= 2 ; true

What's the use?

They help us switch our code
and add conditional logic

( Drawing Board / Conditionals Chart )

Logical Operators Logical OR || checks whether one of the two oper - ands returns true once they have been evaluated: Logical AND && checks whether both operands re - turns true once they have been evaluated: ( 5 > 4 ) || ( 4 > 3 ) ; true ( 5 > 4 ) || ( 4 < 3 ); true ”text” === “diff” || 4 == 3; false ( 5 > 4 ) && ( 4 > 3 ) ; true ( 5 > 4 ) && ( 4 < 3 ); false ”text” === “diff” && 4 == 3; false

Conditionals

{ Conditional Statements }

Image by: Guru99

if ... else

if { ... }

let trafficLight = 'red';

if ( trafficLight === 'red' ){

    console.log( "Stop the car!" );

}

if { ... } else { ... }

let trafficLight = 'red';

if ( trafficLight === 'red' ){

    console.log( "Stop the car!" );

} else {

    console.log( "Move on." );

}

NESTED if { ... } else { ... }

let trafficLight = 'red';

if ( trafficLight === 'red' ){
    console.log( "Stop the car!" );
} else {
    if ( trafficLight === "orange" ){
        console.log( "Slow down!" );
    } else {
        if ( trafficLight === "green" ){
        console.log( "Move on." );
        }
    }
}

This can be written like this...

if { ... } else if { ... }

if ( trafficLight === 'red' ){

    console.log( "Stop the car!" );

} else if ( trafficLight === "orange" ){

    console.log( "Slow down!" );

} else if ( trafficLight === "green" ){

    console.log( "Move on." );

}

The switch statement

No more else ... if's!

let trafficLight = "orange";
switch (trafficLight){
    case "red":
        console.log("Stop!");
        break;
    case "orange":
        console.log("Slow down");
        break;
    case "green":
        console.log("Move on");
        break;
    default:
        console.log("Default catch...");
}

More on the Switch Statement

Loops

The while ... loop

while ( EXPRESSION ){

    RUN CODE...

}

While some EXPRESSION evaluates to TRUE run the { code }

Example:
let counter = 0;

while ( counter < 3 ){

    console.log( "Counter value is: " + counter );
    counter = counter + 1;

}

Output:

Counter value is: 0
Counter value is: 1
Counter value is: 2
Example #2: Inner Counter
let counter = 0;

while ( counter++ < 3 ){

    console.log( "Counter value is: " + counter );

}

Output:

Counter value is: 1
Counter value is: 2
Counter value is: 3

Quick Practice:

https://bit.ly/2riL4RE

References:

Introduction to the JavaScript while loop statement

The for ... loop

A while statement with... a twist!
let counter = 0; 
while ( counter < 3 ){

    console.log( counter );
    counter = counter + 1;

}
for ( let counter = 0; counter < 3; counter = counter + 1 ){

    console.log( counter );

}

So, the loop structure is this:

for ( START STATEMENT; CONDITION; END STATEMENT ){

    CODE

}
Example:
let someArray = [ "a", "b", "c" ];

for ( let counter = 0; counter < someArray.length; counter++ ){

console.log( "Counter value is: " + someArray[counter] );

}

Output:

Counter value is: a
Counter value is: b
Counter value is: c

Quick Practice:

https://bit.ly/2sFunCg

Quick Mention:

The do ... while loop

W3Schools.com

Functions

Declaring a Function:

function repeatCode( param, otherParam ){

    console.log( param );
    console.log( otherParam );

}

Calling the Function:

repeatCode( "value for param", "value for otherParam" );

Will output:

"value for param"
"value for otherParam"

Declaring a Function (#2):

function repeatCode( param, otherParam ){

    console.log( param );
    console.log( otherParam );

}

Can be declared as:

let repeatCode = function( param, otherParam ){

    console.log( param );
    console.log( otherParam );

}

The return statement:

function repeatCode( one, two ){

    return one + two;

}
repeatCode( 4, 6 );
console.log( repeatCode( 4, 6 ) );
let sum = repeatCode( 4, 6 );
console.log( sum );

( What if there is no return statement present? )

Let's practice, shall we?

https://bit.ly/2RxaJl9

Objects

{ Advanced Data Structures }
Remember Arrays?
let arr = [ "Kosmas", "Kostas", "Chris" ]; 

console.log( arr[0] ); // "Kosmas"

Under the hood, this works much like this:

[ 0: "Kosmas", 1: "Kostas", 2: "Chris" ]

Try it on your console!

Objects as Variable Collections

let model = "Nokia";
let color = "Black";
let type  = "X5";

Organize:

{
    model : "Nokia",
    color : "Black",
    type  : "X5",
}

Pack:

let nokiaPhone = {
    model : "Nokia",
    color : "Black",
    type  : "X5",
}

Declaring an Object:

let obj = { 

    teacher: "Kosmas",
    assistant: "Kostas",
    founder: "Chris" 

}

In Objects, instead of using a numeric index for each element,
we explicitly define a key (String).

Accessing an Object Property:

let obj = { teacher: "Kosmas", assistant: "Kostas", founder: "Chris" }

console.log( obj["teacher"] );
console.log( obj.assistant );

Will Output:

"Kosmas"
"Kostas"

Setting an Object Property:

let obj = { teacher: "Kosmas", assistant: "Kostas", founder: "Chris" }

obj.teacher = "Mary";

console.log( obj );
console.log( obj["teacher"] );

Will Output:

{ teacher: "Mary", assistant: "Kostas", founder: "Chris" }
"Mary"

When an Object Property contains a Function, it is called a method

let car = {
    color: "red",
    year: 2010,
    type: "sports",
    showInfo: function(){
        console.log("A red sports car.");
    }
}
car.showInfo();

Will output:

"A red sports car."

You can access any Object property using the this keyword, while inside the Object.

let car = {
    color: "red",
    year: 2010,
    type: "sports",
    showInfo: function(){
        console.log("A " + this.color + " sports car.");
    }
}
car.showInfo();

Will output:

"A red sports car."

Why use this?

Using this

Recap

An Object is a collection of variables (called properties)
functions (called methods) which can be accessed
using the . dot
Object.property, Object.method()

let client = {
    age: 50,
    name: "Jane",
    surname: "Doe",
    getName: function(){

        console.log( this.name + " " + this.surname );

    } 
}

client.getName();
"Jane Doe"

Quick Practice?

https://bit.ly/2FWYb5d

Passing Data by Value
versus
Passing Data by Reference

By Value

Strings

Numbers

Booleans

null

undefined

(Primitives)

By Reference

Arrays

Objects

Functions

Visualization

Resources on Value Types & Reference Types

Value Types and Reference Types in JavaScript

Resources

Exercises & Practice Material:

About me

Tech Instructor

Full Stack Developer @ https://plethorathemes.com

And remember...