Você está na página 1de 35

Values, Types, and Variables

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Objectives
Learn about JavaScript types and comparisons Understand both implicit and explicit type conversions See how to declare and use variables, as well as their scope

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Introduction to Values, Types, and Variables


Handling data is the fundamental task of programming languages
Values Types Variables

JavaScript may seem limited and confining


Weakly typed language, so variables are untyped Object-oriented language

Type system is definitely one of the good parts of the language


Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

JavaScript Types
Defines types you can use to work with values of different kinds Categorizing types
Primitive and object types With or without methods Mutable or immutable

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Primary Types in JavaScript


Type number string Boolean null undefined object Category Primitive Primitive Primitive Primitive Primitive Object Methods Yes Yes Yes No No Yes Mutability Immutable Immutable Immutable Immutable Immutable Mutable

Bad part is that it will liberally convert values from one type to another Special === operator
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

JavaScript Numbers
All numbers are 64-bit floating-point values
IEEE 754 standard Numbers as large as 1.7976931348623157x10308 to as small as 5x10-324 Integers between -9,007,199,254,740,992 (-253) and 9,007,199,254,740,992 (253), inclusive If you work with numbers outside integer range, youll lose precision

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Integer Literals
Represent either as base 10 or hexadecimal All these are valid base 10 values
5, 100, 123456789, 0, -100

Valid hex values


0x1a5f, 0X1A5F, 0x10cd4

ECMAScript doesnt support octal (base 8)


Some JavaScript implementations support Number starts with a leading zero, followed by digits from 0 to 7 Code wont be portable ECMAScript 5/Strict forbids

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Real Number Literals


Express either as real number or exponential Real numbers
1.0, 1.349201942, .3333333333, 125959403.39201488, 56. Omit either integral or fractional part

Exponential numbers
1.23e12 // 1.23 x 1012 1.23e-12 // 1.23 x 10-12 5.90849203e5 // 5.90849203 x 105

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Arithmetic in JavaScript
Expected set of arithmetic operators
Including + (addition), - (subtraction), * (multiplication), / (division), and % (modulo) No integral division

Math object for other operations

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

JavaScript Strings
Ordered, immutable sequence of 16-bit Unicode characters
From zero to as many as will fit in memory Consist of letters, numbers, punctuation, and spaces Zero-based indexing Empty string () has length of zero No special type to represent a single character

Delimit with single ' or double " quotes


Cant mix to delimit string Can embed quote not used to delimit string
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

String Delimiters
Either string is valid
"'Don't use that food to feed she said. 'It's been recalled manufacturer.'" '"Don"t use that food to feed she said. "It"s been recalled manufacturer."' the dog,' by the the dog," by the

Not valid
'"Don't use that food to feed the dog," she said. "It has been recalled by the manufacturer."'
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

String Literals
All the following are valid string literals
"" '' "Don Kiely" '1.414' // an empty string // another empty string

// a number represented as a string "My password is 'beetle$%^Bailey392'"

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Line Breaks in String Literals


ECMAScript 3 requires string literal on one line
ECMAScript 5 allows break with \ at end of line

Problem in ECMAScript 3 but fine in 5:


"Four score and seven years ago our fathers \ brought forth on this continent, a new nation, \ conceived in Liberty, and dedicated to the \ proposition that all men are created equal." "Four score and seven years ago our fathers \ brought forth on this continent, a new nation, \ conceived in Liberty, and dedicated to the \ proposition that all men are created equal."
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Following is invalidsee the difference?

Escape Sequences in String Literals


Include characters that have special meaning by using an escape sequence
Backslash \ identifies the special character '"Don\'t use that food to feed the dog," she said. "It\'s been recalled by the manufacturer."

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

JavaScript Escape Sequences


Escape Sequence \' Description Single quote or apostrophe

\"
\\ \0 \b \f \n

Double quote
Backslash Nul character (thats a backslash-zero) Backspace Form feed Newline

\r
\t \v \xXX \uXXXX

Carriage return
Horizontal tab Vertical tab The Latin-1 character specified by the two hexadecimal digits XX between 00 and ff. For example, the copyright symbol is \xa9. Learn More @ http://www.learnnowonline.com The Unicode character specified by the four Copyright by Application Developers Training Company hexadecimal digits dddd. For example, the symbol is

JavaScript Boolean Values


Represents true or false
Usually the result of some logical comparison

