Presentation is loading. Please wait.

Presentation is loading. Please wait.

T. Jumana Abu Shmais – AOU - Riyadh

Similar presentations


Presentation on theme: "T. Jumana Abu Shmais – AOU - Riyadh"— Presentation transcript:

1 T. Jumana Abu Shmais – AOU - Riyadh
Agenda Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh

2 Introduction JavaScript, as its name suggests, is a scripting language. This means that programs written in JavaScript cannot be run on their own, but have to be run within some application, such as a web browser. JavaScript is an interpreted language. Browsers have embedded JavaScript interpreters. JavaScript was designed to add interactivity to HTML pages. JavaScript is usually embedded directly into HTML pages.

3 A Simple Program <HTML> <HEAD>
<TITLE> Activity_7.2.2 First Program </TITLE> <SCRIPT LANGUAGE = "JavaScript"> document.write('Welcome to programming!') </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Everything between <script> and </script> is written in a scripting language. The LANGUAGE attribute defines the scripting language. JavaScript is the default language, so that if no specific language is specified, HTML will assume that the code is JavaScript.

4 A Simple Program document.write(‘Welcome to programming!’) :
document.write() is a standard JavaScript command for writing output to a page. document is an object that can be thought of as the current HTML page. write() is a method associated with the document object, which enables JavaScript to add text to the page. The ‘dot notation’ (in document.write()) tells the document to execute the code of its write() method. The parenthesis () enclose the argument of the method. It provides information that the method needs to do its job, which, in this case, is the text to be displayed. The text (string) must be enclosed in quotation marks (either double or single quotes).

5 JavaScript Variables A variable is a named location in the computer’s memory where a value is stored. The name of a variable is called its identifier. The value of a variable can change as the program executes. Declaring variables: var myVar; The keyword var is used to declare a variable. myVar doesn’t yet have a value. A group of variables can be declared in one statement var var1, var2, var3;

6 JavaScript Variables Assigning values to variables:
The assignment operator = is used to assign a value to a variable (myVar): myVar = 5; 5=myVar is invalid. You can assign values to the variables when you declare them: var carName=‘Volvo’; If you assign values to variables that have not yet been declared, the variables will automatically be declared. E.g. carName="Volvo"; has the same effect as: var carName=“Volvo”; Assiging a value for the first time is called initialization.

7 Naming Variables Because JavaScript is case-sensitive, variable names are case-sensitive. Variable names must begin with a letter, the underscore _ character or the $ character. Subsequent characters may include digits. Don’t use a reserved word which is already a part of JavaScript’s vocabulary (such as var, if, for, while…etc.) while naming variables. Avoid very short identifiers such as a, b, x, ch.., because they are not very informative. Choose meaningful names that give some indication of the role played by the variable. Start your identifiers with lower-case letters. When an identifier is composed of more than one word, use single upper-case letter to mark the start of each word. E.g. myFamilyName.

8 Data Types and Operators
Number type: 3, 3.25, -2.27, -6 String type: ‘hello’ or “hello”, ‘’ Operators on numbers: Assignment operator = (myVar = 7) Addition operator + Subtraction operator – Multiplication operator * Division operator / Operators on strings: The symbol + is also used as a string operator to append the second string to the first string. Here + is called a concatenation operator. E.g. ‘Hello’ + ‘World’ will give ‘HelloWorld’ If you add a number and a string the result will be a string 5 + 5 =10 “5”+ 5 =“55” “5”+”5”=“55”

9 Operators Precedence Operators in order of decreasing precedence Order
Associativity 1 () Left to right 2 * / 3 + - 4 = Right to left Example: num= (2 * (3 + (6 / (1 + 2)) –1)) num= (2 * (3 + (6 / 3) –1)) num= (2 * (3 + 2 – 1)) num= (2 * (5-1) ) num= (2 * 4) num= 8 And finally the value 8 is assigned to num

