Javascript Arrays, Object & Functions

Similar documents
Produced by. App Development & Modelling. BSc in Applied Computing. Eamonn de Leastar

jquery Fundamentals EVALUATION COPY (JQY102 version 3.0.0) Copyright Information Copyright 2013 Webucator. All rights reserved.

JavaScript CS 4640 Programming Languages for Web Applications


Web Application Development

Introduction to Web Tech and Programming

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

Node.js Training JavaScript. Richard richardrodger.com

Background. Javascript is not related to Java in anyway other than trying to get some free publicity

Client-Side Web Technologies. JavaScript Part I

CSC Web Programming. Introduction to JavaScript

JavaScript CS 4640 Programming Languages for Web Applications

CSCE 120: Learning To Code

BEFORE CLASS. If you haven t already installed the Firebug extension for Firefox, download it now from

JavaScript Functions, Objects and Array

JavaScript: the language of browser interactions. Claudia Hauff TI1506: Web and Database Technology

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh

TypeScript. Types. CS144: Web Applications

The course is supplemented by numerous hands-on labs that help attendees reinforce their theoretical knowledge of the learned material.

Mobile App:IT. Methods & Classes

Part I: Introduction to Functions

Course 2320 Supplementary Materials. Modern JavaScript Best Practices

Chapter 3 Data Types and Variables

Sprite an animation manipulation language Language Reference Manual

Your First Ruby Script

COMS 469: Interactive Media II

MatchaScript: Language Reference Manual Programming Languages & Translators Spring 2017

Javascript. Many examples from Kyle Simpson: Scope and Closures

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects

Powerful JavaScript OOP concept here and now. CoffeeScript, TypeScript, etc

EWD Custom Tag Development. Built-in Custom Tags for defining and manipulating Javascript

JavaScript: Sort of a Big Deal,

COMS 469: Interactive Media II

Session 3: JavaScript - Structured Programming

3 The Building Blocks: Data Types, Literals, and Variables

JavaScript: Coercion, Functions, Arrays

JavaScript Syntax. Web Authoring and Design. Benjamin Kenwright

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

PHP. Interactive Web Systems

COP4020 Programming Assignment 1 - Spring 2011

JavaScript I Language Basics

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

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

Introduction to Programming Using Java (98-388)

Princess Nourah bint Abdulrahman University. Computer Sciences Department

CHAD Language Reference Manual

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

Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p.

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

String Objects: The string class library

JAVASCRIPT - CREATING A TOC

JavaScript Lecture 3b (Some language features)

Lisp. Versions of LISP

Midterm Exam. 5. What is the character - (minus) used for in JavaScript? Give as many answers as you can.

Arrays Structured data Arrays What is an array?

COMP519 Web Programming Lecture 12: JavaScript (Part 3) Handouts

Appendix: Common Errors

CS1046 Lab 4. Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to:

B ON U S C H A P T E R MANNING. Simon Holmes

JAVASCRIPT. The Basics

React. HTML code is made up of tags. In the example below, <head> is an opening tag and </head> is the matching closing tag.

A Small Interpreted Language

IDM 231. Functions, Objects and Methods

Arrays, Strings and Collections

Web Site Design and Development JavaScript

Basics of JavaScript. Last Week. Needs for Programming Capability. Browser as Development Platform. Using Client-side JavaScript. Origin of JavaScript

Data Structures. Lists, Tuples, Sets, Dictionaries

JavaScript: Getting Started

JavaScript for C# Programmers Kevin

Java+- Language Reference Manual

LAST WEEK ON IO LAB. Install Firebug and Greasemonkey. Complete the online skills assessment. Join the mailing list.

CS 130(0) JavaScript Lab

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

This course is designed for web developers that want to learn HTML5, CSS3, JavaScript and jquery.

EXERCISE: Introduction to client side JavaScript

JAVASCRIPT - OBJECTS OVERVIEW

Variables and Typing

JAVASCRIPT FOR THE C# DEVELOPER

JavaScript Lecture 2

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

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

Topic 7: Lists, Dictionaries and Strings

University Convocation IT 3203 Introduction to Web Development Creating Objects Accessing Property Values

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

Robot Programming with Lisp

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts

Boot Camp JavaScript Sioux, March 31, 2011

Lecture 3: The Basics of JavaScript. Background. Needs for Programming Capability. Origin of JavaScript. Using Client-side JavaScript

(Refer Slide Time: 01:40)

Human-Computer Interaction Design

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Bruce Merry. IOI Training Dec 2013

Z Notation. June 21, 2018

INF5750. Introduction to JavaScript and Node.js

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Human-Computer Interaction Design

Rhythm Reference Manual

Chapter 2: Functions and Control Structures

