JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Similar documents
JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Client-Side Web Technologies. JavaScript Part I

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications

Chapter 3: Operators, Expressions and Type Conversion

Operators and Expressions

Expr Language Reference

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

CGS 3066: Spring 2015 JavaScript Reference

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

The PCAT Programming Language Reference Manual

The SPL Programming Language Reference Manual

HTML5 and CSS3 More JavaScript Page 1

1 Lexical Considerations

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

MatchaScript: Language Reference Manual Programming Languages & Translators Spring 2017

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Lexical Considerations

CSC Web Programming. Introduction to JavaScript

JavaScript: Sort of a Big Deal,

Visual C# Instructor s Manual Table of Contents

3. Java - Language Constructs I

Introduction to Programming Using Java (98-388)

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

Ruby: Introduction, Basics

Ruby: Introduction, Basics

Lexical Considerations

Information Science 1

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

Chapter 2 Working with Data Types and Operators

Index COPYRIGHTED MATERIAL

Symbols. accessor properties, attributes, creating, adding properties, 8 anonymous functions, 20, 80

Java Primer 1: Types, Classes and Operators

JavaScript I Language Basics

Unit 3. Operators. School of Science and Technology INTRODUCTION

Full file at

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 17. Fundamental Concepts Expressed in JavaScript

ARG! Language Reference Manual

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Types and Expressions. Chapter 3

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Object Oriented Software Design

A Short Summary of Javali

Operators. Java operators are classified into three categories:

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Programming Lecture 3

Language Reference Manual simplicity

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

SPARK-PL: Introduction

Ch. 12: Operator Overloading

COMS 469: Interactive Media II

Ruby: Introduction, Basics

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Chapter 2: Using Data

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

4. Inputting data or messages to a function is called passing data to the function.

UNIT- 3 Introduction to C++

Typescript on LLVM Language Reference Manual

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

Language Features. 1. The primitive types int, double, and boolean are part of the AP

JavaScript Basics. The Big Picture

IC Language Specification

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

3. Java - Language Constructs I

CHAD Language Reference Manual

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Absolute C++ Walter Savitch

Chapter 2: Using Data

Full file at

CMPT 125: Lecture 3 Data and Expressions

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Information Science 1

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Decaf Language Reference

CSCE 120: Learning To Code

Chapter 02: Using Data

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Fundamental of Programming (C)

Basics of Java Programming

Sprite an animation manipulation language Language Reference Manual

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

FRAC: Language Reference Manual

The Decaf Language. 1 Lexical considerations

CPS122 Lecture: From Python to Java

Single-pass Static Semantic Check for Efficient Translation in YAPL

egrapher Language Reference Manual


Transcription:

Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 2 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

AGENDA 4. Type Values and Conversion 5. Variables 6. Operators and Expressions

Type Values and Conversion 4.

4.1 BOOLEAN VALUES 31 Boolean value represents truth or falsehood, on or off, yes or no Boolean values are generally the result of comparisons in JavaScript programs: If value is 4, the comparison is true Otherwise it is false Boolean values are commonly used in JavaScript control structures, such as If/else, etc. You combine a comparison expression directly with the statement, such as an If statement

4.1 BOOLEAN VALUES 32 Any JavaScript value can be converted to a Boolean value Following values evaluate to false or falsy: All other values, including all objects (and arrays) convert to, and work like, true (truthy) Boolean values have one method: tostring() true, false 3 important operators:

4.2 JAVASCRIPT SPECIAL VALUES 33 Null is a language keyword that evaluates to a special value that is usually used to indicate the absence of a value Undefined value (predefined global variable) represents a deeper kind of absence: Variables that have not been initialized Query an object property or array element that does not exist Function with no return value Despite these differences, null and undefined both indicate an absence of value and can often be used interchangeably:

4.2 JAVASCRIPT SPECIAL VALUES 34 General usage: Use undefined to represent a system-level, unexpected, or error-like absence of value Use null to represent program-level, normal, or expected absence of value

