Expressions in JavaScript. Jerry Cain CS 106AJ October 2, 2017

Similar documents
Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Functions and Libraries Once upon a time...

Programming Lecture 3

CSCE 120: Learning To Code

Mat 2170 Week 6. Methods. Week 6. Mat 2170 Week 6. Jargon. Info Hiding. Math Lib. Lab 6. Exercises. Methods. Spring 2014

Full file at

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

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

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Full file at

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

VARIABLES & ASSIGNMENTS

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

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Chapter 2 Working with Data Types and Operators

Hello, World and Variables

Chapter 17. Fundamental Concepts Expressed in JavaScript

Arithmetic and IO. 25 August 2017

Operators. Java operators are classified into three categories:

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

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

Outline. Data and Operations. Data Types. Integral Types

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Differentiate Between Keywords and Identifiers

3. Java - Language Constructs I

Program Fundamentals

double float char In a method: final typename variablename = expression ;

Expressions and Casting

Reserved Words and Identifiers

Visual C# Instructor s Manual Table of Contents

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

CCBC Math 081 Order of Operations Section 1.7. Step 2: Exponents and Roots Simplify any numbers being raised to a power and any numbers under the

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Programming in C++ 5. Integral data types

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

COMP Primitive and Class Types. Yi Hong May 14, 2015

CS177 Python Programming. Recitation 2 - Computing with Numbers

C++ Programming: From Problem Analysis to Program Design, Third Edition

Python Programming Exercises 1

Operators and Expressions:

Introduction to Computer Science and Object-Oriented Programming

CISC 110 Week 3. Expressions, Statements, Programming Style, and Test Review

Arithmetic Operations

UNIT- 3 Introduction to C++

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

write vs. writeln Prompting as Page Loads Today s Goals CSCI 2910 Client/Server-Side Programming Intermediate File vs. HTML Output

Math 171 Proficiency Packet on Integers

C Programs: Simple Statements and Expressions

CEN 414 Java Programming

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

The float type and more on variables FEB 6 TH 2012

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

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

CS102: Variables and Expressions

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

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

Section 2: Introduction to Java. Historical note

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Objectives. Connecting with Computer Science 2

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

CSE 115. Introduction to Computer Science I

Basics of Java Programming

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Basics of Computational Geometry

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Pace University. Fundamental Concepts of CS121 1

XQ: An XML Query Language Language Reference Manual

CHAPTER 3: CORE PROGRAMMING ELEMENTS

Chapter 2: Using Data

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Values and Variables 1 / 30

Introduction to Computer Programming for Non-Majors

CS112 Lecture: Primitive Types, Operators, Strings

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Basics of Programming

CS112 Lecture: Working with Numbers

Introduction to Engineering gii

COMPUTER ARCHITECTURE AND ORGANIZATION. Operation Add Magnitudes Subtract Magnitudes (+A) + ( B) + (A B) (B A) + (A B)

Sketchpad Graphics Language Reference Manual. Zhongyu Wang, zw2259 Yichen Liu, yl2904 Yan Peng, yp2321

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Logic Design: Part 2

Section 1.2 Fractions

Primitive Data Types: Intro

Watkins Mill High School. Algebra 2. Math Challenge

Downloaded from Chapter 2. Functions

Lab copy. Do not remove! Mathematics 152 Spring 1999 Notes on the course calculator. 1. The calculator VC. The web page

Elementary Programming

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Floating Point Arithmetic

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Chapter 4: Basic C Operators

Transcription:

Expressions in JavaScript Jerry Cain CS 106AJ October 2, 2017

What is JavaScript? JavaScript was developed at the Netscape Communications Corporation in 1995, reportedly by a single programmer in just 10 days. The language, which was called Mocha at the time, was designed to serve as a programming language that could be embedded in web pages viewed in the browser. JavaScript has since become the dominant language for all interactive web content and appears in some surveys as the most popular language in the computing industry. As always, the focus of any of the CS 106A courses is to teach you the fundamentals of programming, rather than to teach the details of any particular language. To this end, CS 106AJ does not try to teach all of JavaScript, but focuses instead on what the JavaScript expert and evangelist Douglas Crockford calls the good parts.

JavaScript: The Good Parts JavaScript Fortunately, is JavaScript a language with has some more than extraordinarily its share of good bad parts. parts. It went In from JavaScript, non-existence there atobeautiful, global adoption elegant, highly in anexpressive alarmingly language short period that is buried of time. under Itanever steaming hadpile an interval of goodinintentions the lab when andit blunders. could be tried The best outnature and of polished. JavaScript It went is so straight effectively intohidden Netscape thatnavigator for many2 just years as it the was, prevailing and it was opinion very rough. of When JavaScriptJava was that applets it was failed, an JavaScript unsightly, became incompetent the Language toy. My of intention the Web here by default. is to JavaScript s expose the popularity goodness isin almost JavaScript, completely an independent outstanding, dynamic of its qualities programming as a programming language. language.