Produced by. Agile Software Development. Eamonn de Leastar

Guidelines Quick Reference

Transcription:

Javascript Arrays, Object & Functions

Agenda Creating & Using Arrays Creating & Using Objects Creating & Using Functions 2

Creating & Using Arrays Arrays are a type of object that are ordered by the index of each item it contains. The index starts at zero and extends to however many items have been added, which is a property of the array known as the "length" of the array. Similar to objects, an array can be created with the array constructor or the shorthand syntax known as array literal. 3

Creating Arrays... Array Constructor var foo = new Array; Array Literal var bar = []; 4

Creating Arrays with Dimensions Array Constructor var foo = new Array(100); Array Literal var bar = []; 5

Using Arrays... Insertion into arrays can be via: [] notation (like Java) Using push which appends to the end of the array var foo = []; foo.push("a"); foo.push("b"); alert( foo[ 0 ] ); // => a alert( foo[ 1 ] ); // => b alert( foo.length ); // => 2 foo.pop(); alert( foo[ 0 ] ); // => a alert( foo[ 1 ] ); // => undefined alert( foo.length ); // => 1 6

Definition of an Array Arrays are zero-indexed, ordered lists of values. They are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays. To create an array, either use the object constructor or the literal declaration, by assigning the variable a list of values after the declaration // A simple array with constructor var myarray1 = new Array( "hello", "world" ); // literal declaration, the preferred way var myarray2 = [ "hello", "world" ]; The literal declaration is generally preferred. See the Google Coding Guidelines for more information. 7

Push If the values are unknown, it is also possible to declare an empty Array, and add elements either through functions or through accessing by index: 'push' is a function that adds an element on the end of the array and expands the array respectively. You also can directly add items by index. Missing indices will be filled with 'undefined'. // Creating empty arrays and adding values var myarray = []; // adds "hello" on index 0 myarray.push("hello"); // adds "world" on index 1 myarray.push("world"); // adds "!" on index 2 myarray[ 2 ] = "!"; 8

Missing Indices Missing indices will be filled with 'undefined'. If the size of the array is unknown, 'push' is far more safe. You can both access and assign values to array items with the index // Leaving indices var myarray = []; myarray[ 0 ] = "hello"; myarray[ 1 ] = "world"; myarray[ 3 ] = "!"; console.log( myarray ); // [ "hello", "world", undefined, "!" ]; // Accessing array items by index var myarray = [ "hello", "world", "!" ]; console.log( myarray[2] ); // "!" 9

Array Methods and Properties 10

length The.length property is used to determine the amount of items in an array. You will need the.length property for looping through an array: // Length of an array var myarray = [ "hello", "world", "!" ]; console.log( myarray.length ); // 3 // For loops and arrays - a classic var myarray = [ "hello", "world", "!" ]; for ( var i = 0; i < myarray.length; i = i + 1 ) { console.log( myarray[i] ); } Except when using for/in loops: // For loops and arrays - alternate method var myarray = [ "hello", "world", "!" ]; for ( var i in myarray ) { console.log( myarray[ i ] ); } 11

concat Concatenate two or more arrays with.concat: // Concatenating Arrays var myarray = [ 2, 3, 4 ]; var myotherarray = [ 5, 6, 7 ]; // [ 2, 3, 4, 5, 6, 7 ] var wholearray = myarray.concat( myotherarray ); 12

join.join creates a string representation of the array. Its parameter is a string that works as a separator between elements (default separator is a comma): // Joining elements var myarray = [ "hello", "world", "!" ]; console.log( myarray.join(" ") ); // "hello world!"; console.log( myarray.join() ); // "hello,world,!" console.log( myarray.join("") ); // "helloworld!" console.log( myarray.join("!!") ); // "hello!!world!!!"; 13

pop.pop removes the last element of an array. It is the opposite method of.push: // pushing and popping var myarray = []; myarray.push( 0 ); // [ 0 ] myarray.push( 2 ); // [ 0, 2 ] myarray.push( 7 ); // [ 0, 2, 7 ] myarray.pop(); // [ 0, 2 ] 14

reverse The elements of the array are in reverse order after calling this method: // reverse var myarray = [ "world", "hello" ]; // [ "hello", "world" ] myarray.reverse(); 15

shift Removes the first element of an array. With.pop and.shift, you can simulate a queue: // queue with shift() and pop() var myarray = []; myarray.push( 0 ); // [ 0 ] myarray.push( 2 ); // [ 0, 2 ] myarray.push( 7 ); // [ 0, 2, 7 ] myarray.shift(); // [ 2, 7 ] 16

