Console.log output

This Code cell outputs a string stored in a variable.

var text = "Hello World";
console.log(text);
Hello World

Function

This code cell uses a function to outputs a string.

function Print(Text) {
    console.log(Text);
}
Print(text);
Hello World

Data types

This code cell demonstrates the different data types in JavaScript by outputting them with a function.

function PrintType(output) {
    console.log(typeof output, ", ", output);
}
PrintType("string");
PrintType(1);
PrintType(true);
PrintType(["A","B","C"]);
string ,  string
number ,  1
boolean ,  true
object ,  [ 'A', 'B', 'C' ]

Operators

var addition = 1+1;
console.log(addition);

var subtraction = 1-1;
console.log(subtraction);

var multiplication = 1*2;
console.log(multiplication);

var division = 1/2;
console.log(division);

var modulus = 3%2; // division remainder
console.log(modulus);
2
0
2
0.5
1

Classes

  • function allows for gathering data, the function "Person" collects a name, age, residence, and role
  • prototype allows for associating methods to a function,the prototype "setRole" allows for you to change the data type "role" in the function "Person"
// define a function to hold data for a Person
function Person(name, age, residence) {
    this.name = name;
    this.age = age;
    this.residence = residence;
    this.role = "";
}

// define a setter for role in Person data
Person.prototype.setRole = function(role) {
    this.role = role;
}

// define a JSON conversion "method" associated with Person
Person.prototype.toJSON = function() {
    const obj = {name: this.name, age: this.age, residence: this.residence, role: this.role};
    const json = JSON.stringify(obj);
    return json;
}

// make a new Person and assign to variable student
var student = new Person("Ryan", 16, "SanDiego");  // object type is easy to work with in JavaScript
PrintType(student);  // before role
PrintType(student.toJSON());

// output of Object and JSON/string associated with student
student.setRole("Student");   // set the role
PrintType(student); 
PrintType(student.toJSON());
object ,  Person { name: 'Ryan', age: 16, residence: 'SanDiego', role: '' }
string ,  {"name":"Ryan","age":16,"residence":"SanDiego","role":""}
object ,  Person { name: 'Ryan', age: 16, residence: 'SanDiego', role: 'Student' }
string ,  {"name":"Ryan","age":16,"residence":"SanDiego","role":"Student"}