CSE 154

Intro to JavaScript

A summary of JavaScript language basics (used to supplement the first few Module 2 lectures)

Following Along

As an interpreted programming language, JS is great to interact with a line at a time (similar to Python, but very different than Java). Where do you start?

The easiest way to dive in is with the Chrome browser's Console tab in the same inspector tool you've used to inspect your HTML/CSS.

Chrome Console

Until we learn functions to interact with the HTML DOM with JS, we recommend experimenting with the following code examples using this console to get comfortable with the fundamental syntax and behavior of the language.

Quick Reference

Our First JavaScript Statement: console.log

Used to output values to the browser console, most often used to debug JS programs. You can think of this as System.out.println in Java or print in Python.

console.log("message");

JS (template)

console.log("The answer is: " + 42);

JS (example)

console.log example

The alert Function

alert("message");

JS (template)

alert("Your browser says hi!");

JS (example)

Demo of browser alert

A JS function that pops up a dialog box with a message - not ideal in practice, but sometimes a recommended debugging tool when first learning JS. Don't include alert statements in any of your assignments.

Variables

let name = expression;

JS (template)

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

JS (example)

Variables are declared with the let keyword (case-sensitive). You may also see var used instead of let - this is an older convention with weaker scope - DO NOT USE var anywhere

CQG: Use camelCasing for variable (and function) names

"Types" in JavaScript

let level = 23; // Number
let accuracyRate = 0.99; // Number
let name = "Pikachu"; // String
let temps = [55, 60, 57.5]; // Array

JS (example)

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

  • Number, Boolean, String, Array, Object, Function, Null, Undefined
  • Can find out a variable's type by calling typeof, but usually this is poor practice (why?)
  • Note: Type conversion isn't always what you expect...

A Note about Declaring Types in JavaScript

If you've programmed in a statically-typed language like Java, you will recall that when declaring variables, you must specify their type which must always stay the same.

boolean isValid = "hello!"; // error

Java

In a dynamically-typed language like JavaScript, you don't need to specify the type (just use let or const) and you may change the type the variable refers to later in execution.

let isValid = true; // no error
isValid = "hello!";
isValid = 1;

JS

This may seem to imply fewer errors in JS, but it's not uncommon to run into subtle (silent) bugs in your JS programs as a result!

"Constants" in JavaScript

Since ECMA6, JavaScript has a special keyword to declare "constant" values. You should use these over the let keyword for variables that are not intended to ever be updated (similar to constants in Java).

CGQ: Use UPPER_CASING naming conventions to denote const in JS.

let month = 12;
month = 1; // no error

const COOLEST_CLASS = "CSE154";
COOLEST_CLASS = "clazz"; // error

JS

These can help avoid some of the bugs mentioned on the previous slide (an error occurs when trying to reassign a const).

Number Type

let enrollment = 99;
let medianGrade = 2.8;
let credits = 5 + 4 + (2 * 3);

JS

Integers and real numbers are the same type (no int vs. double). All numbers in JS are floating point numbers.

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

Similar precedence to Java

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

Practice!

NaN is a return value from operations that have an undefined numerical result (e.g. division by 0)

String type

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

JS

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

More about Strings

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

To convert between Numbers and Strings:

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

JS

To access characters of a String s, use s[index] or s.charAt(index):

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

JS

Splitting strings: split and join

let s = "the quick brown fox";
let 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

  • Can also be used with regular expressions surrounded by /:
    let a = s.split(/[ \t]+/);

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

Common Bugs when Using Strings

While Strings in JS are fairly similar to those you'd use in Java, there are a few special cases that you should be aware of.

  • Remember that length is a property (not a method, as it is in Java)
  • Concatenation with +: 1 + 1 is 2, but "1" + 1 and 1 + "1" are both "11"!

Practice: repeat, containsTwice

Arrays

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

JS (template)

            let types = ["Electric", "Water", "Fire"];
let pokemon = [];        // []
pokemon[0] = "Pikachu";  // ["Pikachu"]
pokemon[1] = "Squirtle"; // ["Pikachu", "Sqiurtle"]
pokemon[3] = "Magikarp"; // ["Pikachu", "Sqiurtle", undefined, "Magikarp"]
pokemon[3] = "Gyarados"; // ["Pikachu", "Sqiurtle", undefined, "Gyarados"]

JS (example)

Two ways to initialize an array

length property (grows as needed when elements are added)

Array methods

let 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

  • push and pop add/remove from back
  • shift and unshift add/remove from front
  • shift and pop return the element that is removed

Practice: findMin , switchPairs

Math object

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

JS

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

