CSCE 120: Learning To Code

Similar documents
Chapter 17. Fundamental Concepts Expressed in JavaScript

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

Full file at

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

Chapter 2 Working with Data Types and Operators

Full file at C How to Program, 6/e Multiple Choice Test Bank

CSC Web Programming. Introduction to JavaScript

CSCE 120: Learning To Code

Variables and Typing

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

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

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Our Strategy for Learning Fortran 90

Outline. Data and Operations. Data Types. Integral Types

CGS 3066: Spring 2015 JavaScript Reference

Section we will not cover section 2.11 feel free to read it on your own

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

CS112 Lecture: Working with Numbers

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Algorithms and Programming I. Lecture#12 Spring 2015

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

VARIABLES & ASSIGNMENTS

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

JavaScript Basics. The Big Picture

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

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

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

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

I. Variables and Data Type week 3

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

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

Learning Language. Reference Manual. George Liao (gkl2104) Joseanibal Colon Ramos (jc2373) Stephen Robinson (sar2120) Huabiao Xu(hx2104)

JavaScript CS 4640 Programming Languages for Web Applications

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

Lecture 4 CSE July 1992

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Program Fundamentals

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

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

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

BASIC ELEMENTS OF A COMPUTER PROGRAM

Expressions and Variables

Elementary Programming

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

Mirage. Language Reference Manual. Image drawn using Mirage 1.1. Columbia University COMS W4115 Programming Languages and Translators Fall 2006

The C++ Language. Arizona State University 1

Chapter 3: Operators, Expressions and Type Conversion

Princess Nourah bint Abdulrahman University. Computer Sciences Department

CS102: Variables and Expressions

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

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

Full file at

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Chapter 3 Structure of a C Program

Computer Programming : C++

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Web Site Design and Development JavaScript

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

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

JavaScript CS 4640 Programming Languages for Web Applications

Introduction to Java Applications

CPS122 Lecture: From Python to Java

Typescript on LLVM Language Reference Manual

9. Elementary Algebraic and Transcendental Scalar Functions

The Warhol Language Reference Manual

MIT AITI Python Software Development

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Visual C# Instructor s Manual Table of Contents

Chapter 2 Basic Elements of C++

Using Basic Formulas 4

Ruby: Introduction, Basics

Programming for Engineers Introduction to C

Data types Expressions Variables Assignment. COMP1400 Week 2

Course Outline. Introduction to java

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

IT 374 C# and Applications/ IT695 C# Data Structures

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

SAMLab Tip Sheet #1 Translating Mathematical Formulas Into Excel s Language

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

Ruby: Introduction, Basics

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

LECTURE 02 INTRODUCTION TO C++

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

Variables, expressions and statements

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

The Very Basics of the R Interpreter

Properties and Definitions

Information Science 1

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

>>> * *(25**0.16) *10*(25**0.16)

Variables and Constants

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

Fundamental of Programming (C)

Transcription:

CSCE 120: Learning To Code Manipulating Data I Introduction This module is designed to get you started working with data by understanding and using variables and data types in JavaScript. It will also introduce you to basic operators and familiarize you with basic syntax and coding style. Variables Previously, we worked with data represented using JSON. JSON is actually a subset of the programming language JavaScript. In the full JavaScript, data is not merely static, it is dynamic. That is, data can be accessed, changed, moved around etc. The first mechanism for working with data is a variable. A variable in a programming language is much like a variable in algebra: it has a name (formally called an identifier) and can be assigned a value. This is very similar to how we worked with JSON data using key-value pairs. With variables, the variable name acts as a key while it can be assigned a value. Variable Declaration, Naming In JavaScript, you can create a variable using the keyword var and then providing a name for the variable. There are a few simple rules that must be followed when you name a variable. 1. Variable names can include letters (upper or lowercase), digits, and underscores (no spaces are allowed) 2. Variable names must begin with a letter (upper or lower case) 1 1 Variable names can also begin with $ or _ but this is discouraged as we ll see later. 1

