Javascript - Program the Web
This course covers the basics of programming in Javascript. Work your way through the videos and we'll teach you everything you need to know to make your website more responsive!

In One Video

Lesson 29
Author : Mike Dane
Last Updated : October, 2017


JavaScript Overview

Javascript is a high-level, dynamically typed and interpreted, programming language that was created in May of 1995 by Netscape employee Brendan Eich.

The language was famously created in only 10 days and adopted the name Javascript as a marketing play, playing off the hugly popular Java programming language. Although ironically the two languages are very different.

Javascript was built with the sole purpose of making websites more responsive and dynamic. Because it’s able to respond to user interactions and access and manipulate the document object model (DOM), Javascript allows web developers to make more dynamic websites.

In 1996 the early version of Javascript was adopted into a formal language specification called ECMAScript, of which Javascript was the most well known implementation. By specifying the language formally, all browsers could support languages implementing ECMAScript. So Technically Javascript is based off the ECMAScript specification.

How JavaScript Runs

Today Javascript is a staple, used on just about every modern website. It’s become one of the three core web development technologies along-side HTML and CSS.

Because javascript is a core web development technology and most web developers know it, Javascript has been stretched beyond it’s original purpose. Now-a-day’s there are thousands of javascript frameworks and it’s even used as a server-side language.

Javascript utilizes a garbage collector and it’s syntax is loosly based on C/C++.

Choosing an IDE

Many developers choose to write Javascript using a basic text editor, generally Javascript will be written in the same enviornment as the HTML and front end technologies that it interacts with. In many cases javascript will be written directly inside of an HTML file, but can also be palced in it’s own separate Javascript file and imported into HTML.

Code

Printing

Copydocument.write("<h1>Hello World</h1>");
document.write("<hr>");
document.write("<p>This is a javascript tutorial</p>");
alert("This is an alert");
console.log("Logging to the console");

Variables and Data Types

Copy/*
Names are case-sensitive and may begin with:
     letters, $, _
After, may include
     letters, numbers, $, _
Convention says
     Start with a lowercase word, then additional words are capitalized
     ex. myFirstVariable
*/
var name = "Mike";                 // String w/ double quotes
var occupation = 'programmer';     // String w/ single quotes

var age = 20;                      // Integer
var gpa = 2.5;                     // Floating point number

var isTall;                        // boolean true/false
isTall = true;

name = "John";

document.write("Your name is " + name);

Casting and Converting

Copydocument.write( 100 + Number("25") + "<br>");
document.write( 100 + parseInt("50") + "<br>");
document.write( 100 + parseFloat("50.99") + "<br>");

Strings

Copyvar greeting = "Hello";
//   indexes:   01234

document.write( greeting.length + "<br>" );
document.write( greeting.charAt(0) + "<br>"  );
document.write( greeting.indexOf("llo") + "<br>"  );
document.write( greeting.indexOf("z") + "<br>"  );
document.write( greeting.substring(2) + "<br>"  );
document.write( greeting.substring(1, 3) + "<br>"  );

Numbers

Copydocument.write( 2 * 3 + "<br>" );       // Basic Arithmetic: +, -, /, *
document.write( 2**3 + "<br>" );        // Exponents
document.write( 10 % 3 + "<br>" );      // Modulus Op. : returns remainder of 10/3
document.write( 1 + 2 * 3 + "<br>" );   // order of operations
document.write(10 / 3.0 + "<br><br>");      // int's and doubles


var num = 10;
num += 100;                              // +=, -=, /=, *=
document.write(num + "<br>");

num++;
document.write(num + "<br><br>");

// Math class has useful math methods
document.write( Math.pow(2, 3) + "<br>" );
document.write( Math.sqrt(144) + "<br>" );
document.write( Math.round(2.7) + "<br>" );

User Input

Copyvar name = window.prompt("Enter your name: ");
alert("Your name is " + name);

Accessing HTML

index.htmlCopy
<h1 id="myHeader" giraffe="Giraffe Attr">Mike Dane</h1> <script src="script.js"></script>
script.jsCopy
var header = document.getElementById("myHeader"); header.style="color:blue; background-color:red;" document.write( header.getAttribute("giraffe") ); header.innerHTML = "Elephant Academy";

Arrays

Copy// luckyNumbers = [];
luckyNumbers = [4, 8, 15, 16, "twenty", false];
//  indexes:    0  1  2   3      4        5

luckyNumbers[0] = 90;
document.write(luckyNumbers[0] + "<br>");
document.write(luckyNumbers[1] + "<br>");
document.write(luckyNumbers.length);

2 Dimensional Arrays

CopynumberGrid = [ [1, 2], [3, 4] ];
numberGrid[0][1] = 99;

document.write(numberGrid[0][0] + "<br>");
document.write(numberGrid[0][1] + "<br>");

