code icon

CSCI 1720

Intermediate Web


Setup

node.js logo We're going to use Node.js for this lab. Node.js is a server-side runtime environment that includes everything you need to execute a program written in JavaScript, instead of a browser (which works client-side). Think: Java, .NET, or Python runtimes...same concept

For our purposes, Node.js also includes an interactive interpreter that we can use to run scripts or enter JavaScript directly into the console. Browsers have this capability also, but this gives us a little more functionality

You will need to have Node.js installed on your machine, if you don't already. The steps below will explain how to install Node.js on your (Windows) computer

Variables

  1. In your browser, navigate to Node.js/download
  1. Download and run the Node.js/download .msi installer
screenshot
Fig 1- Download Node.js Installer
  1. On your local drive, create a new folder in your labs folder named js-intro

We'll be using the console for this lab, but the deliverable is going to be a text file that logs your activities (don't worry...we'll get to that). So we need somewhere to save that file

In File Explorer, launch the Command Line Interpreter (CLI, a.k.a 'the console'), using the same trick we used for Sass. Your current directory should be your js-intro working directory

screenshot
Fig 1a- CLI

Confirm that Node.js is properly installed by entering node -v

screenshot
Fig 1b- Node.js Version

Enter node

screenshot
Fig 1c- Node.js Interactive Shell


We're now ready to start entering JavaScript

  1. Let’s declare some variables:
screenshot
Fig 2- Variables
  1. Now, output the value of the variables to the console:
screenshot
Fig 3- Using console.log()
  1. Let’s see if x is equal to y:
screenshot
Fig 4- Guess not
  1. Change x's value to y's value (9):
screenshot
Fig 5- Set x = y
  1. For form’s sake, let’s check:
screenshot
Fig 6- x now == y;

Strings

  1. Declare some string variables:
screenshot
Fig 7- Strings;
  1. …and output the name to the console:
screenshot
Fig 8- Concatenating Strings;
  1. Change the value of firstName, using the assignment operator (‘=’):
screenshot
Fig 9- Changing string's value
  1. …aaaand output it to the console log:
screenshot
Fig 10- New name

Here's one you'll use a lot, if you're using JS:

Enter console.log( (firstName + ' ' + lastName).length );

screenshot
Fig 10a- string.length

Arrays

In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable

  1. So, let’s create an array:
screenshot
Fig 11- JS array

A couple of things, here:

- Array notation uses square brackets with a comma delimited list of elements:

arrayName = [element0, element1, element2, ... , elementn]
- Notice that JS doesn't require all of the array's elements to be the same data type

  1. Access the second object in the array:
screenshot
Fig 12- Output array value
  1. Create a new array and display it:
screenshot
Fig 13- New array
screenshot
Fig 14- New array
  1. Sort the new array:
screenshot
Fig 15- .sort()

Notice that the sort method treats the numbers like strings, hence the assertion that 10 < 2. We can fix this easily by

screenshot
Fig 16- Adding simple numeric sort

Notice here that we can pass a function as a parameter. JS is cool with that

.shift()

  1. .shift(): Let’s output the first value in newArray:
screenshot
Fig 17- .shift();

Notice that the value of ‘1’ is no longer a part of the array:

screenshot
Fig 18- .shift(); removes array's first value

.push()

  1. .push()Add a new value to the end of the array:
screenshot
Fig 19- .push();

What the heck does '7' in the output mean? Well, the return value for the .push() method is the new length of the array!

  1. ….and display the new array:
screenshot
Fig 20- newArray

.pop()

  1. Retrieve the last value in the array:
screenshot
Fig 21- .pop();


.pop also removes the value from the array

.length

  1. Oftentimes, we have to find the number of values in an array:
screenshot
Fig 22- .length
  1. Add a couple of new values and check the array’s length again:
screenshot
Fig 23- Changing array's length

Objects

The Object class represents one of JavaScript's data types. It is used to store various keyed collections and more complex entities

  1. Now, let’s create a JS object:

A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object. You access the properties of an object with a simple dot-notation

screenshot
Fig 24- Object

Pay close attention to the notation here. The object is declared and contained within braces ({}). Each property is then defined as a comma-separated list of key: value pairs. Note that there is no comma after the last property declaration

  1. …aaand print it out:
screenshot
Fig 25- Object output
  1. Using dot notation, retrieve John Doe’s age:
screenshot
Fig 26- dot notation
  1. Let’s make John a little younger:
screenshot
Fig 27- Changing object property

Object comparison

  1. Let’s make another object:
screenshot
Fig 28- New object
  1. Compare the two person objects:
screenshot
Fig 29- Comparing objects

This seems pretty obvious, since, with the exception of 'firstName', all of the property values for personTwo are different than those in person

  1. So, change personTwo’s lastName , age, and eyeColor:
screenshot
Fig 30- Changing property values (the
values for each of the properties
in person and personTwo are now the
same)
  1. So now, person and personTwo are equivalent, right?
