Press key to advance. Zoom in/out: Ctrl or Command + +/-.

Basic JavaScript

Estelle Weyl

Including Javascript in your HTML

<!doctype html>
<html>
    <head>
        <title>This is a document</title>
        <script src="js/script.js"></script>
        <script>
        	/* code goes here */
        </script>
    </head>
    <body onload="badPlaceToPutJSButAllowed();">
        <script>
       	 // also allowed here
        </script>
        <script src="js/script2.js"></script>
    </body>
</html>
     

Exercise

Try it!
Basic HTML5 template

  • Add an external script in the head
  • Add an embedded script in the head
  • Add an external script in the body
  • Add an embedded script in the body

Warning!!!

Now that you know how to include JavaScript in your webpages, realize that you should not include your JS in the <head> in production. When your browser hits a script in a document while loading the page, it ceases all downloads and rendering until it finishes downloading, parsing and executing your script.

Put your scripts at the *end* of your documents to improve perceived download speed.

Your browser is single threaded. When downloading, parsing and executing JS, all other features (download, user interactions like button clicking, etc) are paused until your browser is finished with the JavaScript

Syntax

Statements

alert('this is an alert');
var addition = 14 * 7;
var functionName = function(){
    alert('an alert');
};

Don't worry if this slide doesn't make sense yet

Comments

Comments make your code more understandable for those updating your code in the future, including YOU!

Single Line Comments

// this is a single line comment

Multi Line Comments

     
/* 
   this is a multi-
   line comment
*/

Exercise: Add comments to the last file

Data Types

Primitive Types

  • Numbers
  • Strings
  • Booleans
  • null
  • undefined
     'Estelle'
     "It's JavaScript"
     'It\'s JavaScript'
     true
     27
     3.1415

Objects

Everything else in JavaScript is an Object!

Numbers

3 === 3.0000000
  • 64-bit float
  • A single number type
 5e3 == 5000 
0x12 == 18 // base 16
 010 ==  8 // base 8

typeof NaN // "number"
typeof Infinity // "number"

Implicit Type Coercion

 3  + 3 ===  6
"3" + 3 === "33"
 3  * 1 ===  3
"3" * 1 ===  3

String Basics

'Estelle'
"Estelle"
'It\'s JavaScript'
'\'\\\' is called a \'back slash\''
"Don't need to escape with mixed quotes"
var goodString = "Really long strings" + 
  " can be concatenated across lines";

var goodString = "This may work but is a \
  bad idea. Space at end?"

var badString = "This will
 fail"        
          

Exercise: Copy & Paste above strings in console

Booleans

true
false
var truthy = true,
    falsey = false;

Variables & Assignment

Variable

var firstName;

Variables that are declared but not assigned return undefined

Assignment

firstName = "Estelle";

Variable and Assignment

var firstName = "Estelle";

Several Variables

Variables

var firstName, lastname, age;

With Assignment

var firstName = "Estelle",
    lastname = "Weyl",
    age = 29;

You can declare (and assign) several variables in a single statement, with multi-line statements being way easier to read

Declaring Variables

var firstName, age, isAwesome;
    firstName = "Estelle";
    age = 29;
    isAwesome = true;
var firstName = "Estelle";
var age = 29;
var isAwesome = true;
var firstName = "Estelle",
    age = 29,
    isAwesome = true; 
var firstName="Estelle",age=29,isAwesome=true;

Variables

  • Begin with letters, numbers, $ or _
  • Only contain letters, numbers, $ and _
  • Case sensitive
  • Avoid reserved words see next slide →
  • Choose clarity and meaning
  • Pick a naming convention and stick with it
  • break
  • case
  • catch
  • continue
  • debugger
  • default
  • delete
  • do
  • else
  • finally
  • for
  • function
  • if
  • in
  • instanceof
  • new
  • return
  • switch
  • this
  • throw
  • try
  • typeof
  • var
  • void
  • while
  • with
  • class
  • enum
  • export
  • extends
  • import
  • super
  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield
  • abstract
  • boolean
  • byte
  • char
  • const
  • double
  • final
  • float
  • goto
  • import
  • int
  • long
  • native
  • short
  • synchronized
  • throws
  • transient
  • volatile
  • true
  • false
  • null
  • undefined

