- Programming languages are written for humans
- They provide us with a mental model of the computer and a vocabulary
- Different models and vocabularies make sense for different applications
- JavaScript is a general-purpose programming language.
- It is loaded with html and css onto a page and run by the browser.
- It is the universal language for creating interactive web pages.
- It was designed by Brendan Eich in 1995 as a scripting language for Netscape Navigator (the predecessor to Firefox)
- Eich designed it in two weeks, drawing inspiration from languages both popular and obscure
- Because it powers the web, it has had an interesting trajectory
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="main.js"></script>
<title>Facts About Bears</title>
</head>
- Create a folder and put a new basic html file in it. Make sure to include
DOCTYPE
and all the standard parts of any html page. It does not need to have anybody
content. - Create a file called
main.js
. - In that file, type the following line, and be sure to save the file:
console.log("Hello, World!")
- Link your JS file to your html page: put a
script
tag with asrc
attribute that links to your javascript file in the<head>
element in your html document:<script src="main.js"></script>
- Load the html page in the browser.
- Open the javascript console in the developer tools. You should see
Hello, World!
printed there.
console.log('My name is', name)
- Data types
- Variables
- Conditionals
- Loops
- Functions
The way that a programming language expresses values.
For instance, think about how you place an order at a restaurant. How do you express the answer to each of these questions?
- How many eggs do you want? (2)
- How do you want them cooked? ('Sunny side up')
- Do you want a cup of coffee? (yes)
- String
"hello there!"
,'hello there!'
- Number
1
,200
,3.14159
- Boolean
true
,false
- Undefined
undefined
(has no value assigned) - Null
null
(has a value of nothing)
- These are what you expect, for when you need to do math
- Can do math with
+
,-
,*
,/
,%
, and**
- Can compare with
===
,!==
,>
,>=
,<
, and<=
-
+
,-
,*
,/
add, subtract, multiply, divide -
%
modulo The remainder of division.For example,9 % 2
equals1
-
**
power Raise x to the power of y. For example,2 ** 3
equals8
For when you need to represent characters/letters, words, sentences,
- "I have 5 pets"
- "0"
- ""
- "^&#O%@"
- "919-439-0215"
let something = 'This is just to have some valid JavaScript code here'
// single line comments in JS
/* a multi-line comment
looks like this */
let anotherThing = 'More random stuff just as a placeholder'
- Variables are a name given to a value
- One way to think of them is a box that holds a value
- Declare them with the keyword
const
orlet
- Variables delared with
let
can have a new value reassigned - You don't need to use the keyword
let
again when you reassign a value.
// variables declared with const cannot be reassigned
const width = 300
width = 400 // NOPE! You can't do this; you will get an error
const name = 'Dorian'
// variables declared with let can be reassigned
let points = 12
let paused = false
paused = true
points = 13
// here we declare and assign an initial value in one line
//this is also called initialization
let totalCost = 99.99
// We could also have done it in two steps:
let totalCost
totalCost = 99.99
=
is used to assign values to variables. There are shortcuts for using math and updating variables, though.
points += 5 // same as points = points + 5
points *= 2 // same as points = points * 2
points++ // same as points = points + 1
- Clone the following repo:
https://github.com/momentum-team-8/examples/tree/main/js-hello-world-exercise
- Open the repo in VS Code. You'll be working on the exercises in
main.js
. - Open
index.html
in your browser. - In the browser, open the dev tools and go to the JavaScript console by clicking on the "Console" tab.
- Work on exercises 1-8. Uncomment the necessary lines in each exercise as you work on it. When you make a change in the javascript file, save it and then reload the index.html page in the browser. You should see the
console.log()
output in the console.
In a computer language, a group of words, numbers, and operators that performs a specific task is a statement. We say a statement is "run" or "executed".
a = b * 2
a
andb
are variables. They will be evaluated.2
is a value*
and=
are operatorsb * 2
is an expression that will be evaluated.
Expressions are individual parts of a statement that are evaluated to produce a value. Statements are executed to make something happen.
- JavaScript programs are simply a sequence of statements to execute.
- The JavaScript interpreter (in the browser) executes these statements one after another in the order they are written.
- Another way to “make something happen” is to alter this default order of execution, and JavaScript has a number of statements or control structures that do just this:
- conditionals, loops, and jumps (stop or go back to where you were)
One of the most basic things we need to do in programming is say "if this thing is true, then do this other thing."
One of the most basic things we need to do in programming is say "if this thing is true, then do this. (And if it's not true, then don't do it.)"
Sometimes we also want to say "And if it's not true, then do that."
We use if and if/else statements for this.
if (points > 10) {
console.log('You win')
}
if (madeGoal) {
points = points + 2
console.log('You made a goal!')
madeGoal = false
}
if (points > 10) {
console.log('You win')
} else {
console.log('You lose')
}
if (predicate) {
codeBlock
} else {
otherCodeBlock
}
if (yourPoints > theirPoints) {
console.log('You win')
} else if (theirPoints > yourPoints) {
console.log('You lose')
} else {
console.log('You tied')
}
===
- equality!==
- inequality>
,>=
,<
,<=
- gt, gte, lt, lte
a = b //assigns the value of b to a
a === b // compares to see if a is equal to and the same type as b
Every value can act like a boolean. When a value is treated like a boolean, we say that it is either truthy or falsy.
A single expression or value can be used in a conditional:
if (value) {
// do something, because the value is truthy
} else {
// don't, because the value is falsy
}
0
-0
""
(an empty string)null
undefined
NaN
false
Everything that is not on the falsy list is truthy. That includes:
- "any characters in a string"
- "0"
- "false"
true
{}
(an empty object)[]
(an empty array)- any Number or negative Number
if (32) {
console.log('This is true!')
}
&&
and
||
or
!
not
let a = true
let b = false
a && b // a AND b have to be true for this expression to evaluate as true
a || b // a OR b have to be true for this expression to evaluate as true
!a // "not a": if a is true, then this will evaluate to false
!b // "not b": if b is false, then this will evaluate to true
The next basic thing we need to do in programming is repeat the same task over and over.
while
and for
are our tools for this.
// say hi 5 times
let count = 0
while (count < 5) {
console.log('Hi!')
count += 1
}
A while loop will run its code block as long as its predicate is true.
while (predicate) {
codeBlock
}
// say hi 5 times
for (let count = 0; count < 5; count++) {
console.log('Hi!')
}
A for loop combines its setup, predicate, and updating in one statement. It will run its code block as long as its predicate is true.
for (setup; predicate; update) {
codeBlock
}
- A for loop is for when you need to go through a limited list of numbers, always increasing (or decreasing) by the same amount, and ending at a specified point.
- A while loop is for everything else.
- You might think you'd use more while loops than for loops, but that's not usually the case.
let primeCount = 0
let currentNumber = 1
while (primeCount < 10) {
if (isPrime(currentNumber)) {
console.log(currentNumber, 'is prime')
primeCount += 1
}
currentNumber += 1
}
Note: this depends on a function named isPrime() that we don't have defined here.
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0) {
console.log(' Fizz')
} else if (i % 5 === 0) {
console.log(' Buzz')
} else {
console.log(i)
}
}
A function is a block of code that takes zero or more values and returns one value.
This block of code isn't executed immediately, but later when it is called.
- Chop an onion.
- Mince two cloves of garlic.
- Heat 1 teaspoon olive oil in a stockpot over medium-high heat.
- Add the onion and garlic and saute for 4 minutes.
- Add the rice and saute for 2 minutes.
- Add 1.5 cups of vegetable broth and boil the mixture.
- Lower the heat and cook for 20 minutes.
- Add the spices and 3.5 cups black beans.
- If the vegetable is an onion, peel back the papery skin and cut off the top.
- Cut the vegetable in half.
- Place each half cut-side down and slice the vegetable lengthwise in parallel cuts.
- Cut the vegetable with several horizontal cuts parallel to the board.
- Cut through the vegetable at right angles to the board.
- Each work in recipe vocabulary (chop, mince, saute, boil, etc) contains several sub-steps. These are functions!
- How you do each of these things is dependent on what you're doing it to (the arguments!)
You need to declare the function first.
function sayHello(name) {
return 'Hello, ' + name + '!'
}
Then you can call the function, which will actually run the code inside the curly braces.
sayHello('Charlie')
// Hello, Charlie!
- Function declarations: a block of code that you define once and then can "invoke," or "call," over and over from other places in your code.
- Declaring the function and calling the function are two separate steps.
- Declare a function with the
function
keyword. - The code inside the curly braces is executed when the function is called.
- To call a function, you need the name of the function and parentheses after it.
- Can optionally take arguments (aka parameters), which are values you give to the function when you call it. When your function needs to receive some outside information to run, you need an argument. Can have multiple arguments. The position of the arguments matters.
- Functions can optionally return a value back. To return a value from the function, you need the
return
keyword. return
also stops the function on that line and exits. Nothing in the body of the function after areturn
will be run.
function ordinal(num) {
if ((num > 3 && num <= 20) || (num < -3 && num >= -20)) {
return num + 'th'
} else if (Math.abs(num % 10) === 1) {
return num + 'st'
} else if (Math.abs(num % 10) === 2) {
return num + 'nd'
} else if (Math.abs(num % 10) === 3) {
return num + 'rd'
}
return num + 'th'
}
- Function arguments are like variables
- You can reassign them with new values
- If you pass variables to a function as arguments, they do not have to have the same name
let ballRadius = 10
let pi = 3.14159
function circleArea(radius) {
return pi * radius * radius
}
console.log(circleArea(ballRadius))
Create a javascript file and link it to an html page (or use one the you created earlier). In the js file, write four functions as described below. You should be able to call these four functions in the console.
- a function that takes a single argument and then logs that argument to the console.
- a function called sum with two parameters that returns the sum of those 2 numbers.
- a function called getLength that takes one argument (a string) and returns its length
- a function that takes a character as an argument (i.e. a string of length 1) and returns true if it is a vowel, false otherwise.
Variables have a scope -- a defined area of the code where they exist and can be used. If you define a variable outside of any code block (an area surrounded by curly braces), it is available throughout your code. If you define a variable within a code block, it is available in that code block and all code blocks nested under it.
// global scope
let name = 'Keelan'
let score = 0
if (score === 0) {
// new scope - name and score are available
let punctuation = '!'
printLoss(name, punctuation)
}
function printLoss(name, punctuation) {
// new scope - name and punctuation are available from the arguments,
// and score is available from the global scope
let message = 'You lose, ' + name + punctuation
console.log(message)
}
{"mode":"full","isActive":false}