Arithmetic Expressions Like most languages, JavaScript specifies computation in the form of an arithmetic expression, which consists of terms joined together by operators. Each term in an arithmetic expression is one of the following: An explicit numeric value, such as 2 or 3.14159265 A variable name that serves as a placeholder for a value A function call that computes a value An expression enclosed in parentheses The operators are typically the familiar ones from arithmetic: + Addition Subtraction * Multiplication / Division % Remainder

The Remainder Operator The only arithmetic operator that has no direct counterpart in traditional mathematics is %, which computes the remainder when the first is divided by the second: 14 % 7 returns 0 14 % 5 returns 4 7 % 14 returns 7 The result of the % operator make intuitive sense only if both operands are positive integers. The examples in the book do not depend on knowing how % works with negative numbers or numbers that have fractional parts. The remainder operator turns out to be useful in a surprising number of programming applications and is well worth a bit of study.

Using the JavaScript Console The easiest way to get a sense of how arithmetic expressions work is to enter them on the JavaScript console available on the cs106aj.stanford.edu web site. JavaScript Console -> 2 + 2 4 -> 342-173 169 -> 12345679 * 63 777777777 -> 9 * 9 * 9 + 10 * 10 * 10 1729 ->

Variables The simplest terms that appear in expressions are constant literals and variables. A variable is a placeholder for a value that can be updated as the program runs. A variable in JavaScript is most easily envisioned as a box capable of storing a value answer 42 Each variable has the following attributes: A name, which enables you to tell the variables apart. A value, which represents the current contents of the variable. The name of a variable is fixed; the value changes whenever you assign a new value to the variable.

Variable Declarations In JavaScript, you must declare a variable before you can use it. The declaration establishes the name of the variable and, in most cases, specifies the initial value as well. The most common form of a variable declaration is let name = value; where name is an identifier that indicates the name of the variable, and value is an expression specifying the initial value. Most declarations appear as statements in the body of a function definition. Variables declared in this way are called local variables and are accessible only inside that function.

Constant Declarations It is often useful to give names to values that you don t intend to change while the program runs. Such values are called constants. A constant declaration is similar to a variable declaration: const name = value; As before, name is an identifier that indicates the name of the constant, and value is an expression specifying its value.

Naming Conventions In JavaScript, all names must conform to the syntactic rules for identifiers, which means that the first character must be a letter and the remaining characters must be letters, digits, or the underscore character. Beyond these rules that apply to all JavaScript names, there are several conventions that programmers use to make their identifier names easier to recognize: Variable names and function names begin with a lowercase letter. If a name consists of more than one word, the first letter in each word is capitalized, as in numberofstudents. This convention is called camel case. Class names and program names begin with an uppercase letter. Constant names are written entirely in uppercase and use the underscore character to separate words, as in MAX_HEADROOM.

Precedence If an expression contains more than one operator, JavaScript uses precedence rules to determine the evaluation order. The arithmetic operators have the following relative precedence: unary - highest * / % + - lowest Thus, JavaScript evaluates unary operators first, then the operators *, /, and %, and then the operators + and -. Precedence applies only when two operands compete for the same operator. If the operators are independent, JavaScript evaluates expressions from left to right. Parentheses may be used to change the order of operations.

Exercise: Precedence Evaluation What is the value of the expression at the bottom of the screen? 42 51 45 6 3 2 9 15 1 * 2 * 3 + ( 4 + 5) % 6 * ( 7 + 8) - 9

Assignment Statements You can change the value of a variable in your program by using an assignment statement, which has the general form: variable = expression; The effect of an assignment statement is to compute the value of the expression on the right side of the equal sign and assign that value to the variable that appears on the left. Thus, the assignment statement total = total + value; adds together the current values of the variables total and value and then stores that sum back in the variable total. When you assign a new value to a variable, the old value of that variable is lost.

Statements such as Shorthand Assignments total = total + value; are so common that JavaScript allows the following shorthand: total += value; The general form of a shorthand assignment is variable op= expression; where op is any of JavaScript s binary operators. The effect of this statement is the same as variable = variable op (expression);

Increment and Decrement Operators Another important shorthand that appears frequently in JavaScript programs is the increment operator, which is most commonly written immediately after a variable, like this: x++; The effect of this statement is to add one to the value of x, which means that this statement is equivalent to or x += 1; x = x + 1; The -- operator (which is called the decrement operator) is similar but subtracts one instead of adding one.

