No homework this week! We're still getting CMS/Piazza set up
- Commonly used in conjunction with HTML/CSS
- Became really popular for powering client-side logic through AJAX
- Previously, languages like PHP had to communicate with the server before coming back with a response
There are three ways to create variables in JS:
var x = 5
let x = 5
const x = 5
We prefer using const for immutability although let is also accepted. Never use var.
We can use
for..of loops to loop through elements of an array.
We can use
for..in loops to loop through keys of an object.
We can use the function key word to define a function!
or we can use arrow functions:
More details on arrow functions in a few weeks when we talk about ES6!
TypeScript allows us to add type information!
x, s, b? What should I pass in for those? What should I expect returned?
Adding the TypeScript types makes this code self-documenting:
None of these variables have to be any specific type! I can have
str be a string and then a number.
In the end, we want to use TypeScript because it is:
- Easier to read
- Easier and faster to implement
- Easier to refactor
- Less buggy
We can also use
const but again no
Any is a wildcard and it can be anything.
any places no restrictions on type.
If you were to use
But it can be useful in specifying collections of items of different types!
Functions can have types too!
myFunc has type
(x: number, y: number): number.
TypeScript can do some limited type inference so if you leave out the return type
number, TypeScript can infer it since we are just adding two numbers which can only produce a number. If TypeScript can't infer the type, it defaults as
We can also have optional parameters:
github as an optional parameter that defaults to
Literal Types are types that can be a literal set of possibilities that you specify. TypeScript allows number and string literal types:
Any variable with
TrafficLightColors type can only take on values
"red", "green", "yellow".
With union types, a variable can be of one type or another type.
With union types, a variable must be of one type and another type.
There's also so much more to TypeScript. Checkout TypeScript docs to learn more! https://www.typescriptlang.org/docs/
We went through a demo of writing and running code in TypeScript using the preassessment as an example. First install
We used the following example code:
Run it with