JavaScript Part 1

Dr. Greg Bernstein

August 22nd, 2021

Getting Started with JavaScript

Learning Objectives

  • Understand JavaScript as a computer language, be able to run example programs in a browser
  • Learn and use JavaScript syntax, grammar, variables, and types
  • Learn and use JavaScript expressions and operators (a subset, more to come)

Readings

  1. Introduction
  2. Grammar and types
  3. Expressions and operators. Only the basic stuff plus typeof.

What is JavaScript?

JavaScript is a cross-platform, object-oriented scripting language.

JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set of language elements such as operators, control structures, and statements.

Client Side JavaScript

Client-side JavaScript extends the core language by supplying objects to control a browser and its Document Object Model (DOM).

Client-side JavaScript runs in a browser

Server Side JavaScript

Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server.

We’ll run server side JavaScript via Node.js

It’s not Java

JavaScript and Java are similar in some ways but fundamentally different in some others. The JavaScript language resembles Java but does not have Java’s static typing and strong type checking. JavaScript follows most Java expression syntax, naming conventions and basic control-flow constructs.

Runtime vs. Compile Time

In contrast to Java’s compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model.

Very Permissive!

JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.

Try it out!

  • Interactive JavaScript consoles are built in to Chrome and Firefox. Use Shift-Ctr-I on windows or use browser menu.

  • As you go over the basics always try things out via the console!

The Developer Console

Developer console

First JS Program

function greetMe(yourName) {
  alert('Hello ' + yourName);
}

greetMe('World');

Grammar and Types

Comments

Just like C/C++ and Java

// Single line comments
/*  Multiple
    line
    comments */

Variable Declarations

Three ways:

var x = 1.0; //Old fashioned, has quirks
let s = "CS3520"; // modern, standard scoping
const C = 299792458.0; // Read only

Variable Naming

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters “A” through “Z” (uppercase) and the characters “a” through “z” (lowercase).

Evaluating Variables

A variable declared using the var or let statement with no initial value specified has the value undefined.

An attempt to access an undeclared variable will result in a ReferenceError exception being thrown.

Try it!

Variable Scope

  • Three types: Global, Local, and Block
  • JavaScript prior to ES2015 only had Global and Local
    • Defined with var statement, a variable without a var statement is by default global!
    • Weird thing called variable hoisting with var
  • ES2015 and beyond using let and const support block, local, and global and they behave as you would expect.
    • Example: variable local to a for loop.

Data Types (Primitives)

  • Boolean. true and false.
  • null. A special keyword denoting a null value.
  • undefined. A top-level property whose value is undefined.
  • Number. 42 or 3.14159.
  • String. "Howdy"
  • Symbol (new in ECMAScript 2015). (later)

Data Types

  • JavaScript objects can contain other data types and other objects.
  • You can use the typeof(...) method to look at data types.
  • Note that JavaScript arrays are special objects
  • JavaScript functions essentially have their own datatype

Dynamically Typed Language

  • Variables do not get a data type!
    • Unlike C/C++ or Java
    • More ways to make errors 😕
  • Values do have specific types!

Type Conversions

Easy combining strings and numbers:

let a = "I feel like I am " + 22;
let b = 20 + " years ago today";

Doesn’t work with other operators such as -

Strings to Numbers

Use parseInt() or parseFloat() functions

let n = parseInt("277");
let x = parseFloat("3.1415");

Try it! Try it with “bad inputs”

Array Literals

Nice and easy!

let a1 = [2, 3, 6, 7];
let a2 = ["a", "CS", "3520", "EB"];
let a3 = [1, 3, "Hi", "world"]; // Why?

Boolean and Float Literals

let stop = false;
let tooCold = true;
let x = -3.01e2;
let y - 7.023;

Integer Literals

You get decimal, octal, hex, and binary

let n1 = 10;
let n2 = 010; //Octal, value is 8
let n3 = 0xff; //Hex, value is 255
let n4 = 0b1010; // Binary, value 10

Object Literals

Similar to Python dictionary, but better:

let webDev = {course: "CS3520", prof: "Dr. B",
              days: "TuTh", time: "10:00-11:50AM"};

String Literals

Single quotes, double quotes, back-ticks for templates:

let s1 = 'Sunflowers';
let s2 = "Cactus";
// The next is a template string, uses back-ticks
let s3 = `Should I plant ${s1} or ${s2}`;

Lots of support for special characters. See MDN.

Hands on Time

  • Math in JS: Guess my number
  • Working with and JS Objects: extract, add, and change info

Expressions and Operators

Assignment Operators

Name Shorthand Meaning
Assignment x = y x = y
Addition assignment x += y x = x + y
Subtraction assignment x -= y x = x - y
Multiplication assignment x *= y x = x * y
General Idea… x op= y x = x op y

Array Destructuring (new)

See Destructuring

var foo = ['one', 'two', 'three'];

var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"

Object Destructuring (new)

var o = {wind: 22, waves: true};
var {wind, waves} = o;
console.log(wind, waves); // 22, true

// Or with new names
var {wind: speed, waves: anyWaves} = o;
console.log(speed, anyWaves);

Comparison Operators

Operator Description
Equal (==) Returns true if the operands are equal.
Not equal (!=) Returns true if the operands are not equal.
Strict equal (===) Returns true if the operands are equal and of the same type.

Comparison Operators 2

Operator Description
Strict not equal (!==) Returns true if the operands are of the same type but not equal, or are of different type.
Greater than (>) Returns true if the left operand is greater than the right operand.
Greater than or equal (>=) Returns true if the left operand is greater than or equal to the right operand.

Comparison Operators 3

Operator Description
Less than (<) Returns true if the left operand is less than the right operand.
Less than or equal (<=) Returns true if the left operand is less than or equal to the right operand.

Arithmetic Operators 1

Operator Description
Remainder (%) Binary operator. Returns the integer remainder of dividing the two operands.
Increment (++) Unary operator. Adds one to its operand.
Decrement () Unary operator. Subtracts one from its operand.

Arithmetic Operators 2

Operator Description
<Unary negation (-) Unary operator. Returns the negation of its operand.
Unary plus (+) Unary operator. Attempts to convert the operand to a number, if it is not already.
Exponentiation operator (**) Calculates the base to the exponent power, that is, baseexponent

Bitwise Operators

  • With its C/Java heritage JavaScript comes with a full set of bitwise operators
  • Things like bitwise AND, OR, and XOR
  • Shift operators: left and right with extension/fill options
  • See MDN Bitwise

Logical Operators 1

Operator Usage Description
Logical AND (&&) expr1
&&
expr2
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

Logical Operators 2

Operator Usage Description
Logical OR (||) expr1
||
expr2
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

Logical Operators 3

Operator Usage Description
Logical NOT (!) !expr Returns false if its single operand can be converted to true; otherwise, returns true.

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

String operators

You can use comparison operators on string and you can use + for string concatenation:

console.log("CS3520: " + "web development");

We’ll use this a lot.

Conditional (ternary) Operator

condition ? val1 : val2

If condition is true, the operator has the value of val1. Otherwise it has the value of val2.

var age = 20;
var status = (age >= 18) ? 'adult' : 'minor';

Unary Operators

  • delete: use to delete objects or properties
  • typeof: returns a string describing the type of the operand.

Relational Operators

  • in: use to tell if an object has a property
  • instanceof: to see if an object is of a specified object type.
let my1 = {board: "Foil", sail: "6.6m"};
let my2 = {board: "Surf"};
console.log("sail" in my1, "sail" in my2);
var arr = [1, 2, 3];
console.log(arr instanceof Array, arr instanceof Date);
// reveal.js plugins