screenshot
Fig 31- Compare objects

Say whaaaaaat?? The reason for this is that internally JavaScript actually has two different approaches for testing equality. Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference. That comparison by reference basically checks to see if the objects given refer to the same location in memory. Here is an example of how that works

screenshot
Fig 32- Create a third variable
Call it personCompare

Now,

screenshot
Fig 33- Compare the objects

We can even

screenshot
Fig 34- Comparing objects

The triple equals sign in JavaScript checks to ensure that both value and type are equivalent

The reason person and personTwo don't evaluate to equal is subtle. When we compare objects, JS compares the objects' locations in memory. So even if the two objects' properties are equalavent, each object is stored in a different memory location. So JS tells us they aren't equal

When we initialize a new object by making it equal to another object, JS stores a reference to the second object's location instead of creating a whole new object. So, as far as JS is concerned, they are equal. This is important, because if you change a value of a property in either object, the change is reflected in both

screenshot
Fig 35- Compare objects

Functions

Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it

  1. Create a function that will take two parameters and return their product:
screenshot
Fig 36- Function definition
  1. And take it for a test drive:
screenshot
Fig 37- Function in action
  1. Let’s get a little more complex:
screenshot
Fig 38- F to C

The third line fixes the decimal precision to two places. It also returns the value of ‘c’ as a string (the toFixed() method returns a string value)

Using the 'chaining' feature of JavaScript, we could collapse the above function down to something smaller, if not necessarily more readable by doing this:
js function

  1. JavaScript has a number of built-in libraries. Math is one of them (for more complex mathematical operations and constants). One more function:
screenshot
Fig 39- .sqrt()

The parseFloat() method converts the string value returned by toFixed() into a number value
parseFloat()

  1. More functions in the JS Math library:

W3Schools lists a number of available operations and constants available in the Math library:

screenshot
Fig 40- JS Math library functions

Decisions, decisions!

In any programming language, the code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime

if

  1. Construct an if statement:
screenshot
Fig 41- if statement

if/else

  1. First, change the value of x:
screenshot
Fig 42- Change 'x'
  1. Then, add the if statement ...
  1. And add the else condition to it:
screenshot
Fig 43- Adding an 'else' condition

if/else if/else

  1. Let’s take else if out for a run:
screenshot
Fig 44- if/else if

Note that 'else' here defines a default condition. If, for some reason, none of the if/else if statements evaluate to true, the else statement returns at least something

switch

if...else statements do the job of enabling conditional code well, but they are not without their downsides. They are mainly good for cases where you've got a couple of choices, and each one requires a reasonable amount of code to be run, and/or the conditions are complex (for example, multiple logical operators). For cases where you just want to set a variable to a certain choice of value or print out a particular statement depending on a condition, the syntax can be a bit cumbersome, especially if you've got a large number of choices. Because of this, we have an alternative: switch

  1. Construct a switch statement. First, a new variable:
screenshot
Fig 45- fruit
  1. Create the switch:
screenshot
Fig 46- switch statement

Notice that there's a break; statement after each case is defined. This makes the interpreter 'break' out of the switch as soon as the first case evaluates to true. So all of the remaining tests don't have to be run

In my opinion, FWIW, any time you have multiple conditions to test against, a switch construct is much more elegant than if..else if..else if..else if......else

Loops

Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true

  1. JavaScript has a number of loop constructs. These are very similar to those in Java (syntactically, actually, they're the same)

for

  1. Let’s do a for loop:
screenshot
Fig 47- Simple for loop

We can declare the counter (i) inside the for loop - for (var i = 0; i < 10; i++) - but it's considered best practice to create variables first. If nothing else, it saves you from having to declare a counter for each and every for loop you run

When you're hip-deep in a 1000-line script, though, it's usually easier to just declare it on the fly

while

  1. How about a while loop?

First:

screenshot
Fig 48- Initialize counter

Then:

screenshot
Fig 49- Execute the loop

You really don’t want to forget to modify the test value in a while loop (or a do while loop)! I mention this because initially, I did. It crashed my browser, forcing me to use the Task Manager to shut it down and restart it

for/in

  1. Now, a for/in loop. First initialize i and create an empty string:
screenshot
Fig 50- Initialize i
  1. Then construct the loop:
screenshot
Fig 51- Execute the loop

The for/in loop iterates through all the properties in an object and stops. This way, we don't have to know ahead of time how many properties there are or worry about iterating too many times. This works with arrays, too (remember, JS treats arrays as objects)

Finishing up...

  1. Enter .save js-intro.txt

This is a Node.js directive that, believe it or not, will save your console session into a text file named js-intro.txt

  1. Upload js-intro.txt to the JS Intro folder on D2L
  1. If you’ve been wondering…I don’t know what <- undefined means either… 😊

Actually, now I do - the console displays the return value when a function (like console.log()) is executed. What <- undefined means is that the function has no return value

  1. Good times! Next time, we’ll use JS to create a lightbox!

Have a nice day 😊