10 Getting data from the user: the Prompt box
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns an empty string or the the default response string. Syntax: window.prompt(“instructions","defaultvalue"); Example: var name; name = window.prompt(‘Enter your name’,’’); “window” refers to the browser’s window in which document is displayed. The method prompt() is associated with the window object, this will cause the prompt box to appear on the top of the window.

11 Getting numbers as input
All inputs from keyboard are assumed to be strings. num1 = window.prompt('Enter your first number',''); num2 = window.prompt('Enter your second number',''); sum = num1 + num2; document.write('The sum of'+num1+' and '+num2+' is '+sum) If the user entered the two numbers 32 and 45, the output will be 3245 Instead of the sum (77). + operator works as concatenation not addition. The solution is to use a function called parseFloat(). (A function is similar to a method but is not associated with an object) parseFloat() takes a string and returns the number corresponding to its numeric part (num1 = parseFloat(num1); ) parseFloat(‘3’) returns 3 parseFloat(’10.25’) returns 10.25 parseFloat(‘string’) returns NaN (Not a Number) Use parseFloat() only when you need to do calculations to numbers.

12 Programming for selection
Selection needs conditions (Boolean expressions). To write conditions in JavaScript, you should use comparison operators. Comparison operators act on two values (binary operators) of same type and return a Boolean value (true/false). Compound Conditions: NOT, OR & AND can also be used in JavaScript ! means NOT || means OR && means AND E.g. Either ( x > 3) or (x <= 1)  ((x > 3) || (x <= 1)) Both (x > 3) and (x <= 5)  ((x > 3 ) && (x <= 5)) It is not true that (x > 10)  ! (x > 10) Examples (3 < 3) false (2 <= 5) true (2 > 3) (3 >= 3) (2 == 3) (2 != 2)

13 Programming for selection (the if statement)
The if statement asks the computer to do something when a condition is true. if (Boolean Expression) { statement(s) } Execute the statements before the if statement Evaluate the Boolean expression false true Execute the statement(s) in braces Ignore the statement(s) in braces Carry on with the rest of the program

14 Programming for selection (the if…else statement)
The if..else statement asks the computer to do one thing if a condition is true and something else if the condition is false. Syntax of if..else statement: if (Boolean Expression) { statement(s) } else Nesting: if (Boolean Expression) { statement(s) } else if (Boolean Expression 2)

15 Using comments Adding comments to the program increase its readability. There are two symbols for comments: // tells the JS to ignore anything on the remainder of that line. The pair of symbols /* and */ tells JS to ignore anything between them. Example: //This is an example of a single-line comment Var myVar; /* This is an example Of a multi-line Comment */

16 Programming for Repetition (the while statement)
Loops allow the computer to do repeat calculations or instructions. The while statement creates a loop that repeats until the test expression becomes false. The syntax of the while statement is: while (Boolean expression) { one or more statements } Example: var myVar; myVar=window.prompt('Enter a positive number',''); while(myVar <= 0) myVar=window.prompt('Enter a POSITIVE number','') document.write('The Positive number is ' + myVar)

17 Programming for Repetition (the while statement)
charAt( ) is a method associated with string objects and it returns the character at a particular location in the string (called index). Strings are indexed from left to right and starting from 0. Activity 7.4.8 /* Program to find the position of the first occurrence of e in a string input by the user */ var myWord, index; myWord = window.prompt('Please enter a word which has an e in it', ''); index = 0; while (myWord.charAt(index) != 'e') { index = index + 1 }; document.write('The first occurrence of letter e is in position ' + (index + 1) + ' in ' + myWord)

18 Programming for Repetition (the for statement)
The for loop enables you to repeat the execution of a block of statements a predetermined number of times. The for loop uses a variable as a counter. To use a JS for loop, you need to know: the starting value of the counter; the final value of the counter for which the loop body is executed; the fixed number by which the counter is increased or decreased after each repetition; The general form of the for loop is: for (declare and initialize; test; update) { statement(s) } The for statement uses three control expressions, separated by semicolons.

19 Programming for Repetition (the while statement)
How a for loop is executed: for (var count = 0; count < 5; count = count + 1) { statement(s)… } First, the initialization expression is executed once, before any of the loop statements are executed. Then, the test expression is evaluated and if it is true, the loop is cycled through once. Then, the update expression is evaluated. The test expression is checked again. The statement part of the form can be a simple statement or a compound statement.

20 Programming for Repetition (the for statement)
A string object has a property called length which holds the number of characters in it. Properties are accessed using the dot notation. Activity : /* Program to count the number of occurrences of the letter e in a word */ var word, total; word = window.prompt('Please enter a word',''); total = 0; for (var count = 0; count < word.length; count = count + 1) { if (word.charAt(count) == 'e') total = total + 1 } }; document.write ('The number of occurrences of e in the word ' + word + ' is ' + total)

21 Programming for Repetition
Which Loop to use? While and for do the same function, that means, what you can do with one, you can do with the other. If you know in advance how many repetitions will be needed, you will probably use a for loop. If you don’t know, you will need to use a while loop.


Download ppt "T. Jumana Abu Shmais – AOU - Riyadh"

Similar presentations


Ads by Google