4.3 JAVASCRIPT GLOBAL OBJECT 35 Properties of global object are globally defined symbols available to a JavaScript program When JavaScript interpreter starts (i.e.web browser loads page), it creates a new global object and defines following properties: In top-level code (JavaScript not part of a function) use the JavaScript keyword this to refer to the global object In client-side JavaScript: Window object serves as the global object for all JavaScript code contained in the browser window it represents Global object holds predefined global values as well as program-defined global values, such as a global variable

4.4 JAVASCRIPT WRAPPER OBJECTS 36 JavaScript objects are composite values collection of properties or named values: Use. notation for value of property When value is a function, then property is a method To invoke the method m of an object o, we write o.m() Strings, numbers, and Booleans are not objects, so why do they have properties? JavaScript temporarily converts them into objects so that properties and methods can be used No wrapper objects for null and undefined

4.4 JAVASCRIPT WRAPPER OBJECTS 37 Strings, numbers, and Boolean values behave like objects when you try to read the value of a property (or method) from them But setting (= writing) a property value is silently ignored When reading properties temporary (wrapper) objects JavaScript converts wrapper objects into the wrapped primitive value as necessary objects S, N, and B usually behave just like the values s, n, and b Wrapper object == primitive value, to differentiate use strict equal operator (===) or typeof operator

4.5 TYPE CONVERSION 38 JavaScript is very flexible about the types of values it requires Truthy values convert to true, whereas falsy automatically convert to false Implicit conversion takes place!

4.5 TYPE CONVERSION 39

4.5 TYPE CONVERSION 40 Equality and Conversion Because JavaScript can convert values flexibly, its equality (==) operator is also flexible with its notion of equality All comparisons are true: == equality operator performs some conversion (covered later) === strict equality operator does not perform any conversion Convertibility of one value to another does not imply equality of those two values:

4.5 TYPE CONVERSION 41 Explicit Conversions In most cases, explicit conversion is desired cleaner code Easiest way to perform an explicit type conversion: Every value (except null/undefined) has a tostring() method Result of tostring() method is usually the same as that returned by the String() function Certain operators perform implicit type conversions sometimes used for the purposes of type conversion:

4.5 TYPE CONVERSION 42 Formatting/parsing numbers are common in computer programs: JavaScript has specialized functions and methods that provide more precise control over number-to-string and string-to-number conversions tostring() method defined by the Number class accepts an optional argument that specifies a radix (base) for the conversion (if left blank base 10) Number class defines 3 methods for number-to-string conversions: If a string value is passed to Number() function, it attempts to parse that string as an integer or floating-point literal (works only for base-10 integers)

4.5 TYPE CONVERSION 43 parseint() and parsefloat() global functions are more flexible:

4.5 TYPE CONVERSION 44 Object to Primitive Types Conversion Object conversions to other types are more complex: Object-to-Boolean conversions are trivial: all objects (including arrays and functions) convert to true Object-to-string and object-to-number conversions are performed by invoking a method of the object to be converted: Complicated due to the fact that JavaScript objects have two different methods that perform conversions Also complicated by some special cases described below All objects inherit two conversion methods: tostring() Method Returns a string representation of the object Many classes define more specific versions of the tostring() method: Array, Date, Function

4.5 TYPE CONVERSION 45 valueof() Method: Its job is less defined Supposed to convert an object to a primitive value that represents the object, if any such primitive value exists Arrays, functions, and regular expressions simply inherit the default method, which returns the object itself Date class defines a valueof() method that returns the date in its internal representation: Number of milliseconds since January 1, 1970

Variables 5.

5.1 VARIABLE DECLARATION 46 A variable is a named memory location Before using a variable in a JavaScript program, you should declare it You can declare multiple variables with one var: And you can combine variable declaration with initialization: When no initial value for a variable with the var statement is specified variable is declared, but its value is undefined until your code stores a value into it var statement also as part of the for and for/in loops:

