Concatenation Comments

Slides:



Advertisements
Similar presentations
Modifying existing content Adding/Removing content on a page using jQuery.
Advertisements

1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Escaping Characters document.write(). Learning Objectives By the end of this lecture, you should be able to: – Recognize some of the characters that can.
Introduction to scripting
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
Using the API. Learning Objectives By the end of this lecture, you should be able to: – Identify what is meant by an ‘API’ – Know how to look up functions.
Chapter 4 JavaScript and Dynamic Web pages. Objectives Static Web pages Dynamic Web pages JavaScript Variables Assignments. JavaScript Functions –(prompt(“”,””)
Introduction.  The scripting language most often used for client-side web development.  Influenced by many programming languages, easier for nonprogrammers.
Working with Files. Learning Objectives By the end of this lecture, you should be able to: – Examine a file that contains code with unfamiliar material,
Return values Efficiency in Coding. Learning Objectives By the end of this lecture, you should be able to: – Be able to apply an ‘object literal’ when.
Dr. Qusai Abuein1 Internet & WWW How to program Chap.(6) JavaScript:Introduction to Scripting.
JavaScript Programming Unit #1: Introduction. What is Programming?
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
Sahar Mosleh California State University San MarcosPage 1 JavaScript Basic.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Working with Strings. Learning Objectives By the end of this lecture, you should be able to: – Appreciate the need to search for and extract information.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
Introduction to Arrays. Learning Objectives By the end of this lecture, you should be able to: – Understand what an array is – Know how to create an array.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
JavaScript: Conditionals contd.
Getting Started With HTML
JavaScript Controlling the flow of your programs with ‘if’ statements
Precedence Operators Error Types
Module 1 Introduction to JavaScript
Moving away from alert() Using innerHTML Using an empty div section
Topic: Python’s building blocks -> Variables, Values, and Types
Chapter 6 JavaScript: Introduction to Scripting
Predefined Functions Using the JavaScript Documentation
Checkboxes, Select boxes, Radio buttons,
Data Types Variables are used in programs to store items of data e.g a name, a high score, an exam mark. The data stored in a variable is entered from.
Essential Tags Web Design – Sec 3-3
JavaScript Wrap-up.
Chapter 13 - JavaScript/JScript: Introduction to Scripting
Variables, Expressions, and IO
Introduction to Scripting
Retrieving information from forms
JavaScript Part 2 Organizing JavaScript Code into Functions
Intro to PHP & Variables
Introduction to JavaScript
Data Types Parsing Data
Phil Tayco Slide version 1.0 Created Oct 2, 2017
Exercises on JavaScript & Revision
Number and String Operations
JavaScript – Part I Mendelsohn.
INFO/CSE 100, Spring 2005 Fluency in Information Technology
INFO/CSE 100, Spring 2006 Fluency in Information Technology
JavaScript Variables.
Introduction to JavaScript
Tutorial 10: Programming with javascript
Introducing JavaScript
JavaScript: Introduction to Scripting
Working with Strings.
JavaScript Variables.
Random Stuff Colors Sizes CSS Shortcuts.
Using the API.
Working with Numbers parseInt() and parseFloat() Math.round()
A Few Notes on JavaScript
JavaScript Part 2 Organizing JavaScript Code into Functions
Retrieving information from forms
Checkboxes, Select boxes, Radio buttons
Data Types Parsing Data
Introduction to scripting
JavaScript Variables.
Adios alert() Using innerHTML Using an empty section
Concatenation of Strings JavaScript Comments
Standard Normal Table Area Under the Curve
Presentation transcript:

Concatenation Comments JavaScript Concatenation Comments

Learning Objectives By the end of this lecture, you should be able to: Concatenation: Describe the two different operations carried out by the ‘+’ operator. Describe the circumstances under which the operator does addition, and when it does concatenation. Join variables, literal text, and even numbers into a single string using concatenation. Comments: Be comfortable inserting comments in your code. Demonstrate how comments can be used to temporarily remove code for debugging and testing purposes.

Reminder: Only move on from a concept after you can apply the concept in your code with few if any peeks at the notes.

The lowly ‘+’ operator We are all familiar with this operator… we use it for addition all the time. alert(5+2);  outputs 7 alert(5+5);  outputs 10 However, this '+' operator is unusual in that it has two different uses. In addition to ‘adding’, the + operator, if used with strings, can “concatenate” (join) those strings together. alert("H" + "e" + "l" + "l" + "o" + "."); ouputs: Hello. alert("Hello, " + "How are you?");  outputs: Hello, How are you? alert("5" + "5");  what do you think??

Can’t we all just get along? Consider: alert("5" + "5");  two strings, so concatenation: outputs 55 alert(5+5);  two integers, so addition: outputs 10 What if there is a disagreement? alert("5" + 5); Notice that we have a string and a number. So… which version of the ‘+’ operator will the JS interpreter use? Answer: The way the ‘+’ operator works, is that a string always “wins”. That is, if there is a string on EITHER side of the ‘+’ operator, you will get concatenation. Therefore, in this example, because there is a string on the left side, and a number on the right side, the presence of the string “wins out”, and thus, the operator will concatenate as opposed to add. So in this case, the output of: alert("5" + 5); will be 55

Form values are retrieved as strings The following is a very very important point: Any time you retrieve a value from a form, that value comes back as a string. Even if the value looks exactly like a number, that "number" will, in fact, be treated as a string. Concept check: Can you predict what will be output by the alert box here? var age; age = document.getElementById('txtAge').value; //Let's suppose that the user entered 25 for their age alert(age+age); The output will be 2525 Because ‘age’ is holding a string (as opposed to a number), the ‘+’ operator will do concatenation as opposed to addition. This type of thing comes up a lot! Therefore, we will shortly learn how to fix this situation. Be absolutely certain that you understand this problem. It will be vital in upcoming assignments, and I can guarantee at least a few exam questions that will require an understanding of this concept!

Outputting variable values to a web page Concatenation becomes extremely useful when we want to output the value of different strings and variables together. Recall an earlier example where we had something like: alert(firstName); alert(lastName); alert(favColor); Now compare it with: alert(firstName + " " + lastName + " " + favColor); By concatenating the five strings together, this line of code will output all three variables in only one alert box, with a space between them.

Concatenation example Study this example to ensure that you understand it. var firstName, lastName, age; firstName = document.getElementById('txtFirstName').value; lastName = document.getElementById('txtLastName').value; age = document. getElementById('txtAge').value; alert("Dear " + firstName + " " + lastName + "."); alert("You are " + age + " years old."); As always, be sure to type out the example yourself and to experiment with it. Incidentally, note how I typed a space before and after certain strings in our alert statements. If I neglected those spaces, I hope you can see that the words would all be scrunched up against each other. Next, experiment by placing the entire string in just one alert() window instead of two.

File: concat_ex1.htm <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Practice Makes Perfect</title> <script type="text/javascript"> function testConcatenation() { var firstName, lastName, age; firstName = document.getElementById('txtFirstName').value; lastName = document.getElementById('txtLastName').value; age = document.getElementById('txtAge').value; alert( "Hello " + firstName + " " + lastName + "! " + "You are " + age + " years old."); } </script> </head> <body> <h1>It Takes Practice...</h1> <hr> <form id="formName"> <p>First Name: <input type="text" id="txtFirstName" ></p> <p>Last Name: <input type="text" id="txtLastName" ></p> <p></p> <p>Age: <input type="text" id="txtAge" ></p> <p></p> <p><input type="button" value="Submit" onclick="testConcatenation()"> </p> </form> </body> </html>

Concatenation example var firstName = "Wofgang"; var middleName = "Amadaeus"; var lastName = "Mozart"; var fullName; fullName = lastName + ", " + firstName + " " + middleName + "!"; alert(fullName); In this case, I concatenated the variables firstName, middleName, and lastName, and placed the resulting longer string inside the variable fullName. In this example, I hope you can see that our alert box would output the string: Mozart, Wolfgang Amadeus!

New Topic: “Comments” In a couple of previous JavaScript examples, have you noticed any lines that began with the characters // ? In JavaScript -- in fact, in all languages -- there is a way to type information inside your program without that text being parsed/executed by the interpreter. We call this non-interpreted text "comments". You have already seen HTML comments earlier in the course. Recall that we can comment text in HTML by placing that text between <!-- and --> In JavaScript, we type comments by putting // characters at the beginning of any line of text we wish to have ignored. Beginning ith those // characters, all remaining text until the end of the line will be ignored by the interpreter. If you have multiple lines you wish to “comment out”, then you must put the // characters before each and every one of those lines.

Why we comment – part 1 alert("Hello " + "How are you?"); //greets the user alert( Today is: + Date()); //prints the date In this example, only the 1st and 3rd lines will be interpreted. The 2nd and 4th lines will be not be executed by the JavaScript interpreter. Those lines will be ignored because they were “commented out”. Commenting is very frequently used in programming as a means of writing explaining what your code is doing. Over time, you will see that code can become very confusing to look at and interpret. For this reason, writing in some comments can make life much, much easier for other programmers who may look at your code down the road. In the example above, the comments are not really needed since the code is very simple. However, you will come to see that, sometimes, code that makes "perfect sense" when you are writing it, can, in fact, be very confusing when you look at it out of context at a later point in time.

Why we comment – part 2 Perhaps an even more common use for comments is as a debugging tool! var number, name, age; age = document.getElementById('txtAge').value; name = document.getElementById('txtName').value; number = Math.Sqrt(33); alert(name); alert(age); alert(number); Let’s say that I suspect my page is failing to work properly due to an error in the line that is calculating the square root. The easiest way to debug, is to temporarily remove this line (along with its corresponding alert statement). However, in addition to being time-consuming, there is the real risk that I will forget to copy these lines elsewhere such as to the clipboard and will forget about it or copy over it. One VERY convenient tool, therefore, is to simply comment out the line(s) of code that I think may be causing the problem. I can then reload the file in my browser, and if the file now works, I have at least isolated the approximate location of the bug!

The ‘suspicious’ lines commented out: var number, name, age; age = document.getElementById('txtAge').value; name = document.getElementById('txtName').value; //number = Math.Sqrt(33); alert(name); alert(age); //alert(number); Because I suspect that the error is in the square root line somewhere, I commented it out. (I also had to comment out the related alert statement). When I go back and reload my page, I see that things are working fine. As a result, I know that I did appear to have isolated the error. I can now focus in on that particular line in order to find the bug. Incidentally, can you spot the bug? Recall that JS is case-sensitive – the function is called sqrt NOT Sqrt!

File: debug_practice.htm <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Practice Makes Perfect</title> <script type="text/javascript"> function testComments() { var number, name, age; age = document.getElementById('txtAge').value; name = document.getElementById('txtName').value; number = Math.Sqrt(33); alert(name); alert(age); alert(number); } </script> </head> <body> <h1>It Takes Practice...</h1> <hr> <form id="formName"> <p>Name: <input type="text" id="txtName" ></p> <p></p> <p>Age: <input type="text" id="txtAge" ></p> <p></p> <p><input type="button" value="Submit" onclick="testComments()" ></p> </form> </body> </html> Try it! You’ll see that when you run this page, the entire script fails! This is because of the bug in the ‘sqrt’ line. Note that a SINGLE line of mistyped code can often cause the ENTIRE script to fail! Now ‘comment out’ the ‘sqrt’ line and see what happens…