the grammar of javascript. each line of a script is a statement an instruction that javascript can...

30
JAVASCRIPT The Grammar of JavaScript

Upload: elmer-oneal

Post on 13-Jan-2016

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

JAVASCRIPTThe Grammar of JavaScript

Page 2: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

STATEMENTS IN A SCRIPT Each line of a script is a statement An instruction that JavaScript can

evaluate (make sense of) Ends with a semicolon; Each one on a new line

Example: var x =2; var y = 3; alert(x + y); // displays 5

Page 3: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

VARIABLES OVERVIEW Used to represent or hold a value The value of a variable can change over

time Give a variable a name and then assign

a value to it

Remember Algebra?x = 100 let x hold the value 100x = 200 now x holds the value 200

The concepts are similar – JavaScript variable and Algebra variable

Page 4: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

VARIABLES AS CODE CLARIFIERS Words are more meaningful than

numbers You don’t have to remember what a

number means

payRate = 10.50;year = 2010; totalPrice = cost + tax;

Page 5: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

VARIABLES ANALOGY

Variables can be compared to small boxes with names.

If you were to store 5 pair of shoes, you might have a box for each pair. On each box you would write what is in it.

The boxes would be your variables.- Places to store things.

The name on the boxes would be the variable names. - The ones you'd use when referring to each of the boxes.

And finally the shoes, would be the content of the variables.- What is stored in the boxes

Note: from http://www.echoecho.com/javascript5.htm

Page 6: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

DECLARING VARIABLES AND ASSIGNING VALUESStandard Form:

var variablename = value;

var is a keyword ( a reserved word) Variablename – a user defined name = the assignment operator Value – value to be assigned

Examplesvar interestRate = 0.08;var carType = “Mustang”;var salary = 3000;var answer = false;

Page 7: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

VARIABLE NAMES Give variable names meaningful names!!!

Case sensitive (y and Y are two different variables)

Must begin with a letter or the underscore character

Good Practice: use camelCase naming convention First word lower case, every subsequent word – the first

letter is uppercase Example

dayOfWeek firstName myDogsName

Page 8: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

VARIABLE TYPES – DATA & WAYS TO STORE IT

You are not forced to declare a “type” of a variable like in more strict languagesNumbers: can have integers, floats,

exponential values x = 22.9;

Strings: text characters need to be enclosed by double or single quotes firstName = “Mickey”;

Boolean: Value is true or false true and false are reserved words – don’t need

quotes switchOn = true;

null – no value middleName = null;

Page 9: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

NUMERIC VARIABLE TYPES Unlike other programming languages, there is no

int or float variable type You do not have to tell the interpreter the data

type, it is assumed when you assign data to the variable

x = x + 1; //doesn’t make sense in algebra It means: take whatever is on the right side and

assign it to whatever is on the left side If x was 10 to start, after this line of code is

interpretted, x is 11 IMPORTANT: = is used as assignment operator IMPORTANT : == is used as a relational operator

(a comparison)

Page 10: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

BUILT IN STRING FUNCTION LENGTH Consist of 1 or more characters in

quotes:var shirtSize= “medium”var month = “October”

length methodalert(month.length);Displays the number 7

alert(shirtSize.length)Displays the number 6

Page 11: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

DOCUMENT.WRITE Use to print out a line of text

document.write(“hello world”); Can embed html elements into the write

functionTo place a line feed at the end of a line of

text+ concatenation operator

document.write(“hello world” + “<br>”); To make a line of text an h2 element

document.write(“<h2>” + “hi there” + “</h2>”)

Page 12: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

USING VARIABLES IN SCRIPTS

var myDog = “durango”;document.write(myDog); this prints the value stored in myDog

document.write(“My dog is named “ + myDog);this prints the text “My dog is named” followed by the value stored in myDog

document.write(“My dog is named “ + myDog + “ and he is very nice”);

this prints the text “My dog is named” followed by the value stored in myDog followed by the text “and he is very nice”

Do VariablesStudent.html

Page 13: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

MATHEMATICAL OPERATORS Purpose: used to perform math calculations

on 2 or more valuesOperator Symbo

lFunction

Addition + Add 2 values

Subtraction - Subtract 1 value from another

Multiplication * Multiply 2 numbers

Division / Divide 1 value by another

Modulus % Remainder

Increment ++ Shortcut – add 1 to a single number

Decrement -- Shortcut – subtract1 a single number

Page 14: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

EXAMPLES USING MATH OPERATORSvar x = 10;var y = x + 20;var z = y / x;var mod = y % z;var mod2 = x % 4;

document.write(“x:” + x);document.write(“y:” + y);document.write(“z:” + z);document.write(“mod:” + mod);document.write(“mod2:” + mod2);

Page 15: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

INCREMENT / DECREMENT OPERATOR Increment: ++myVariable;

Adds 1 to the value stored in myVariable

Decrement: --myVariable; Subtracts 1 to the value stored in myVariable

Examples:var x = 20;var y = 10;