5.1 VARIABLE DECLARATION 47 No type associated with JavaScript s variable declarations JavaScript variable can hold a value of any type (loosely typed) Perfectly legal in JavaScript to assign first a number to a variable, then later assign a string to that variable Following rules exist: Omitting the var keyword still creates a global variable not good practice and a source of bugs You should organize your variables based on what kind of data they will hold in your program (pseudo data type)

5.2 VARIABLE SCOPE 48 Scope is region of your source code in which variable is defined: Global variable; it is defined everywhere in your JavaScript code Variables declared in a function are local variables (local scope) Function parameters are also local variables, defined only within the body of the function Local variable takes precedence over a global variable with the same name (within function)

5.2 VARIABLE SCOPE 49 var is optional for global scope, but required for local variables, otherwise a locally intended variable becomes automatically global Consider what happens if you do not: Each function has its own scope, possible to have several nested layers of scope

5.2 VARIABLE SCOPE 50 In other programming languages, code within curly braces has its own scope, and variables are not visible outside of the block in which they are declared block scope JavaScript uses only function scope where variables are: visible within the function in which they are defined visible within any functions that are nested within that function All variables declared in a function are visible throughout the body of function This means that variables are even visible before they are declared! hoisting: JavaScript code behaves as if all variable declarations in a function (but not any associated assignments) are hoisted to the top of the function Local variable is defined throughout the body of the function, which means the global variable by the same name is hidden throughout the function Declare all variables at the top of a function, rather than to declare them closer to the point at which they are used

5.3 GLOBAL OBJECT AND VARIABLES 51 Global JavaScript variable is a property of the global object: Variable declaration with keyword var: property that is created is nonconfigurable cannot delete it! Variable declaration without keyword var: When assigning a value to an undeclared variable, JavaScript automatically creates a global variable for you that is configurable can delete it! Local variables are properties of an object associated with each function invocation JavaScript is a lexically (vs. dynamically) scoped language: Scope of a variable can be thought of as the set of source code lines for which the variable is defined Variable is defined by its location within the source code (it is apparent lexically) and nested functions have access to variables declared in their outer scope

5.3 GLOBAL OBJECT AND VARIABLES 52 JavaScript code (global code, functions) scope chain Scope chain is a list or chain of objects that defines the variables that are in scope JavaScript looks up value of variable x (variable resolution), it starts at the top of chain looking for property x in the object until it finds the first occurrence( if none found ReferenceError): When function is invoked, it creates a new object to store its local variables added to the stored scope chain to create a new, longer, chain that represents the scope for that function invocation

Operators and Expressions 6.

6. OPERATORS AND EXPRESSIONS 53 Complex expressions are built from simpler expressions: Array access expression consists of one expression that evaluates to an array followed by an open square bracket, an expression that evaluates to an integer, and a close square bracket (i.e. arr[2] ) Function invocation expression consists of one expression that evaluates to a function object and zero or more additional expressions that are used as the arguments to the function (i.e. ftest(4, test ) ) Common way to build a complex expression out of simpler expressions is with an operator: +, -, *, / Operators are used for JavaScript s arithmetic expressions, comparison expressions, logical expressions, assignment expressions, and more

6.1 OVERVIEW OF JAVASCRIPT OPERATORS 54 Most operators are represented by punctuation characters Some are represented by keywords (delete, instanceof) Number of Operands Operators can be categorized based on the number of operands they expect (their arity): Operand and Result Type Some operators work on values of any type But most expect their operands to be of a specific type And most operators return (or evaluate to) a value of a specific type (result type)

6.1 OVERVIEW OF JAVASCRIPT OPERATORS 55 Order by operator precedence Thick horizontal line separates precedence levels Column A: Operator associativity (L left to right, R right to left) Type lists the expected types of the operands and (after the symbol) the result type for the operator lval can legally appear on left side of assignment expression (vars, properties, array elements)

6.1 OVERVIEW OF JAVASCRIPT OPERATORS 56 JavaScript operators usually convert the type of their operands as needed (implicit conversion): 5 * 3 = 15 Every JavaScript value is either truthy or falsy, so operators that expect Boolean operands will work with an operand of any type Some operators behave differently depending on type, i.e. +: If numbers arithmetic addition If strings string concatenation (unfortunately confusing) Operator Precedence Operators with higher precedence are performed before those with lower precedence Assignment operator has lower precedence than * and + performed last Use parentheses to override order of precedence

