Author(s): Hayden Smith
Because you already know C, we will teach Javascript very quickly and mainly focus on the differences between Javascript and C.
Unlike C, Javascript has a sprawling set of capabilities - the language will feel much bigger, and therefore you might feel you have a poorer grasp on it.
Don't expect to know everything about Javascript this term. Just focus on only learning what you need to solve a problem at hand, and you will learn more super quick.
Javascript is a high level multi-paradigm scripting language with a massive popularity in the web-based software engineering space.
Javascript has become the universal go-to language to build web-based applications, which is more and more becoming the primary way we consume end-user applications
const z = 3; function hello(a, b, c) { return `${a} ${b}`; }
1.4_intro.jsLearning another programming language is a very doable exercise, particularly if the language is from the same programming paradigm. Let's compare some languages.
Procedural | Object-oriented | Typed | Pointers | Compiled | |
C | Yes | No | Yes | Yes | Yes |
C++ | Yes | Yes | Yes | Yes | Yes |
Java | No | Yes | Yes | No | Yes |
Python | Yes | Yes | Can be | No | No |
Javascript | Yes | Yes | Can be | No | No |
Once you know a language from a paradigm, others are much easier.
In the case of learning another language like Javascript after doing COMP1511 with C, the main hurdles we have to overcome are:
Write a function that takes in two numbers, and returns the smaller number
int minimum(int a, int b) { if (a > b) { return b; } else { return a; } }
1.4_compare_1.cfunction minimum(a, b) { if (a > b) { return b; } else { return a; } }
1.4_compare_1.jsNow let's call the function and print the result!
Write a function that takes in two numbers, and returns the smaller number
#include <stdio.h> int minimum(int a, int b) { if (a > b) { return b; } else { return a; } } int main(int argc, char* argv[]) { printf("%d\n", minimum(3, 5)); }
1.4_compare_2.cfunction minimum(a, b) { if (a > b) { return b; } else { return a; } } console.log(minimum(3, 5));
1.4_compare_2.jsNow let's run the program
#include <stdio.h> int minimum(int a, int b) { if (a > b) { return b; } else { return a; } } int main(int argc, char* argv[]) { printf("%d\n", minimum(3, 5)); }
1.4_compare_2.cfunction minimum(a, b) { if (a > b) { return b; } else { return a; } } console.log(minimum(3, 5));
1.4_compare_2.jsOK but:
What is node
? 😵💫
Are there steps missing? 😰
NodeJS is a command line interface that interprets Javascript code within a runtime environment that is built on Google's V8 engine. 😵💫
Or if you want a simpler explanation...
NodeJS is the program that compiles and runs Javascript.
To really oversimplify it, NodeJS has a similar function to GCC.
NodeJS is what's known as an interpreted language instead of a compiled language. This means that the program is compiled and run as part of the same step.
This has two implication:
🤺 Performance V Convenience
But let's go and learn more about the language...
const
, let
, console.log
Run// Variables declared with "let" // can be modified after definition const years = 5; // Variables declared with "const" // cannot be modified after definition const name = 'Giraffe'; const age = 18; const height = 2048.11; const notexist = undefined; const existbutnothing = null; // You print with console.log console.log(years); console.log(name); console.log(height); // Double and single apostrophes are equivalent console.log('Hello!'); console.log('how are you?');
1.4_variables.jsConcatenation, string literals
Run// We can easily join strings together! let sentence = 'My'; sentence = sentence + ' name is'; sentence += ' Pikachu'; console.log(sentence); // If you need to mix variables and // strings, you can create a string literal const age = 7; const name = 'Hayden'; const phrase = `Hello! My name is ${name} and I am ${age}`; console.log(phrase);
1.4_strings.jsAlso come single & double apostrophe.
if
, else if
, else
, while
, for
.
const number = 5; if (number > 10) { console.log('Bigger than 10'); } else if (number < 2) { // Do nothing } else { console.log('Number between 2 and 9'); } console.log('--------------------------'); let i = 0; while (i < 5) { console.log('Hello there'); i += 1; } console.log('--------------------------'); for (let i = 0; i < 5; i++) { console.log('Hello there'); }
1.4_control_structures.jsVery similar syntax to C
function minimum(a, b) { if (a > b) { return b; } else { return a; } }
1.4_compare_1.jsWe'll now discuss two important data structures that are both collections of data. Collections can either be:
In sequential collections values are referenced by their integer index (key) that represents their location in an order.
In Javascript sequential collections are represented by an array. In Javascript, arrays are used for both C-style arrays and C-style linked lists.
In associative collections values are referenced by their string key that maps to a value. They often do not have an inherent sense of order.
They're kind of like C structs
, except the structure does not have to be defined at compile time.
name
→ "sally"
age
→ 18
height
→ "187cm"
Unpause, back to code!
Arrays are mutable ordered structures of the same type. We will not go into the depths of using arrays, since most of the semantics are things you are familiar with from COMP1511. However, we will look at the basic usage of arrays.
// This is a array const names = ['Hayden', 'Jake', 'Nick', 'Emily']; console.log(`1 ${names}`); console.log(`2 ${names[0]}`); names[1] = 'Jakeo'; names.push('Rani'); console.log(`3 ${names}`);
1.4_arrays.jsWe can use arrays with loops, too.
const items = ['a', 'b', 'c', 'd', 'e']; let i = 0; while (i < 5) { console.log(items[i]); i++; } for (let j = 0; j < 5; j++) { console.log(items[j]); } for (let k = 0; k < items.length; k++) { console.log(items[k]); }
1.4_array_basic.jsWe can use arrays with loops, too.
Runfunction getEvens(nums) { const evens = []; for (let i = 0; i < nums.length; i++) { if (nums[i] % 2 === 0) { // Why is this not == ?? evens.push(nums[i]); } } return evens; } const allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; console.log(getEvens(allNumbers));
1.4_functions.jsBecause Javascript is a higher level language, we have the ability to use a more concise and clear syntax when doing looping. You are not required to use this in the first few weeks of the course but we'd encourage all students to move toward this.
const items = ['a', 'b', 'c', 'd', 'e']; // prints 0, 1, 2, 3, 4 for (const i in items) { console.log(items[i]); } // prints a, b, c, d, e for (const item of items) { console.log(item); } console.log(items.includes('c'));
1.4_array_advanced.jsObjects are mutable associative structures that may consist of many different types. They are similar to C-style structs.
You can use them when you need a collection of items that are identified by a string description, rather than a numerical index (arrays).
const student = { name: 'Emily', score: 99, rank: 1, }; console.log(student); console.log(student.name); console.log(student.score); console.log(student.rank); student.height = 159; console.log(student);
1.4_objects.jsWe can create and populate objects different ways.
const userData = {}; userData.name = 'Sally'; userData.age = 18; userData.height = '187cm'; console.log(userData);
1.4_object_basic1.jsconst userData = { name: 'Sally', age: 18, height: '187cm', }; console.log(userData);
1.4_object_basic2.jsBoth of these programs would print { name: 'Sally', age: 18, height: '187cm' }
We can mix the two methods, and also use alternative syntax with assigning.
Or in a more full example.
// You can assign more keys even // after creation const userData = { name: 'Sally', age: 18, }; userData.height = '187cm'; console.log(userData);
1.4_object_more1.js// You can reference keys with either // obj.key or obj['key'] const userData = {}; userData.name = 'Sally'; userData.age = 18; userData.height = '187cm'; console.log(userData);
1.4_object_more2.jsWe can also get various properties of an object using the Object
functions.
const userData = { name: 'Sally', age: 18, height: '187cm', }; const keys = Object.keys(userData); const entries = Object.entries(userData); const values = Object.values(userData); console.log(keys); console.log(entries); console.log(values);
1.4_object_props_1.js[ 'name', 'age', 'height' ] [ [ 'name', 'Sally' ], [ 'age', 18 ], [ 'height', '187cm' ] ] [ 'Sally', 18, '187cm' ]
We can also loop through objects and check if certain keys are in them.
const userData = { name: 'Sally', age: 18, height: '187cm', }; for (const key in userData) { console.log(key); } if ('name' in userData) { console.log('Has name key'); }
1.4_object_props_2.jsname age height Has name key
The following code exhibits behavior you're probably not used to:
const arr = [1, 2, 3]; console.log(arr.length); console.log(arr.includes(3));
1.4_object_model.js"arr" is an array, but it also seems to have:
length
that we never set?Let's look at why this is.
To oversimplify: It's structs with functions
Let's try some lists of objects.
const userData = [ { name: 'Sally', age: 18, height: '186cm', }, { name: 'Bob', age: 17, height: '188cm', }, ]; const keys = Object.keys(userData); const entries = Object.entries(userData); console.log(keys); console.log(entries);
1.4_object_loop1.js[ 'name', 'age', 'height' ] [ [ 'name', 'Sally' ], [ 'age', 18 ], [ 'height', '187cm' ] ] [ 'Sally', 18, '187cm' ]
Let's try some lists of objects.
const userData = [ { name: 'Sally', age: 18, height: '186cm', }, { name: 'Bob', age: 17, height: '188cm', }, ]; for (let i = 0; i < userData.length; i++) { console.log(`${userData[i].name}'s properties are:`); console.log(` name: ${userData[i].name}`); console.log(` age: ${userData[i].age}`); console.log(` height: ${userData[i].height}`); }
1.4_object_loop2.jsLet's try some lists of objects.
const userData = { Sally: { age: 18, height: '186cm', }, Bob: { age: 17, height: '188cm', }, }; for (const key in userData) { console.log(`${key}'s properties are:`); for (const key2 in userData[key]) { console.log(` ${key2}: ${userData[key][key2]}`); } }
1.4_object_loop3.jsSally's properties are: age: 18 height: 186cm Bob's properties are: age: 17 height: 188cm
Let's try more lists of objects.
const student1 = { name: 'Hayden', score: 50 }; const student2 = { name: 'Nick', score: 91 }; const student3 = { name: 'Emily', score: 99 }; const students = [student1, student2, student3]; console.log(students); // Approach 1 const numStudents = students.length; for (let i = 0; i < numStudents; i++) { const student = students[i]; if (student.score >= 85) { console.log(`${student.name} got an HD`); } } // Approach 2 for (const student of students) { if (student.score >= 85) { console.log(`${student.name} got an HD`); } }
1.4_combining.js