Yo Melis it's all you

CSE 154

Lecture 6: Introduction to JavaScript

Terminology: Client-Side Scripting

client-side scripting

Client-side script: Code runs in browser after page is sent back from server. Often, this code manipulates the page or responds to user actions.

What is JavaScript

A lightweight programming language ("scripting language")

Used to make web pages interactive:

A web standard (but not supported identically by all browsers)

NOT related to Java other than name and some syntatic similarities...

JavaScript vs. Java

Interpreted, not compiled

More relaxed syntax and rules

JavaScript's key construct is the function rather than the object/class.

Contained within a web page and integrates with its HTML/CSS content

Linking to a JavaScript file: script

              
                
              
            

HTML

              
                
              
            

HTML

The script tag should be placed in the HTML page's head

Script code is stored in a separate .js file

JS code can be placed directly in the HTML file's body or head (like CSS)

Our First JavaScript Statement: alert

            
              alert("message");
            
          

JS

            
              alert("IE6 detected. Suck-mode enabled.");
            
          

JS

never use internet explorer

A JS command that pops up a dialog box with a message

Variables and types

            
            var name = expression;
            
          

JS

            
            var level = 23;
            var accuracyRate = 0.99;
            var name = "Pikachu";
            
          

JS

Variables are declared with the var keyword (case-sensitive)

Types are not specified, but JS does have types ("loosely-typed")

Number type

            
            var enrollment = 99;
            var mediangrade = 2.8;
            var credits = 5 + 4 + (2 * 3);
            
          

JS

Integers and real numbers are the same type (no int vs.

Same operators: + - * / % ++ \-\- = += -= *= /= %=

Similar precedence to Java

Many operators auto-convert types: "2" * 3 is 6

String type

            
            var nickName = "Sparky O'Sparkz"
            var fName = nickName.substring(0, s.indexOf(" ")); // "Sparky"
            var len = nickName.length;                         // 15
            var name = 'Pikachu';                              // can use " " or ' '
            
          

JS

Methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf, replace, split, substring, toLowerCase, toUpperCase

length property (not a method, as it is in Java

Concatentation with +: 1 + 1 is 2, but "1" + 1 is "11"

More about Strings

Escape sequences behave as in Java: \' \" \& \n \t \\

To convert between numbers and Strings:

            
            var count = 10;                              // 10
            var stringedCount = "" + count;              // "10"
            var puppyCount = count + " puppies, yay!";   // "10 puppies, yay!"
            var magicNum = parseInt("42 is the answer"); // 42
            var mystery = parseFloat("Am I a number?");  // NaN
            
          

JS

To access characters of a String, use [index] or charAt:

            
            var firstLetter = puppyCount[0];                   // "1"
            var fourthLetter  = puppyCount.charAt(3);          // "p"
            var lastLetter  = puppyCount.charAt(s.length - 1); // "!"
            
          

Comments (same as Java)

            
            // single-line comment

            /* multi-line comment */
            
          

JS

Identical to Java's comment syntax

Recall: 4 comment syntaxes

for loop (same as Java

            
            for (initialization; condition; update) {
              statements;
            }
            
          

JS

            
              var sum = 0;
              for (var i = 0; i < 100; i++) {
                sum = sum + i; // same as sum += i;
              }
            
          

JS

            
              var s1 = "It's a-me, Mario!";
              var s2 = "";
              for (var i = 0; i < s.length; i++) {
                s2 += s1[i] + s1[i];
              }
              // s2 stores "IItt''ss  aa--mmee,,  MMaarriioo!!"
            
          

JS

Math object

          
          var rand1to10 = Math.floor(Math.random() * 10 + 1);
          var three = Math.floor(Math.PI);
          
        

JS

Methods: abs, ceil, cos, floor, log, max, min, pow, random, round, sin, sqrt, tan

Properties: E, PI

Logical Operators

Relational: > < >= <=

Logical: && || !

Equality: == != === !==

Boolean Type

          
          var iLikeJS = true;
          var ieIsGood = "IE6" > 0; // false
          if ("web dev is great") { /* true */ }
          if (0) { /* false * }
          
        

JS

Any value can be used as a Boolean

Converting a value into a Boolean explicitly:

Special Values: null and undefined

          
          var foo = null;
          var bar = 9;
          var baz;

          /* At this point in the code,
               foo is null
               bar is 9
               baz is undefined */
          
        

JS

undefined: has not been declared, does not exist

null: exists, but was specifically assigned an empty or null value

Why does JavaScript have both of these?

if/else Statements (same as Java)

          
          if (condition) {
            statements;
          } else if (condition) {
            statements;
          } else {
            statements;
          }
          
        

JS

Identical structure to Java's if/else statements

JavaScript allows almost anything as a condition

while loops (same as Java)

          
          while (condition) {
            statements;
          }
          
        

JS

          
          do {
            statements;
          } while (condition);
          
        

JS

break and continue keywords also behave as in Java but do not use them in this class!

Arrays

          
          var name = [];                          // empty array
          var names = [value, value, ..., value]; // pre-filled
          names[index] = value;                   // store element
          
        

JS

          
          var types = ["Electric", "Water", "Fire"]; 
          var pokemon = [];
          pokemon[0] = "Pikachu";
          pokemon[1] = "Squirtle";
          pokemon[4] = "Magikarp";
          pokemon[4] = "Gyarados";
          
        

JS

Two ways to initialize an array

length property (grows as needed when elements are added)

Array methods

          
          var a = ["Mario", "Luigi"]; // [Mario, Luigi]
          a.push("Koopatroopa");      // [Mario, Luigi, Koopatroopa]
          a.unshift("Bowser");        // [Bowser, Mario, Luigi, Koopatroopa]
          a.pop();                    // [Bowser, Mario, Luigi]
          a.shift();                  // [Mario, Luigi]
          a.sort();                   // [Luigi, Mario]
          
        

JS

Array serves as many data structures: list, queue, stack, ...

Methods: concat, join, pop, push, reverse, shift, slice, sort, splice, toString, unshift

Splitting strings: split and join

          
          var s = "the quick brown fox";
          var a = s.split(" "); // ["the", "quick", "brown", "fox"]
          a.reverse();          // ["fox", "brown", "quick", "the"]
          s = a.join("!");      // "fox!brown!quick!the"
          
        

JS

split breaks apart a String into an array using a delimiter

join merges an array into a single String, placing a delimiter between them

Defining functions

          
          function name() {
            statement;
            statement;
            ...
            statement;
          }
          
        

JS

          
          function myFunction() {
            alert("Hello!");
            alert("Your browser says hi!");
          }
          
        

JS

The above could be the contents of example.js linked to our HTML page

Statements placed into functions can be evaluated in response to user events

Event-Driven Programming

event-driven programming

Unlike Java programs, JS programs have no main; they respond to user actions called events

Event Handlers

          
            <element attributes onclick="function();">...
          
        

HTML