var incrementedX = ++x;var decrementedY = --y;

document.write(incrementedX); //will print 21document.write(decrementedY ); // will print 9

Page 16: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

WINDOW.ALERT A method used to display info in a pop-

up window Examples:

var theName = “James”;window.alert(“hello “+ theName);

var theAge = 22;window.alert(“You are “ + theAge + “

years old”);

Page 17: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

SPECIAL CHARACTERS Used to add things to strings

window.alert(“\nthis is fun \n”);

Character Meaning

\t tab

\n Newline

\\ backslash

\” Double quote

\’ Single quote

Page 18: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

WINDOW.PROMPT A method used to prompt the user for

information Examples:

var theName = window.prompt(“What is your name?”);

window.alert(“hello “ + theName);

var theAge = window.prompt(“What is your age?”);

window.alert(“You are “ + theAge + “ years old”);

Page 19: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

BUILT IN NUMERIC FUNCTIONS isNaN( ) – determines whether a

number is legal

Math.PI – returns value of pi

Math.Random( ) – returns random number

Math.pow(x, y) – returns x to the power of y

Page 20: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

WINDOW.PROMPT RETURN TYPE The result of a window.prompt method call is a

string You can not do math on a string, so if you are

prompting the user to enter a number that you want to do math on, you must convert it.

Example:var theNum1 = window.prompt("enter a number");

var theNum2 = window.prompt("enter another number");

var newNum = theNum1 + theNum2;

window.alert("new num is: " + newNum);

If user enters a 1 and then a 2, the alert window says:

new num is 12 ?????? Not what we expected

Page 21: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

NEED TO CONVERT STRING TO A NUMBER parseInt- Parses a string and returns an

integer parseFloat - Parses a string and returns an

float Example:

var theNum1 = window.prompt("enter a number");var theNum2 = window.prompt("enter another number");var newNum = parseInt(theNum1) + parseInt(theNum2);

window.alert("new num is: " + newNum);

Page 22: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

ASSIGNMENT OPERATORS Purpose: used to used to assign values to

variables

Operator Symbol Function

Assignment = Assign the value on the right side of the operator to a variable

Add and assign += Adds the value on the right side of the operator to the variable on the left side and then assigns the new value to the variable

Subtract and assign

-= Same as above except “subtract”

Multiple and assign

*= Same as above except “multiply”

Divide and assign /= Same as above except “divide”

Modulus and assign

%= Same as above except “modulus”

Page 23: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

EXAMPLES OF USING ASSIGNMENT OPERATORSvar total = 100;total += 50; // same as total = total + 50

//total stores value 150

total -= 30; // same as total = total – 30// total stores value 120

total /= 2; // same as total = total /2// total stores value 60

total %= 5; // same as total = total /5 (modulus )// total stores value 0

Page 24: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

ARRAYS Purpose: a way of storing more than 1 value

in a single place Shopping list analogy:

you can add things to your list when you need something

You can remove things from your list after you bought them

Still one single list

Page 25: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

CREATING AN ARRAY First declare the array name and then

supply comma separated values

var friends =[‘sue’, ‘bob’, ‘ann’, ‘joe’];

The brackets tell interpreter you are working with an array

Empty array:var enemies = [ ];

Page 26: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

ACCESSING ITEMS IN AN ARRAY Access an item in an array by typing the

variable name and an index Array indexes start at 0.

var friends =[‘sue’, ‘bob’, ‘ann’, ‘joe’];

First friend: friend[0]Second friend: friend[1]

alert(friends[2]); // this would display “ann”

Page 27: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

ADDING ITEMS TO AN ARRAYvar colors = [ ‘red’, ‘blue’]

Adding at the end: colors.push(‘pink’); Array would contain: red, blue, pink

Adding at the beginning: colors.unshift(‘green’); Array would contain: green, red, blue, pink

Number of items in an array var num = color.length // this would set num

to 4

Page 28: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

REMOVING ITEMS FROM AN ARRAYvar colors = [ ‘red’, ‘blue’, ‘purple’]

Removing at the end:colors.pop( );Array would contain: red, blue

Removing from the beginning:colors.shift( );Array would contain: blue

Number of items in an arrayvar num = color.length // this would set

num to 4

Page 29: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

JAVASCRIPT AND OBJECTS JavaScript is filled with Objects,

examples:Browser windowDocumentStringDate

Object property:The parts of an objectUse dot notation to access e.g.

document.url Object method:

Actions an object can performMethods end with () e.g. document.write()

Page 30: The Grammar of JavaScript.  Each line of a script is a statement  An instruction that JavaScript can evaluate (make sense of)  Ends with a semicolon;

OBJECT INSTANCES Can create multiple instances of an

object Each instance has its own set of

properties and methods Example, create 2 instances of a String

object:var dog = ‘spot’;var cat = ‘morris’;

Example, whenever you create a variable you are creating a new objectvar size = 10; //new number objectvar answer = false; //new Boolean object