6.1 OVERVIEW OF JAVASCRIPT OPERATORS 57 Property access and invocation expressions have higher precedence than any of the operators listed in previous Table! If unsure about the precedence of operators, simply use parentheses to make the evaluation order explicit Operator Associativity The associativity of an operator specifies the order in which operations of the same precedence are performed Value of L = left right R = right left

6.2 ARITHMETIC EXPRESSIONS 58 Basic arithmetic operators are: * (multiplication), / (division), % (modulo: remainder after division), + (addition), - (subtraction) Non-numeric operands that cannot convert to numbers convert to the NaN value If either operand is (or converts to) NaN, the result of the operation is also NaN The + Operator The binary + operator: adds numeric operands or concatenates string operands

6.2 ARITHMETIC EXPRESSIONS 59 When + operator is used with string and numbers, it may not be associative result depends on order of operation Unary Arithmetic Operators Unary operators modify the value of a single operand to produce a new value High precedence and right associative

6.2 ARITHMETIC EXPRESSIONS 60 Unary Operators: Return value of ++/-- operator depends on its position relative to the operand: Warning: Expression ++x is not always the same as x=x+1 ++ operator never performs string concatenation: it always converts its operand to a number and increments it If x is the string 1, ++x is the number 2, but x+1 is the string 11

6.3 RELATIONAL EXPRESSIONS 61 Relational operators test for a relationship (such as equals, less than, or property of ) between two values return true or false depending on whether that relationship exists Equality and Inequality Operators == and === check whether two values are the same using two different definitions of sameness === Strict equality == Less strict equality!= and!== tests for the exact opposite (! is Boolean NOT): Objects are compared by reference, not by value! Object is equal to itself, but not to any other object

6.3 RELATIONAL EXPRESSIONS 61 Strict equality operator evaluates its operands, then compares the two values performing no type conversion: Equality operator is like the strict equality operator, but it is less strict attempts some type conversion before comparing!

6.3 RELATIONAL EXPRESSIONS 63 Expression using equality operator evaluates to true, indicating that these very different-looking values are equal! Using strict equal operator values are indeed different

6.3 RELATIONAL EXPRESSIONS 64 Comparison Operators Operands may be of any type But comparison can be performed only on number and strings Operands that are not strings or numbers are converted Comparisons and conversion occurs as follows:

6.3 RELATIONAL EXPRESSIONS 65 Strings are sequences of 16-bit integer values comparison of numerical values in the string Numerical encoding order defined by Unicode may not match the traditional collation order used in any particular language or locale Use String.localeCompare() for a more robust string-comparison algorithm Use String.toLowerCase() and String.toUpperCase() for caseinsensitive comparision

6.3 RELATIONAL EXPRESSIONS 66 IN Operator in operator expects a left-side operand that is or can be converted to a string It expects a right-side operand that is an object It evaluates to true if the left-side value is the name of a property of the right-side object instanceof Operator The instanceof operator expects a left-side operand that is an object and a right-side operand that identifies a class of objects The operator evaluates to true if left-side object is an instance of the right-side class Evaluates to false otherwise

6.4 LOGICAL EXPRESSIONS 67 Logical AND (&&) The && operator can be understood at 3 different levels: 1 st Level: When used with Boolean operands, && performs the Boolean AND operation on the two values: Returns true if and only if both its first and second operand are true If one or both of these operands is false, it returns false But && does not require that its operands be Boolean values Recall that all JavaScript values are either truthy or falsy 2 nd Level: && can be understood as a Boolean AND operator for truthy and falsy values 3 rd Level: Starts by evaluating its first operand, the expression on its left: If the value on the left is falsy, entire expression is falsy, returns left value (and does not even evaluate right value) If the value on the left is truthy evaluates and returns right value