foreach In modern browsers it is possible to traverse through arrays with a.foreach method, where you pass a function that is called for each element in the array. The function takes up to three arguments: Element - The element itself. Index - The index of this element in the array. // native foreach function printelement( elem ) { console.log( elem ); } myarray = [ 1, 2, 3, 4, 5 ]; // prints all elements to the console myarray.foreach( printelement ); Array - The array itself. All of these are optional, but you will need at least the 'element' parameter in most cases 17

Element & Index Parameters function printelementandindex( elem, index ) { console.log( "Index " + index + ": " + elem ); } // prints "Index 0: 1" "Index 1: 2" "Index 2: 3"... myarray.foreach( printelementandindex ); 18

Creating & Using Objects The simplest way to create an object is either through: the object constructor the shorthand syntax known as object literal. Objects are unordered key/value pairs. The key is formally known as a property and the value can be any valid JavaScript type, even another object. To create or access a property on an object, we use dot notation bracket notation 19

Creating Objects... Object Constructor var person1 = new Object; person1.firstname = "John"; person1.lastname = "Doe"; Object Literal var person2 = { firstname: "Jane", lastname: "Doe" }; 20

Using Objects... Dot Notation person1.firstname = "John"; person1.lastname = "Doe"; Bracket Notation person['firstname'] = "Mary"; person['lastname'] = "Smith"; 21

Tracing Objects Object structure and contents can be explored in detail in Chrome Developer Tools 22

Object Literals Objects contain one or more keyvalue pairs. The key portion can be any string. The value portion can be any type of value: a number, a string, an array, a function, or even another object. When one of these values is a function, it s called a method of the object. Otherwise, they are called properties. // Creating an object literal var myobject = { sayhello : function() { console.log("hello"); }, myname : "Rebecca" }; myobject.sayhello(); // "hello" console.log(myobject.myname); // "Rebecca" 23

Object Literals When creating object literals, note that the key portion of each key-value pair can be written as any valid JavaScript identifier, a string (wrapped in quotes), or a number: // test var myobject = { valididentifier : 123, "some string" : 456, 99999 : 789 }; 24

Creating Functions Functions contain blocks of code that need to be executed repeatedly. Functions can take zero or more arguments, and can optionally return a value. // Function Declaration function foo() { /* do something */ } Functions can be created in a variety of way // Named Function Expression var foo = function() { /* do something */ } 25

Using Functions // A simple function var greet = function(person, greeting) { var text = greeting + ", " + person; console.log(text); }; greet("rebecca", "Hello"); // A function that returns a value var greet = function(person, greeting) { var text = greeting + ", " + person; return text; }; console.log(greet("rebecca", "hello")); // "hello, Rebecca" 26

Functions creating Functions the greet function returns a function! This functions is then called. // A function that returns another function var greet = function(person, greeting) { var text = greeting + ", " + person; return function() { console.log(text); }; }; var greeting = greet("rebecca", "Hello"); greeting(); 27

Immediately-Invoked Function Expression (IIFE) A common pattern in JavaScript is the immediately-invoked function expression. This pattern creates a function expression and then immediately executes the function. // An immediately-invoked function expression (function() { var foo = "Hello world"; })(); This pattern is extremely useful for cases where you want to avoid polluting the global namespace with code no variables declared inside of the function are visible outside of it. console.log( foo ); // undefined! 28

Functions as Arguments In JavaScript, functions are "first-class citizens" they can be assigned to variables or passed to other functions as arguments. Challenging and difficult to read code! // Passing an anonymous function as an argument var myfn = function(fn) { var result = fn(); console.log(result); }; // logs "hello world" myfn(function() { return "hello world"; }); 29

Scope "Scope" refers to the variables that are available to a piece of code at a given time. A lack of understanding of scope can lead to frustrating debugging experiences. When a variable is declared inside of a function using the var keyword, it is only available to code inside of that function code outside of that function cannot access the variable. On the other hand, functions defined inside that function will have access to to the declared variable. 30

More Scope... Furthermore, variables that are declared inside a function without the var keyword are not local to the function JavaScript will traverse the scope chain all the way up to the window scope to find where the variable was previously defined. If the variable wasn't previously defined, it will be defined in the global scope, which can have unexpected consequences. 31

Scope Example 1 // Functions have access to variables defined in the same scope var foo = hello"; var sayhello = function() { console.log(foo); }; sayhello(); // "hello" console.log(foo); // "hello" 32

Scope Example 2 // Code outside the scope in which a variable was defined does not have access // to the variable var sayhello = function() { var foo = "hello"; console.log(foo); }; sayhello(); // hello console.log(foo); // undefined 33

Scope Example 3 // Variables with the same name can exist in different scopes with different // values var foo = "world"; var sayhello = function() { var foo = "hello"; console.log(foo); }; sayhello(); // logs "hello" console.log(foo); // logs "world" 34