Reserved for Browser

  • alert
  • blur
  • closed
  • document
  • focus
  • frames
  • history
  • innerHeight
  • innerWidth
  • length
  • location
  • navigator
  • open
  • outerHeight
  • outerWidth
  • parent
  • screen
  • screenX
  • screenY
  • statusbar
  • window

Loosely typed language

var anyValue = 'red ribbon';       // string
     
    anyValue = 24;                 // number   

    anyValue = true;               // boolean

    anyValue = [3, 'hello', true]; // array

Unlike many other programming languages, JS is loosely typed. Variable types are not declared. Variable will be reassigned to a different type with assignment to a different type.

Global Scope

Any variable declared outside of a function will have global scope. In the browser this means that all global variables and functions are methods and properties of the window object.

To avoid polluting the window object, namespace your code.

Object Notation

 var person = {
    firstName: "Estelle",
    age: 29,
    isAwesome: true
 }; 
var person = new Object();
    person['firstName'] = "Estelle",
    person['age'] = 29,
    person['isAwesome'] = true; 
var person = {}; 
    person.firstName =  "Estelle",
    person.age = 29,
    person.isAwesome = true;

Basic Math

Operators

  • +
  • -
  • *
  • /
  • %
var cost = 2.5;
var quantity = 10;
var total = cost * quantity;
  • Order of operations is same as math. (Use parentheses.)
  • modulo → remainder

Addition & Subtraction

var easy = 2 + 2;
var hard = 6298 + 3817;
var sum = easy + hard;
var easy = 10 - 5;
var hard = 6298 - 3817;
var difference = hard - easy;

Exercise: Get the values for easy, hard, sum and difference

Multiplication & Division

var easy = 5 * 5;
var hard = 11 * 7;
var product = easy * hard;
var easy = 5 / 5;
var hard = 51 / 17;
var quotient = hard / easy;

Exercise: Get the values for easy, hard, product and quotient

Note: dividing any number by 0 returns infinity

Modulus

var easy = 10 % 7;
var hard = 41 % 7;
var modulus = hard % easy;

Exercise: Get the values for easy, hard and modulus.

Here are a few more equations to put in the console:

4 + 7			10 % 3
5 - 2           	12 % 4
9 * 9           	30 % 28
27 / 3			44 % 7
9 + 2 * 3 - 8
(9 + 2) * (3 - 8)

Concatenation

var firstName = "Estelle";
var lastName = "Weyl";
var age = 29;
var fullName = firstName + " " + lastName;

Joining Numbers and String

var sentence = firstName + 
  " is not really " + age + " years old";

Type conversion to enable math

var notMath = '2' + 4;			// 24

var yupMath = +'2' + 4; 		// 6

var yupMath = Number('2') + 4; 		// 6

var notMath = Number('2foo') + 4 	// NaN

var yupMath = parseInt('2foo') + 4;	// 6

Exercise:
Try the expressions above, and try your own

Loosely Typed Language

Type casting

var yupMath = '2' * 1 + 4; 	// 6
var yupMath = '2' * 4; 		// 8

 

if("1" == 1) {
	// true
}

if("1" === 1) {
	//false
}

Operator Shortcuts

  • +=
  • -=
  • *=
  • /=
  • ++
  • --
var increment += 1;
  ++increment;
    increment++;
var decrement -= 1;
  --decrement;
    decrement--;

    errorMessage += " " + newError;
var iteration = 0;
console.log('value of iteration is: ' + iteration++);
console.log('value of iteration is: ' + ++iteration);

MadLibs with Window Methods

var color = window.prompt('Your favorite color');
var tool = window.prompt('What do you draw with?');
var count = window.prompt('Favorite Number?');
window.alert(count + ' ' + color + ' ' + tool + 's');
var answers = {
  color: window.prompt('Favorite Color'),
  tool: window.prompt('What do you draw with?'),
  count: window.prompt('Favorite Number?'),
  message: function(){
	  return answers.count + ' ' + answers.color + ' ' + answers.tool + 's';
  },
  annoy: function(){ 
      alert('You told us: ' + answers.message());
  }
};
answers.annoy();

Exercise

Get the answers to these math problems:

  • 27 * 6 - 18
  • The value of 28 ÷ 2
  • the remainder of 29 ÷ 3

Get the browser to alert your name

Get the browser to approximate your age with current year and birth year

Next

Go