6.4 LOGICAL EXPRESSIONS 68 It is important to understand that && may or may not evaluate right-side operand Behavior of && is sometimes called short circuiting behavior is sometimes exploited: Careful when writing expressions with side effects on right side!! Logical OR ( ) The operator performs the Boolean OR operation on its two operands: If one or both operands is truthy, it returns a truthy value If both operands are falsy, it returns a falsy value Also complex behavior: Starts by evaluating its first operand (expression on the left) If the value of this first operand is truthy, it returns that truthy value Otherwise, it evaluates its second operand (expression on the right), and returns the value of that expression

6.4 LOGICAL EXPRESSIONS 69 Logical NOT (!)! operator is a unary operator; placed before a single operand Its purpose is to invert the Boolean value of its operand Unlike the && and operators, the! operator converts its operand to a Boolean value before inverting the converted value This means that! always returns true or false As a unary operator,! has high precedence and binds tightly If you want to invert the value of an expression like p && q, you need to use parentheses:!(p && q) It is worth noting two theorems of Boolean algebra here that we can express using JavaScript syntax:

6.5 ASSIGNMENT EXPRESSIONS 70 Use the = operator to assign a value to a variable or property = operator expects its left-side operand to be an lvalue: a variable or object property (or array element) Expects its right-side operand to be an arbitrary value of any type Value of an assignment expression is the value of the right-side operand! Assignment expression as part of a larger a expression: Assignment operator has right-to-left associativity when multiple assignment operators appear in an expression, they are evaluated from right to left

6.5 ASSIGNMENT EXPRESSIONS 71 Assignment with Operation += operator performs addition and assignment += operator works for numbers or strings Numbers addition, then assignment Strings concatenation, then assignment

6.5 ASSIGNMENT EXPRESSIONS 72 First line, expression a is evaluated once Second line a is evaluated twice The two cases will only differ if a includes side effects: function call, increment operator Example shows that two assignments are not the same:

6.6 MISCELLANEOUS OPERATORS 73 Conditional Operator (? :) The only ternary operator (three operands) Three operands: First goes before the? Second goes between the? and the : Third goes after the : First operand is evaluated and interpreted as a Boolean: If first operand is truthy, then the second operand is evaluated, and its value is returned If first operand is falsy, then the third operand is evaluated and its value is returned

6.6 MISCELLANEOUS OPERATORS 74 typeof Operator typeof is a unary operator that is placed before its single operand, which can be of any type typeof operator is also useful when used with the switch statement You can place parentheses around the operand to typeof looks like the name of a function rather than an operator keyword

6.6 MISCELLANEOUS OPERATORS 75 Note that typeof returns object if the operand value is null typeof may return a string other than object for host objects Because typeof evaluates to object for all object and array values other than functions, it is useful only to distinguish objects from other, primitive types In order to distinguish one class of object from another, you must use other techniques, such as the instanceof operator, the class attribute, or the constructor property Although functions in JavaScript are a kind of object, the typeof operator considers functions to be sufficiently different that they have their own return value JavaScript makes a subtle distinction between functions and callable objects. All functions are callable, but it is possible to have a callable object that can be invoked just like a function that is not a true function

6.6 MISCELLANEOUS OPERATORS 76 delete Operator delete is a unary operator that attempts to delete the object property or array element specified as its operand Note that a deleted property or array element is not merely set to the undefined value When a property is deleted, the property ceases to exist: Attempting to read a nonexistent property returns undefined You can test for actual existence of property with the in operator Delete expects its operand to be an lvalue: If it is not an lvalue, the operator takes no action and returns true Otherwise, delete attempts to delete the specified lvalue delete returns true if it successfully deletes the specified lvalue

6.6 MISCELLANEOUS OPERATORS 77 void Operator void is a unary operator: appears before a single operand, which may be of any type Unusual and infrequently used: it evaluates its operand, then discards the value and returns undefined Comma Operator (,) Binary operator whose operands may be of any type Evaluates its left operand, evaluates its right operand, and then returns the value of the right operand Left-hand expression is always evaluated, but its value is discarded Only makes sense to use the comma operator when the left-hand expression has side effects