3. Variable names are case sensitive so total, Total and TOTAL are three different variables 4. The JavaScript language has several reserved words that are used by the language itself and cannot be used for variable names 5. Variable names in the same context (same code block for example) must be unique A complete list of reserved words can be found here: http://www.w3schools.com/js/ js_reserved.asp. Some examples of variable declarations and names: 1 //variable declarations: 2 var total; 3 var numberofstudents; 4 var averagegpa; 5 var index; Semicolons You ll notice in the previous example each line was ended with a semicolon. This is a common aspect of many modern C-style syntax programming languages. Each executable line or statement is ended with a semicolon to make it unambiguous and clear where the statement ends. In JavaScript, semicolons are not absolutely necessary in many cases. However, it is still considered good programming practice and style to include semicolons where they would traditionally be required in other languages. For more information on when semicolons are necessary and when they are not, see the following article, http://inimino.org/~inimino/blog/javascript_semicolons. In this course, we will always include semicolons. Naming Conventions When naming variables, its best practice to give them names which describe their purpose. The names used above were full English words or phrases that described what the variables represented. You should avoid cryptic or generic variable names as it makes your code less readable and more difficult to manage. Moreover, we used a common modern naming convention called lower camel casing. In this convention, variable names consisting of multiple words are written together with no spaces, but the first letter of each new word is capitalized. The first word and the rest of the letters are all lower case. This convention has gained favor because of its relatively easy to both read and type. 2

Scoping The scope of a variable is the section of code in which the variable is valid. In general, a variable is valid within the block of code in which you declare it. We ll explore this issue in greater depth later on, but it is necessary at this point to understand two issues involving scoping in JavaScript. The first issue is that some variables have global scope. For example, when JavaScript is run within an HTML document, there is a document variable that refers to the document itself. When a variable has a global scope, it can be accessed anywhere in the code. Making changes to such variables is risky unless you know what you are doing. The second issue is that failure to use the var keyword in front of your variables is not an error. Instead, JavaScript creates your variable in the global context, making the scope of your variable global. In general this is bad practice. Using global variables pollutes the name space. Variable names must be unique, creating two different variables with the same name in the global context will lead to conflicts. Though it won t be an error, it may lead to unexpected or bad results. Comments The final thing to notice about the above example is the first line. This is a comment. Software developers place comments throughout their code as a form of documentation. Notes that document why they did things a certain way or other information intended for other developers (such as copyright declarations). In general, good code should be self-documenting. That is, well-written code should be readable enough that an experienced developer can discern how the code works. Comments in code should tell a developer the what and they why. Good comments provide a summary of what certain functions or code blocks do. Good comments also inform other developers of why things were done in a certain way (to be compatible with other code, performance, etc.). Single-line comments are denoted with two forward slashes: //. Anything that follows is ultimately ignored by the computer. Multi-line comments are denoted with an opening forward-slash-star: /* and closed with a */. Anything that appears between them is a comment and is ignored. Another example: 1 /* 2 John Student 3 CSCE 120 4 Fall 2014 5 */ 6 var total; 7 //used for pre-tax total: 8 var subtotal; 3

Operators Now that we have variables, we need a way to manipulate the values in the variables. To do this, we use operators that act on variables (in this context often referred to as operands) and values (referred to as literals). Assignment Operator We first need a way to assign values to variables. To do so, we use the assignment operator which is the single equals sign. Any type of value can be assigned to a variable. The proper usage of the assignment operator is to write: var variable = value; This has the meaning assign the value on the right hand side to the variable on the left hand side. Take care not to confuse the usage of a single equals sign as it is used in algebra. This is not an assertion of equality, but an assignment. Some examples: 1 var x; 2 x = 10; 3 var y; 4 y = "Hello"; 5 var z; 6 z = { 7 "lastname": "Student", 8 "firstname":"john" 9 }; 10 var myarray; 11 myarray = [10, 20, 30]; To save space, you can do a compound declaration-assignment in one line. You can even do multiple variable declaration-assignments on a single line using a comma as a separator. 1 var x = 10; 2 var y = "Hello"; 3 var a = 5, b = "five"; You can also reassign variable values. Reassigning a variable will erase the old value and take on the new value. You do not redeclare a variable when reassigning its value. 1 var x = 10; 2... 3 x = 20; 4... 5 x = "hello"; In the previous example observe that x was originally assigned a number and later it was 4