Functions Revisited Last week, you learned that a function in Karel is a sequence of statements that has been collected together and given a name. Although that definition also applies in JavaScript, it fails to capture the idea that functions can process information. In JavaScript, a function can take information from its caller, perform some computation, and then return a result. This notion that functions exist to manipulate information and return results makes functions in programming similar to functions in mathematics, which is the historical reason for the name.

Functions in Mathematics The graph at the right shows the values of the function f (x) = x 2-5 Plugging in a value for x allows you to compute the value of f (x), as follows: f (0) = 0 2-5 = -5 f (1) = 1 2-5 = -4 f (2) = 2 2-5 = -1 f (3) = 3 2-5 = 4 The JavaScript version of f (x) is function f(x) { return x * x 5; }

Writing JavaScript Functions The general form of a function definition is function name(parameter list) { statements in the function body } where name is the name of the function, and parameter list is a list of variables used to hold the values of each argument. You can return a value from a function by including a return statement, which is usually written as return expression; where expression is an expression that specifies the value you want to return.

Examples of Simple Functions The following function converts Fahrenheit temperatures to their Celsius equivalent: function fahrenheittocelsius(f) { return 5 / 9 * (f 32); } The following function computes the area of a triangle from its base and height: function trianglearea(base, height) { return (base * height) / 2; }

Libraries To make programming easier, all modern languages include collections of predefined functions. Those collections are called libraries. For programming that involves mathematical calculations, the most useful library is the Math library, which includes a number of functions that will be familiar from high-school mathematics (along with many that probably aren t). A list of the most important functions appears on the next slide. In JavaScript, each of the functions in the Math library begins with the library name followed by a dot and then the name of the function. For example, the function that calculates square roots is named Math.sqrt. You call library functions just like any other function, so that calling Math.sqrt(16) returns the value 4.

Useful Functions in the Math Library Math.PI The mathematical constant π Math.E The mathematical constant e Math.abs(x) The absolute value of x Math.max(x, y,...) The largest of the arguments Math.min(x, y,...) The smallest of the arguments Math.round(x) The closest integer to x Math.floor(x) The largest integer not exceeding x Math.log(x) The natural logarithm of x Math.exp(x) The inverse logarithm (e x ) Math.pow(x, y) The value x raised to the y power (x y ) Math.sin(q ) The sine of q, measured in radians Math.cos(q ) The cosine of q, measured in radians Math.sqrt(x) The square root of x Math.random() A random value between 0 and 1

Exercise: Calculating a Quotient It is often useful to be able to compute the quotient of two numbers, which is the whole number that results if you divide the first by the second and then throw away any remainder. As noted on the prior slide, there is a function called floor in the Math library that makes the quotient function easier to write, but it is possible to write it using only JavaScript s standard arithmetic operators. Get together with your neighbors in the class and come up with an implementation for a function quotient(x, y) that returns the quotient of the positive integers x and y.

Nonnumeric Data The arithmetic expressions in the early sections of Chapter 2 enable you to perform numeric computation. Much of the excitement of modern computing, however, lies in the ability of computers to work with other types of data, such as characters, images, sounds, and video. As you will learn in Chapter 7, all of these data types are represented inside the machine as sequences of binary digits, or bits. When you are getting started with programming, it is more important to think about data in a more abstract way in which you focus on the conceptual values rather than the underlying representation.

Data Types The notion that data values come in many different forms gives rise to the notion of a data type, which defines the common characteristics of data values that have a particular form or purpose. In computer science, each data type is defined by a domain, which is the set of values that belong to that type, and a set of operations, which shows how the values in that domain can be manipulated. For example, the JavaScript type for numbers has a domain that consists of numeric values like 1.414213 or 42. The set of operations includes addition, subtraction, multiplication, division, remainder, and a few more that you haven t learned yet.

The String Type One of the most important data types in any programming language is the string type. The domain of the string type is all sequences of characters. In JavaScript, you create a string simply by including that sequence of characters inside quotation marks, as in "Jerry". The set of operations that can be applied to strings is large, but you don t need to know the entire set. In fact, for the first six chapters in the text, the only string operation you need to know is concatenation, as described on the next slide. You will learn about other operations in Chapter 7. All values including numbers, strings, graphical objects, and values of many other types can be assigned to variables, passed as arguments to functions, and returned as results.

Concatenation One of the most useful operations available for strings is concatenation, which consists of combining two strings end to end with no intervening characters. Concatenation is built into JavaScript using the + operator. For example, the expression "ABC" + "DEF" returns the string "ABCDEF". If you use + with numeric operands, it signifies addition. If at least one of its operands is a string, JavaScript interprets + as concatenation. It automatically converts the other operand to a string and concatenates the two strings, so that "Catch" + -22 "Catch-22"

The End