JavaScript can convert any value to a Boolean


These are all false
o o o o o o

0 (zero) -0 (negative zero) "" (empty string) NaN null undefined

All other values are true


Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Truthy and Falsy


Any value that converts to true is truthy Any value that converts to false is falsy When JavaScript expects a Boolean value
Truthy value works like true Falsy value works like false

These are generally equivalent


if (result !== 0) if (result)

But be careful!
The result variable could hold other truthy or falsy values

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Boolean Methods and Logical Operators


Boolean values have two methods
toString() returns "true" or "false" valueOf() returns true of false

Logical operators
&& AND || OR ! NOT

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Special Values: null and undefined


null
Language keyword An object, but considered a separate type Absence of a value

undefined
Also means absence of value, but in a deeper way Predefined global variable Type is undefined (literally, thats its type)

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

undefined
JavaScript uses in a few different ways
Variable that has been declared but not yet assigned a value Function parameter that the calling code doesnt provide a value for Property that doesnt exist on an object Array element that doesnt exist Function that doesnt return a value

undefined is read/write in ECMAScript 3, readonly in ECMAScript 5


Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Use null or undefined?


Both mean absence of value
Can often use interchangeably In fact, null == undefined But null !== undefined

Best advice
Use undefined to represent system-level, unexpected, or erroneous absence of value Use null to represent a program-level normal, or expected absence of value

In other words, use null when you need to express missing value
Let JavaScript manage use of undefined
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Type Comparisons
JavaScript compares primitive values and object values differently
Primitive values by value Object values by reference

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Object Comparisons
JavaScript compares objects by reference
Equal only if the two variables hold a reference to the same object in memory If hold a reference to two different objects, even if objects are the exact same, they are not equal

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Type Conversions
Feature that makes JavaScript easy and hard
Does everything it can to implicitly convert values to make useable in a statement Doesnt always do what you want

Automatic type conversions


Convert to truthy or falsy when expects Boolean Converts anything to a string when expects string Tries to convert to a number when expects number

Also supports explicit type conversions


Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Explicit Type Conversions


You can do it yourself explicitly
Use when implicit conversions dont work for you Or you want cleaner and clearer code

Various ways
Wrapper objects Type methods Global functions among others

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Formatting Methods and Parsing Functions


Dont have much control with other conversion techniques
Get a reasonable value in the type you want

JavaScript has specialized methods and functions that give you control

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Conversions Using Wrapper Objects


Number, String, Boolean, and Object wrapper objects
Provide properties and methods for corresponding types Creates a String object and uses length property

"AppDev".length

Can use these functions for explicit conversion

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Number Formatting Methods


Give more control than toString()
toFixed() toPrecision() toExponential()

All three round number or pad with zeros as necessary

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Using Variables
Way to temporarily store bits of data Necessity in almost every language JavaScript variables are a bit different

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Variable Declaration
Not required, but you should do it Untyped, so simple: use var with identifier
var count; var minMsgID; var lastName;

Undefined until initialized Can declare and initialize in one statement


var count = 0; var minMsgID = 32629; var lastName = "Kiely";
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Variable Declaration
Multiple variables in single var statement
var count = 0, minMsgID = 32629, lastName = "Kiely";

Break onto multiple lines


var count = 0, minMsgID = 32629, lastName = "Kiely";

Declare and initialize within loops


for (var i = 2; i <= 36; i++) console.log("Base " + i + ": " + num.toString(i));

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Variable Cautions and Gotchas


Variable can hold any type during execution
var count = 0; <program code> count = "Don"; <more program code> count = false <yet more code> count = "The Duke of Windsor";

Be careful splitting across multiple lines!


var count = 0 minMsgID = 32629, lastName = "Kiely";
Learn More @ http://www.learnnowonline.com
Copyright by Application Developers Training Company

Variable Scope
Scope is section of code where variable is defined and accessible Two scopes in JavaScript
Global Local

Local variable has function scope in JavaScript

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Variable Hoisting
Function scope has an important implication All local variables declared within a function
Visible throughout the body of the function

Side effect: all local variables are visible even before they are declared

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Learn More!
This is an excerpt from a larger course. Visit www.learnnowonline.com for the full details! Learn more about JavaScript on SlideShare!
Introduction to JavaScript

Learn More @ http://www.learnnowonline.com


Copyright by Application Developers Training Company

Você também pode gostar