Array Functions

Copyfriends = new Array();
friends.push("Oscar");
friends.push("Angela");
friends.push("Kevin");

// friends.pop();
document.write( friends + "<br>" );
document.write( friends.indexOf("Angela") + "<br>" );
document.write( friends.indexOf("Z") + "<br>" );
document.write( friends.reverse() + "<br>" );
document.write( friends.sort() + "<br>" );

Objects

Copyvar student = {
     name: "Jim",
     major: "Business",
     age: 19,
     gpa: 2.5
};

student.name = "Andy"
document.write( student.name + "<br>" );
document.write( student.major + "<br>" );
document.write( student.gpa + "<br>" );

Functions

Copyvar sum = addNumbers(4, 60);
document.write(sum);

function addNumbers(num1, num2){
     return num1 + num2;
}

Inline Event Listeners

https://www.w3schools.com/jsref/dom_obj_event.asp

index.htmlCopy
<h1 id="myHeader" onclick="handleClick(this)">Mike Dane</h1> <script src="script.js"></script>
script.jsCopy
function handleClick(element){ alert("Clicked " + element.id); }

Programatic Event Listeners

https://www.w3schools.com/jsref/dom_obj_event.asp

index.htmlCopy
<h1 id="myHeader">Mike Dane</h1> <script src="script.js"></script>
script.jsCopy
var header = document.getElementById("myHeader"); header.addEventListener("click", function(){ alert("You clicked " + header.id); }); ### If Statements <pre class="" style="font-size:18px; position:relative;"onmouseover="this.childNodes[0].className = 'red white-text right'; " onmouseout="this.childNodes[0].className = 'red lighten-2 white-text right hide'"><span id="copyBtn" onclick="copyTextToClipboard(this, &#34;\nvar isStudent = false;\nvar isSmart = false;\n\nif(isStudent \u0026\u0026 isSmart){\n document.write(\&#34;You are a student\&#34;);\n} else if(isStudent \u0026\u0026 !isSmart){\n document.write(\&#34;You are not a smart student\&#34;);\n} else {\n document.write(\&#34;You are not a student and not smart\&#34;);\n}\ndocument.write(\&#34;\u003cbr\u003e\&#34;);\n\n// \u003e, \u003c, \u003e=, \u003c=, !=, ==\nif(1 \u003e 3){\n document.write(\&#34;number comparison was true\&#34;);\n}\ndocument.write(\&#34;\u003cbr\u003e\&#34;);\n\nif(\&#34;dog\&#34; != \&#34;dog\&#34;){\n document.write(\&#34;string comparison was true\&#34;);\n}\n&#34;)" style="font-family:arial; position: absolute; right:10px; top:10px; padding-left:10px; padding-right:10px; cursor:pointer; font-size: 18px; " class="red lighten-2 white-text right hide">Copy</span><code id="code" style="padding:15px;" class="js">var isStudent = false; var isSmart = false; if(isStudent &amp;&amp; isSmart){ document.write(&#34;You are a student&#34;); } else if(isStudent &amp;&amp; !isSmart){ document.write(&#34;You are not a smart student&#34;); } else { document.write(&#34;You are not a student and not smart&#34;); } document.write(&#34;&lt;br&gt;&#34;); // &gt;, &lt;, &gt;=, &lt;=, !=, == if(1 &gt; 3){ document.write(&#34;number comparison was true&#34;); } document.write(&#34;&lt;br&gt;&#34;); if(&#34;dog&#34; != &#34;dog&#34;){ document.write(&#34;string comparison was true&#34;); }</code></pre> ### Switch Statements <pre class="" style="font-size:18px; position:relative;"onmouseover="this.childNodes[0].className = 'red white-text right'; " onmouseout="this.childNodes[0].className = 'red lighten-2 white-text right hide'"><span id="copyBtn" onclick="copyTextToClipboard(this, &#34;\nvar myGrade = \&#34;A\&#34;;\nswitch(myGrade){\n case \&#34;A\&#34;:\n document.write(\&#34;You Pass\&#34;);\n break;\n case \&#34;F\&#34;:\n document.write(\&#34;You fail\&#34;);\n break;\n default:\n document.write(\&#34;Invalid grade\&#34;);\n}\n&#34;)" style="font-family:arial; position: absolute; right:10px; top:10px; padding-left:10px; padding-right:10px; cursor:pointer; font-size: 18px; " class="red lighten-2 white-text right hide">Copy</span><code id="code" style="padding:15px;" class="js">var myGrade = &#34;A&#34;; switch(myGrade){ case &#34;A&#34;: document.write(&#34;You Pass&#34;); break; case &#34;F&#34;: document.write(&#34;You fail&#34;); break; default: document.write(&#34;Invalid grade&#34;); }</code></pre> ### While Loops <pre class="" style="font-size:18px; position:relative;"onmouseover="this.childNodes[0].className = 'red white-text right'; " onmouseout="this.childNodes[0].className = 'red lighten-2 white-text right hide'"><span id="copyBtn" onclick="copyTextToClipboard(this, &#34;\nvar index = 1;\nwhile(index \u003c= 5){\n document.write(index);\n index&#43;&#43;;\n}\n\nindex = 1;\ndo{\n\tdocument.write(index);\n\tindex&#43;&#43;;\n}while(index \u003c= 5);\n&#34;)" style="font-family:arial; position: absolute; right:10px; top:10px; padding-left:10px; padding-right:10px; cursor:pointer; font-size: 18px; " class="red lighten-2 white-text right hide">Copy</span><code id="code" style="padding:15px;" class="js">var index = 1; while(index &lt;= 5){ document.write(index); index&#43;&#43;; } index = 1; do{ document.write(index); index&#43;&#43;; }while(index &lt;= 5);</code></pre> ### For Loops <pre class="" style="font-size:18px; position:relative;"onmouseover="this.childNodes[0].className = 'red white-text right'; " onmouseout="this.childNodes[0].className = 'red lighten-2 white-text right hide'"><span id="copyBtn" onclick="copyTextToClipboard(this, &#34;\nfor(var i = 0; i \u003c 5; i&#43;&#43;){\n document.write(i);\n}\n\nvar luckyNums = [4, 8, 15, 16, 23, 42];\nluckyNums.forEach(function(luckyNum){\n document.write(luckyNum &#43; \&#34;\u003cbr\u003e\&#34;);\n});\n&#34;)" style="font-family:arial; position: absolute; right:10px; top:10px; padding-left:10px; padding-right:10px; cursor:pointer; font-size: 18px; " class="red lighten-2 white-text right hide">Copy</span><code id="code" style="padding:15px;" class="js">for(var i = 0; i &lt; 5; i&#43;&#43;){ document.write(i); } var luckyNums = [4, 8, 15, 16, 23, 42]; luckyNums.forEach(function(luckyNum){ document.write(luckyNum &#43; &#34;&lt;br&gt;&#34;); });</code></pre> ### Exception Catching <pre class="" style="font-size:18px; position:relative;"onmouseover="this.childNodes[0].className = 'red white-text right'; " onmouseout="this.childNodes[0].className = 'red lighten-2 white-text right hide'"><span id="copyBtn" onclick="copyTextToClipboard(this, &#34;\ntry{\n // throw \&#34;Something went wrong\&#34;\n var x = y &#43; 9;\n}catch(err){\n document.write(err)\n}finally{\n // this code always gets executed\n}\n&#34;)" style="font-family:arial; position: absolute; right:10px; top:10px; padding-left:10px; padding-right:10px; cursor:pointer; font-size: 18px; " class="red lighten-2 white-text right hide">Copy</span><code id="code" style="padding:15px;" class="js">try{ // throw &#34;Something went wrong&#34; var x = y &#43; 9; }catch(err){ document.write(err) }finally{ // this code always gets executed }</code></pre> ### Classes and Objects <pre class="" style="font-size:18px; position:relative;"onmouseover="this.childNodes[0].className = 'red white-text right'; " onmouseout="this.childNodes[0].className = 'red lighten-2 white-text right hide'"><span id="copyBtn" onclick="copyTextToClipboard(this, &#34;\nclass Book{\n constructor(title, author){\n this.title = title;\n this.author = author;\n }\n\n readBook(){\n document.write(\&#34;Reading \&#34; &#43; this.title &#43; \&#34; by \&#34; &#43; this.author);\n }\n}\n\nvar book1 = new Book(\&#34;Harry Potter\&#34;, \&#34;JK Rowling\&#34;);\n\ndocument.write(book1.title &#43; \&#34;\u003cbr\u003e\&#34;);\nbook1.readBook();\n&#34;)" style="font-family:arial; position: absolute; right:10px; top:10px; padding-left:10px; padding-right:10px; cursor:pointer; font-size: 18px; " class="red lighten-2 white-text right hide">Copy</span><code id="code" style="padding:15px;" class="js">class Book{ constructor(title, author){ this.title = title; this.author = author; } readBook(){ document.write(&#34;Reading &#34; &#43; this.title &#43; &#34; by &#34; &#43; this.author); } } var book1 = new Book(&#34;Harry Potter&#34;, &#34;JK Rowling&#34;); document.write(book1.title &#43; &#34;&lt;br&gt;&#34;); book1.readBook();</code></pre> ### Getters and Setters <pre class="" style="font-size:18px; position:relative;"onmouseover="this.childNodes[0].className = 'red white-text right'; " onmouseout="this.childNodes[0].className = 'red lighten-2 white-text right hide'"><span id="copyBtn" onclick="copyTextToClipboard(this, &#34;\nclass Book{\n constructor(title, author){\n this.title = title;\n this.author = author;\n }\n\n get title(){\n document.write(\&#34;\u003cp\u003egetting\u003c/p\u003e\&#34;);\n return this._title;\n }\n\n set title(title){\n document.write(\&#34;\u003cp\u003esetting \u003c/p\u003e\&#34;);\n this._title = title;\n }\n\n readBook(){\n document.write(\&#34;Reading \&#34; &#43; this.title &#43; \&#34; by \&#34; &#43; this.author);\n }\n}\n\nvar book1 = new Book(\&#34;Harry Potter\&#34;, \&#34;JK Rowling\&#34;);\n\ndocument.write(book1.title &#43; \&#34;\u003cbr\u003e\&#34;);\nbook1.readBook();\n&#34;)" style="font-family:arial; position: absolute; right:10px; top:10px; padding-left:10px; padding-right:10px; cursor:pointer; font-size: 18px; " class="red lighten-2 white-text right hide">Copy</span><code id="code" style="padding:15px;" class="js">class Book{ constructor(title, author){ this.title = title; this.author = author; } get title(){ document.write(&#34;&lt;p&gt;getting&lt;/p&gt;&#34;); return this._title; } set title(title){ document.write(&#34;&lt;p&gt;setting &lt;/p&gt;&#34;); this._title = title; } readBook(){ document.write(&#34;Reading &#34; &#43; this.title &#43; &#34; by &#34; &#43; this.author); } } var book1 = new Book(&#34;Harry Potter&#34;, &#34;JK Rowling&#34;); document.write(book1.title &#43; &#34;&lt;br&gt;&#34;); book1.readBook();</code></pre> ### Inheritance <pre class="" style="font-size:18px; position:relative;"onmouseover="this.childNodes[0].className = 'red white-text right'; " onmouseout="this.childNodes[0].className = 'red lighten-2 white-text right hide'"><span id="copyBtn" onclick="copyTextToClipboard(this, &#34;\nclass Chef{\n\n constructor(name, age){\n this.name = name;\n this.age = age;\n }\n\n makeChicken(){\n document.write(\&#34;The chef makes chicken \u003cbr\u003e\&#34;);\n }\n\n makeSalad(){\n document.write(\&#34;The chef makes salad \u003cbr\u003e\&#34;);\n }\n\n makeSpecialDish(){\n document.write(\&#34;The chef makes a special dish \u003cbr\u003e\&#34;);\n }\n}\n\nclass ItalianChef extends Chef{\n\n constructor(name, age, countryOfOrigin){\n super(name, age);\n this.countryOfOrigin = countryOfOrigin;\n }\n\n makePasta(){\n document.write(\&#34;The chef makes pasta \u003cbr\u003e\&#34;);\n }\n\n // overridden\n makeSpecialDish(){\n document.write(\&#34;The chef makes chicken parm \u003cbr\u003e\&#34;);\n }\n}\n\nvar myChef = new Chef(\&#34;Gordon Ramsay\&#34;, 50);\nmyChef.makeChicken();\n\nvar myItalianChef = new ItalianChef(\&#34;Massimo Bottura\&#34;, 55, \&#34;Italy\&#34;);\nmyItalianChef.makeChicken();\ndocument.write(myItalianChef.age);\n&#34;)" style="font-family:arial; position: absolute; right:10px; top:10px; padding-left:10px; padding-right:10px; cursor:pointer; font-size: 18px; " class="red lighten-2 white-text right hide">Copy</span><code id="code" style="padding:15px;" class="js">class Chef{ constructor(name, age){ this.name = name; this.age = age; } makeChicken(){ document.write(&#34;The chef makes chicken &lt;br&gt;&#34;); } makeSalad(){ document.write(&#34;The chef makes salad &lt;br&gt;&#34;); } makeSpecialDish(){ document.write(&#34;The chef makes a special dish &lt;br&gt;&#34;); } } class ItalianChef extends Chef{ constructor(name, age, countryOfOrigin){ super(name, age); this.countryOfOrigin = countryOfOrigin; } makePasta(){ document.write(&#34;The chef makes pasta &lt;br&gt;&#34;); } // overridden makeSpecialDish(){ document.write(&#34;The chef makes chicken parm &lt;br&gt;&#34;); } } var myChef = new Chef(&#34;Gordon Ramsay&#34;, 50); myChef.makeChicken(); var myItalianChef = new ItalianChef(&#34;Massimo Bottura&#34;, 55, &#34;Italy&#34;); myItalianChef.makeChicken(); document.write(myItalianChef.age);</code></pre>