Week 06 (Javascript)
Variables
A variable is a named container for a value that is used to store, manipulate and retrieve data.
let quantity = 3;
console.log(quantity);
The name of a variable can be anything as long as it is meaningful.
- Each variable must have a unique name.
Statements
console.log('Welcome!');
Like C#, Javascript statements must end with a semi-colon.
Datatypes
There are 3 primitive data types in javascript:
- Numbers: Floating point numbers, decimals and integers
- No quotes are required
- Strings: Sequence of characters, text
- Enclosed in quotes
- Booleans: Logical data (true or false)
- Either
trueorfalse, no quotes.
- Either
There are 2 other primitive data types:
- Undefined: Data type of a variable that does not value yet
- Null: Self explanatory
// Syntax
// let name = <value>;
// Numbers
let x = 1;
// Strings
let myName = "Bob";
// Boolean
let myName = true;
// Array
let myName = [1,2,3,"hi"];
Dynamic Typing
Javascript can figure out the datatype. Datatypes can also be changed later.
String Processing
Concatenation
let greeting = 'Howdy';
let name = `Molly`;
let message = greeting + name;
// message = "HowdyMolly"
Length of String
"My name".length // = 7, spaces are also counted
"".length // = 0
Case Manipulation
"my name".toUpperCase(); // Returns "MY NAME"
"MY NAME".toLowerCase(); // Returns "my name"
Other Examples
trim()replace()charAt()substring()indexOf()
Template Literals
Template literals in javascript are enclosed by the back-tick (`).
They can extend across multiple lines.
Why?
- String substitution
- Cleaner
- More readable
// Usual method of writing strings
var age = 21;
console.log('My age is ' + age);
// Substitution using Template String
var age = 21;
console.log(`My age is ${age}`);
Comparison Operators
Strict Equal To (===)
This operator compares two values to check that both the datatype and value are the same.
- '8' === 8 returns false
- They are not the same data type
- '8' === '8' returns true
- They are the same data type and value
Strict Not Equal To (!==)
Opposite of ===.
Is Equal To (==)
This operator compares two values to see if they are the same.
- 'Hello' == 'Goodbye' returns false
- They are not the same value
- 5 == '5' returns true
- They have the same value despite different data types
Is Not Equal To (!=)
Opposite of ==.
Greater Than (>) & Less Than (<)
Same application as with mathematics, applies to <= and >= as well.
Rounding Numbers
To round off numbers, use Math.round(x);
Logical Operators
Logical Operators allow you to compare the results of more than one comparison operator.
- Logical and =
&& - Logical or =
||
Repetition
- Loops check a condition. If the condition returns true, a code block will run. The condition will be checked again and if still remains true, the code block will run again. This cycle repeats until the condition returns false.
- Each time we perform a loop action, it is called an iteration.
- Loops provide a way to repeat the same set of actions over and over again.
For Loops
// Syntax
// for (initialisation; condition; increment/update)
for (let i = 0; i < 10; i++) {
console.log("Practice:" + i);
}
While Loops
let i = 0;
while (i < 10) {
console.log("Practice:" + i );
i++;
}
Arrays
Arrays help us avoid having many variables of different names.
- Instead of variables "name1", "name2", "name3", an array called "names[]" can be used.
Arrays in JavaScript can store mixed data types (strings, numbers, boolean, etc)
Common Methods and Properties
| Method | Description |
|---|---|
pop() | Removes the last element in an array and returns that value |
push() | Adds new elements to the back of the array and returns the new length |
shift() | Removes the first element in an array and returns that value |
unshift() | Adds new elements to the front of the array and returns the new length |
splice(a,b,<elements>) | - a defines position where new elements are added - b defines how many elements to be removed - <elements> define new elements to be added |
sort() | Sorts array alphabetically |
indexOf() | Search the array for an element and returns it position |
| Property | Description |
|---|---|
length | Returns the number of keys |
Defining Arrays
let list=[];
list[0] = "First";
list[1] = "Second";
let list=["First", "Second", "Third", "Fourth"];
You can skip indexes in an array.
let list=[];
list[0] = "a";
list[26] = "z";
All values skipped are filled with undefined.
Associative Arrays
Normal arrays use integers as the index. However, associative arrays use strings as the index.
- In an associative array, the index is often known as the key.
Basically acts like a dictionary
Functions
Functions allow you to group a series of statements together to perform a specific task.
- They are reusable, and save you from writing out the same code over and over again.
Declaring a Function
function sayHello() {
document.write(`Hello`);
}
sayHello();
function getArea(width, height) {
return width * height;
}
getArea(3, 5);
Object Oriented Programming (OOP)
Objects group together a set of variables and functions to create a model.
- Similar to classes in C#
Literal Object Example:
let hotel = {
name: 'Raffles Hotel',
rooms: 100,
booked: 24,
gym: true,
roomTypes; ['twin', 'suite', 'deluxe'],
checkAvailability: function() {
return this.rooms - this.booked;
}
}
Accessing Objects
let hotelName = hotel.name;
let roomsFree = hotel.checkAvailibility();
let hotelName = hotel['name'];
let roomsFree = hotel['checkAvailibility']();
Updating Objects
hotel.name = 'Favecho Royale Hotel';
hotel['name'] = 'Favecho Royale Hotel';
delete hotel.name; // deletes property
hotel.name = '' // clears the value of a property
Function-Based objects
Creating a function-based object allows it to be used as a template for creating multiple objects.
function Hotel(name, rooms, booked) {
this.name = name;
this.rooms = rooms;
this.booked = booked;
this.checkAvailability = function() {
return this.rooms - this.booked;
};
}
let favchoHotel = new Hotel('Favecho Hotel', 100, 25);
let lizzieHotel = new Hotel('Lizzie Inn', 48, 12);
The this keyword is used instead of the object name to indicate the property/method belongs to the object that this function creates.
Literal VS Function-Based Objects
Literal Objects:
- Has no constructors
- Cannot be inherited
- Best used for "one-off" objects where only one copy will exist
- A colon separates the key/value pair
- For global or configuration objects like game settings
Function-Based Objects:
- Has a constructor
- Can be inherited (not covered yet)
- Best used for objects that you want to instantiate more than once
thiskeyword is used instead of object name- For objects with similar functionality
var, let, const
var
Variable declaration using var is treated as though they are at the top of the function (or global scope if they are declared outside of a function), regardless of where the actualy declaration occurs. This is known as hoisting.
varalso allows us to re-declare a variable.
function getValue(hasValue) {
if (hasValue) {
var value = "blue";
return value;
} else {
console.log(value);
return null;
}
console.log(value);
}
// How the JS engine inteprets the above code
function getValue(condition) {
var value;
if (condition) {
value = "blue";
return value;
} else {
return null;
}
}
let
let is block-scoped, meaning it only exists within the braces ({...}) it is contained in.
letdoes not allow us to re-declare a variable.
function getValue(hasValue) {
if (hasValue) {
let value = "blue";
// value only exists here
return value;
} else {
console.log(value); // value does not exist here
return null;
}
console.log(value); // value does not exist here
}
const
Variables declared using const are considered constants, which means their values cannot be changed once set.
- This means that ever
constvariable must be initialised on declaration.
const grade = 'AD';
const grade; // this gives an error
Declaring Objects Using const
const student = {
name: 'Joshua',
age: 18
}
student.name = 'Sean'; // Changing a property works
student.mate = 'Nigel'; // Adding a new property works
// this fails as we cannot change the information that an object is bound to
student = {
name: 'Scott',
age: 21
}
A `const' declaration prevents modification of the binding and not of the value itself.
for ... of Loop
let dailyExpenses = [29, 81, 43];
for (let expense of dailyExpenses) {
expense *= 2;
console.log("Expense:" + expense);
}
Similar to for...each loop in C#