Properties: E, PI

Loops and Conditionals

function mystery(a, b) {
  if (a > b) {
    return 0;
  } else {
    let result = 0;
    for (let i = a; i <= b; i++) {
      result += i;
    }
    return result;
  }
}

JS (template)

Morpheus Java vs. JS Meme

for Loops (same as Java)

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

JS (template)

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

JS (example)

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

JS (example)

See slides below for comparisons in Java/Python!

for Loop Comparisons

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

JS (example)

String s1 = "It's a-me, Mario!";
String s2 = "";
for (int i = 0; i < s.length(); i++) {
  s2 += s1.charAt(i) + s1.charAt(i);
}

Java (example)

s1 = "It's a-me, Mario!";
s2 = "";
for i in range(len(s1)):
    s2 += s1[i] + s1[i];

Python (example)

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

Practice: rockPaperScissors

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!

Practice: loopMystery6

Logical Operators

Relational: > < >= <=, Logical: && || !, Equality: === !== == !=

  • Most logical operators automatically convert types. These are all true:
    • 5 < "7"
    • 42 == 42.0
    • "5.0" == 5
  • The === and !== are strict equality tests; checks both type and value: "5.0" === 5 is false. It's almost always best to use === instead of ==.
  • What does 154 === 154.0 evaluate to?

Helpful JavaScript equality table!

Boolean Type

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

JS

Any value can be used as a Boolean

  • "falsey" values: false, 0, NaN, "", null, and undefined
  • "truthy" values: anything else

Understanding what is "falsey" vs. "truthy" takes patience and practice.

When in doubt, check in the browser console!

Defining Functions

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

JS (template)

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

JS (example)

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

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

Practice: fixErrors2 , containsTwice , functionMystery1 , sumUpTo , veryBestSong

JS Function vs. Java Method

function repeat(str, n) {
  let result = str;
  for (let i = 1; i < n; i++) {
    result += str;
  }
  return result;
}
let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."

JS (example)

public static String repeat(String str, int n) {
  String result = str;
  for (int i = 1; i < n; i++) {
    result += str;
  }
  return result;
}
String repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."

Java (example)

JS Function vs. Python Function

function repeat(str, n) {
  let result = str;
  for (let i = 1; i < n; i++) {
    result += str;
  }
  return result;
}
let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."

JS (example)

def repeat(str, n):
  result = str;
  for i in range(1, n):
    result = result + str;
  return result;

repeatedStr = repeat("echo...", 3) // "echo...echo...echo..."

Python (example)

Comments (similar to Java)

// single-line comment

/**
 * multi-line
 * comment
 */

JS

Identical to Java's comment syntax

Recall: 3 comment syntaxes

  • HTML: <!-- comment -->
  • CSS/Java/JS: /* comment */
  • Java/JS: // comment

Documenting JS Functions with JSDoc

In this class, we expect you to use the @param and @returns annotation tags in JSDoc when appropriate for the function.

The @param annotation specifies the name and type of each parameter, as well as what the purpose of that parameter is in the function.

The @returns annotation specifies the type and expected value of what is returned given the parameters and any other conditions of the function. You do not need to use any other JSDoc annotations in CSE 154.

Documenting JS with JSDoc: Templates

Here is an example of function comment skeletons as reference:

// Single-line JSDoc comment:
/** Your comment here */

JSDoc Single-Line Comment

/**
 * brief description of the function
 * @param {datatype} parameterName1 - parameter description
 * @param {datatype} parameterName2 - parameter description
 * @returns {datatype} Description of the return value
 */
function functionName(parameterName1, parameterName2) {
  ...
}

JSDoc Function Template (Multi-line)

You can find more examples in our Code Quality Guide.

Summary: JavaScript vs. Java

Interpreted, not compiled (huh?)

More relaxed syntax and rules

  • Fewer and "looser" data types
  • Variables don't need to be declared
  • Errors often silent (few exceptions)
  • More similar to Python in these ways

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

  • "first-class" functions are used in many situations

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

Summary of Java vs. JS vs. Python

Java JS Python
Compiled vs. Interpreted Compiled Interpreted Interpreted
Typing Strong Loose Loose
Variable Declaration Must be declared before use Does not need to be declared before use Does not need to be declared before use
Key Construct Classes (OOP) Function Function

Resources and Tips

Review programming basics: using variables, arrays, loops, if-statements, and functions

Go over some JavaScript tutorials - there are many great ones!

Practice! We now have JavaScript problems on Practice-It (80+ problems) and its sister site CodeStepByStep (200+ problems).

Check out cool examples of JavaScript on the web!