assigned a string. Variables in JavaScript have no fixed type: the type (numeric, string, object, etc.). Instead, the type of a variable is whatever the type of variable has been assigned to it last. Reassigning a variable value to a different type changes the variables type. This is known as dynamic typing and JavaScript is a dynamically typed language. In contrast, other languages are statically typed. Variables in a statically typed languages such as Java and C are declared by specifying their type and only values of that type may be assigned to the variable. That is, you cannot assign a string value to a numeric type. Arithmetic Operators Basic mathematical expressions can be formed using the common arithmetic operators: +, -, *, / which are used for addition, subtraction, multiplication and division respectively. These are binary operators in that they are applied to two variables, literals, or expressions. In addition, more complex expressions can be formed by using parentheses, (, ) just as you would in algebra. Also as in algebra, these operators have an order of precedence: multiplication and division are evaluated first, then addition and subtraction. Moreover, expressions are evaluated in a left-to-right manner. 1 var x = 10 + 20 * 30; //610 2 var y = (10 + 20) * 30; //900 3 var average = (x + y) / 2; 4 var a = 3, b = 4; 5 var c = a * a + b * b; 6 var d = (a - b) * (a + b); In each of the examples above, an expression was formed on the right-hand-side of the assignment operator. The value of the result of the expression was then placed into the variable on the left-hand-side. It would be invalid to put an expression on the lefthand-side. However, you can write an expression without an assignment operator such as: (a - b) * c; which is evaluated, but has no effect. We ve written a valid expression which is evaluated and has a value but we didn t end up doing anything with it (like placing the value into a variable). Another useful arithmetic operator is the integer division operator, a % b which gives the value of the remainder of a divided by b. For example, 23 % 5 would have a value 3 since 23 divided by 5 has a remainder of 3. Concatenation When working with strings, it is often useful to combine several strings into one single string. Or, it is useful to combine a string and the value stored in another variable (say 5

to print it out to the user). This operation is known as concatenation and is achieved by using the plus symbol +. Note: we previously used + when we wanted to perform addition. However, when used in the context of strings, + has the implicit meaning of concatenation. Consider the following: var c = a + b; In this line, if a, b are both numbers, then + is interpreted as addition and the result stored in c is a number. However, if either a, b are strings (or they both are), then + is interpreted as concatenation and the result in c is a string. 1 var message = "Hello, " + "World"; 2 var name = "John"; 3 var greet = "Greetings, " + name; 4 var a = 10; 5 var s = "The value stored in the variable a is " + a; Dot Accessor Recall that objects contain several key-value pairs. Given an object, we can manipulate each key-value pair by using the dot-operator,.. If an object is stored in a variable a, then we can access a value in that object by using: a.key Where key is replaced with the string of the key name you wish to access (this is why using spaces in a key is discouraged). Using the dot operator you can both assign values and access them. A full example: 1 var student = { 2 "firstname": "John", 3 "lastname": "Student" 4 }; 5 //access the names and concatenate them: 6 var name = student.lastname + ", " + student.firstname; 7 //reassign a value to an existing key: 8 student.firstname = "Jonathan"; 9 //set a new key-value pair in the object: 10 student.gpa = 3.75; Note in the last line above we created a new key value pair in an existing object by simply setting it. We did not need to use the keyword var to create this new variable inside the object. Advanced Tip: If you don t know what keys are part of your object x, you can get an array of strings containing them by calling Object.keys(x). 6

Array Indexing When elements are stored in an array, they can be accessed by specifying which element in the array you want. To do this, you must specify the index of the element. JavaScript, like most languages, uses zero-indexing to store elements meaning that the first element in the array is stored at index 0, the second is stored at index 1, etc. The last element is stored at index n 1 where n is the number of elements stored in the array. To access a single element in an array you use a combination of the array name, square brackets, and an index: arr[index] A full example: 1 var arr = [4, 7, 3, 9, 2, 1]; 2 var first = arr[0]; //4 3 var last = arr[5]; //1 4 //reassign an existing element: 5 arr[3] = 42; //now arr is [4, 7, 3, 42, 2, 1] We ll work with arrays in more depth later, but some other useful items: To determine the size (length) of an array, you can use arr.length Attempting to set a value of a negative index will transform your array into an object! Attempting to set a value of an index larger than the current size of the array will work. However, the elements in the array will no longer be contiguous. Indices between the new element and the previous old element are undefined (they do not exist; this is different from being null ). To easily add elements to the end of an array, use the push operation: arr.push(100); Math Library Sometimes its necessary to use mathematical functions more complex than simple addition, multiplication, etc. Fortunately, JavaScript provides a library of mathematical functions to help you compute square roots, powers, exponentials, etc. It also defines several useful mathematical constants such as π, e, etc. These convenient functions are part of the Math object and can be accessed using the dot operator (we ll study functions more in depth later on). Some examples: 7

1 //area of a circle 2 var radius = 1.5; 3 var area = Math.PI * radius * radius; 4 5 //quadratic formula: 6 var x1 = (-b + Math.sqrt(b*b - 4*a*c) ) / (2*a); 7 var x2 = (-b - Math.sqrt(b*b - 4*a*c) ) / (2*a); 8 9 //annual percentage rate and annual percentage yield 10 var apr = 0.08; 11 var apy = Math.exp(apr) - 1; A complete list of math functions and constants is available here: http://www.w3schools. com/js/js_math.asp. 8