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

Syntax

Statements

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

Comments

// this is a single line comment
     
/* 
   this is a multi-
   line comment
*/

Exercise: Add comments to the last file

Types of Data

  • Numbers
  • Strings
  • Booleans
  • Objects
     'Estelle'
     "Estelle"
     "It's JavaScript"
     'It\'s JavaScript'
     true
     27
     3.1415
     window

Everything in JavaScript is an Object!

Declaring Strings

'Estelle'
"Estelle"
'It\'s JavaScript'
'\'\\\' is called a \'back slash\''
var goodString = "Really long strings" + 
  " can be concatenated across lines";

var goodString = "This is\
 another way of creating\
 a multi-line string"

var badString = "This will
 fail"        
          

Exercise: Copy & Paste above strings in console

Variables

// 2 steps: Name and declare the variable
var firstName;
firstName = "Estelle";

// Name and declare in one step
var firstName = "Estelle";
     
  • Begin with letters, numbers, $ or _
  • Only contain letters, numbers, $ and _
  • Case sensitive
  • Avoid reserved words →
  • 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

Declaring Variables

var firstName, lastName, age, isAwesome;
    firstName = "Estelle";
    lastName = 'Weyl';
    age = 29;
    isAwesome = true;
var firstName = "Estelle";
var lastName = 'Weyl';
var age = 29;
var isAwesome = true;
var firstName = "Estelle",
    lastName = 'Weyl',
    age = 29,
    isAwesome = true; 
var firstName="Estelle",lastName='Weyl',age=29,isAwesome=true;

Loosely typed language

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

anyValue = true; 			// boolean

anyValue = [3, 'red ribbon', true, 24];	//array

Global Scope

Object Notation

 var person = {
    firstName: "Estelle",
    lastName: 'Weyl',
    age: 29,
    isAwesome: true
 }; 
var person = new Object();
    person['firstName'] = "Estelle",
    person['lastName'] = 'Weyl',
    person['age'] = 29,
    person['isAwesome'] = true; 
var person = 'foo'; // or assign any objectish value
    person.firstName =  "Estelle",
    person.lastName =  'Weyl',
    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;

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;

Modulus

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

Exercise:

  • Guess: what are the values for the 3 slides?
  • Test the values in the console.
  • Write a few equations and test in console.

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";
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 also 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