Top Banner
Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within a program. JavaScript has primitive data types and composite data types.
33

Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Jan 12, 2016

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Data types, Literals (constants) and Variables

Data types specify what kind of data, such as numbers and characters, can be stored

and manipulated within a program.

JavaScript has primitive data types and composite data types.

Page 2: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Primitive Data Types• Numeric

• String

• Boolean

Special types

• Null

• UndefinedComposite Data Types (discussed later in the course)

• Objects

• Arrays

• Functions

Page 3: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Numeric Literals• Integers – numbers that do not contain a

decimal point. Can be expressed in decimal (10), octal(8) and hexadecimal(16) and are either positive or negative values (-39; +14).

• Floating Point – fractional numbers. They must contain a decimal point or an exponent specifier. The letter ‘e’ for the exponent can be either lowercase or uppercase (1.2e-3; 4.5E+6)

Page 4: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

String Literals

• String literals are rows of characters enclosed in either double or single quotes. The quotes must be matched.

• Strings are called constants or literals.

• Escape sequences: mechanism for quoting a single character: \n (new line); \r (return); \f (form feed); \b (backspace); \t (tab); \uXXXX (Unicode character specified by the four hex digits XXXX.

Page 5: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Example<html>

<head></head>

<body><pre><font size="+2"><script language="JavaScript"><!-- Hide script from old browsers.

document.write("\t\tHello\nworld!\n");document.writeln("\"Nice day, Mate.\"\n");

document.writeln('Smiley face:<font size="+3"> \u263A\n'); document.writeln('Copyright: \u00A9\n');//End hiding here. --></script></pre></body>

</html>

Page 6: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

String Concatenation

• The operator is a plus (+) signal. The operands are two strings.

• If on operand is a number and the other is a string, JavaScript will still concatenate them as strings. If both operands are numbers, then the (+) will be the addition operator:

• “5” + 10 = 510

• 5 + 10 = 15

• This is one of the most common source of errors.

Page 7: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Boolean Literals

• Have only one of two values: true or false (yes or no; on or off; 1 or 0).

• Used to test if a condition is true or false.

• TRUE evaluates to 1

• FALSE evaluates to 0

Page 8: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Null and undefined

• Null keyword represents no value, nothing, not even an empty string or zero. It is a type of JavaScript object. When a variable is assigned null, it does not contain any valid data type.

• A variable that has been declared but given no initial value, contains the value undefined and will produce a runtime error if you try to use it.

Page 9: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

The “typeof” operator

• Returns a string to identify the type of its operand.

• If there is no value associated with the variable, the typeof operator returns undefined.

• Format: typeof (operand)

Page 10: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Example<html>

<head><title>The typeof Operator</title><script language="JavaScript"><!-- Hide script from old browsers. document.write("<em>55</em> is type " + typeof(55), "<br>"); document.write('<em>"hello there"</em> is type ' + typeof("hello

there"), "<br>"); document.write("<em>true</em> is type " + typeof(true), "<br>"); document.write("<em>null</em> is type "+typeof(null), "<br>"); document.write("<em>undefined</em> is type "+typeof(undefined),

"<br>"); //End hiding here. --></script></head>

</html>

Page 11: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Variables• Variables are data items that represent a

memory storage location in the computer.• Variables hold data such as numbers and

strings.• Variables have a “name”, a “type” and a “value”.• The values assigned to variables may change

throughout the run of a program whereas constants (literals) remain fixed.

• JavaScript variables can be assigned numeric, string, and Boolean data.

• In JavaScript you do not have to specify the data type of a variable. Doing so will produce an error. When you assign a value to a variable, JavaScript will figure out what type of data is being stored in the variable.

Page 12: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Valid names to variables

• Variable names consists of any number of letters and digits.

• First character must be a letter or an underscore. As reserved keywords do not contain underscores, if you use one, you are safe of inadvertently use a reserved keyword.

• Variable names are case sensitive.• JavaScript does not allow you to use a number

as the first character in an identifier, so that it can easily distinguish between an identifier and a literal value.

Page 13: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Declaring and Initializing Variables• Variables must be declared before they can be used.

Usually you declare them in the <head> of the HTML document.

• You can use the keyword “var”. It is good practice to use it, but it is not mandatory.

Examples:var first_name = “Roberto”;first_name = “Roberto”;var first_name;• You can declare multiple variables on the same line by

separating each one with a comma:var first_name, var middle_name, var last_name;• When you declare a variable without assigning it a value,

you must use “var”, and the variable will initially contain the value undefined.

Page 14: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Example of error<html>

<head><title>Using the var Keyword</title> <script language="JavaScript"> var language="English"; var name; age; document.write("Name is "+ name); </script></head>

<body></body>

</html>

Page 15: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Dynamically or Loosely Typed Language

• JavaScript interpreter will always convert the data to the correct type:

Variable Assignment Conversion

var item = 1.2; Assigned a float

item = 3; Converted to integer

item = “Today is Tuesday”;

Converted to string

item = true; Converted to Boolean

item = null; Converted to null

Page 16: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Example<html>

<head><title>JavaScript Variables</title><script language="JavaScript">var first_name="Christian"; // first_name is assigned a stringvar last_name="Dobbins"; // last_name is assigned a stringvar age = 8; // age is assigned an integervar ssn; // Unassigned variablevar job_title=null; // job_title is assigned null</script></head>

<body bgcolor="lightblue"><font="+1"><script>document.write("<b>Name:</b> " + first_name + " " + last_name + "<br>");document.write("<b>Age:</b> " + age + "<br>");document.write("<b>Ssn:</b> " + ssn + "<br>");document.write("<b>Job Title:</b> " + job_title + "<br>");ssn="xxx-xx-xxxx";document.write("<b>Now Ssn is:</b> " + ssn , "<br>"); </script><body><p><img src="Christian.gif"></body>

</html>

Page 17: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Scopes of Variables

Scope describes where a variable is visible, or where it can be used within the program.

• A global variable can be accessed from any JavaScrip script on a page.

• A local (private) variable is created when a variable is declared within a function. They must be declared with the keyword var. They are accessible only from within the function from the time of declaration to the end of the enclosing block. They take precedence over any global variable with the same name.

Page 18: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Concatenation and Variables<html>

<head><title>Concatenation</title><script language="JavaScript">var x = 25;var y = 5 + "10 years"; document.write( x + " cats" , "<br>"); document.write( "almost " + 25, "<br>"); document.write( x + 4, "<br>"); document.write( y, "<br>"); document.write(x + 5 + " dogs"+ "<br>"); document.write(" dogs"+ x + 5, "<br>");</script> </head>

</html>

Page 19: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Dialog Boxes

• Dialog Boxes are used to interact with the user.

• Dialog boxes are created with three methods:

alert ()

prompt()

confirm()

Page 20: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

The alert() method

• Creates an independent box which contains a small triangle with an exclamation point. A user message is placed after the triangle, and beneath it, an OK button (IE).

• When this dialog box pups up, all execution is stopped until the user presses the OK button in the pop-up box.

• The message is a string of text enclosed in double quotes, and send as a single argument to the alert() method.

Page 21: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Creating first Window<html>

<body><script>

// this is used for commentsalert ("Hello World");

</script></body>

</html>

Page 22: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Example of alert() dialog box<html>

<head><title>Dialog Box</title></head>

<body bgcolor="yellow" text="blue"><b>Testing the alert method</b><br><script language="JavaScript"> document.write("<font size='+2'>"); document.write("Its a bird, "); document.write("Its a plane, <br>"); alert("Its Superman!");</script></body>

</html>

Page 23: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Using variables

• You can do a similar program like the Hello World using variables.

• <html>

• <head>• <title> Hello Mark </title>• </head>

• <body>• <h1> Hello, Michael</h1>

• <script>• var greetings;• greetings = "Hi there, Mirza";• alert (greetings);• </script>

• </body>

• </html>

Page 24: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Example<html>

<head><title>Using JavaScript alert box</title><script language="JavaScript">alert("Welcome to\nJavaScript Programming!");var message1="Match your Quotes and ";var message2="Beware of Little Bugs ";alert(message1 + message2);</script</head>

</html>

Page 25: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Doing Math

• <html>

• <head>• <title> Adder </title>• </head>

• <body>• <h1> The Adder</h1>

• <script>• var meal = 22.50;• var tip = meal * 0.15;• var total = meal + tip;• alert ("the meal is $" + meal);• alert ("the tip is $" + tip);• alert ("Total Bill: $" + total);

• </script>

• </body>

• </html>

Page 26: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Using Numeric Variables – the Bad Adder

• <script>• var meal;• meal = prompt ("How much was the meal?");• var tip = meal * 0.15;• var total = meal + tip;• alert ("the meal is $" + meal);• alert ("the tip is $" + tip);• alert ("Total Bill: $" + total);• </script>

Page 27: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

The Good Adder Application

• <script>• var meal;• meal = prompt ("How much was the meal?");• meal = eval(meal);• var tip = meal * 0.15;• var total = meal + tip;• alert ("the meal is $" + meal);• alert ("the tip is $" + tip);• alert ("Total Bill: $" + total);• </script>

Page 28: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

The prompt() method

• It accept user inputs.• It pops-up with a simple textfield box. After the

user enters text into the prompt dialog box, its value is returned.

• The prompt dialog box takes two arguments: a string of text that is normally displayed as a question to the user, prompting him to do something, and another string of text which is the initial default setting for the box.

Page 29: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

prompt() method example<html><head><title>Using the JavaScript prompt box</title></head><body><script language = "JavaScript">

var name=prompt("What is your name?", "");document.write("<br>Welcome to my world! "+ name +

".</font><br>");var age=prompt("Tell me your age.", "Age");if ( age == null){ // if user presses the cancel button

alert("Not sharing your age with me"); } else{ alert(age + " is young"); }alert(prompt("Where do you live? ", ""));</script><body></html>

Page 30: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

String Methods

• stringVar.toUpperCase() -> converts stringVar to all uppercase letters.

• stringVar.length -> return the number of characters in the stringVar variable.

Page 31: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

Name Game

• <script>• var firstName = "";• var lastName = "";• var numLetters = 0;

• firstName = prompt ("Hi, What's your first name?");• alert ("That's a nice name, " + firstName);• alert ("I think I'll shout it: " + firstName.toUpperCase());• lastName = prompt ("So, what's your last name, " + firstName + "?");• alert ("Oh." + firstName + " " + lastName + ".");• alert ("Sometimes called " + lastName + "," + firstName);• numLetters = firstName.length + lastName.length;• alert ("Did you know there are " + numLetters + " letters in your

name?");

• </script>

Page 32: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

The confirm() method

• The confirm dialog box is used to confirm a user’s answer to a question.

• A question mark will appear in the box with an OK button and a Cancel button. Pressing OK, TRUE is returned. Pressing Cancel, FALSE is returned. This method takes only one argument, the question you will ask the user.

Page 33: Data types, Literals (constants) and Variables Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within.

confirm() method example

<html>

<head><title>Using the JavaScript confirm box</title></head>

<body><script language = "JavaScript">document.clear // Clears the pageif(confirm("Are you really OK?") == true){

alert("Then we can proceed!"); } else{ alert("We'll try when you feel better? "); }</script></body>

</html>