Intro to JavaScript
04.28.18 ∙ GDI MPLS ∙ Amy Gebhardt
Wifi
Network: OLSONHQguest
Username: Olson
Password: guest
Welcome!
Who are you?
What do you do?
Do you have any experience with JavaScript or programming?
Slides
https://gdiminneapolis.github.io/intro-to-js/day-one/index.html
After today, you will:
Be able to define JavaScript.
Understand basic programming concepts such as:
Variables & data types.
Functions.
Conditional statements.
Loops.
Arrays.
What is JavaScript?
A client-side
processing language.
The browser reads and executes the code.
Works with HTML and CSS.
Let's you build dynamic
web pages that respond to user input.
Your first JavaScript code.
Set up some project files:
If you have not done so yet, download our project files from: https://gdiminneapolis.github.io/intro-to-js/
Open Atom or Sublime Text, then open your gdiIntroToJS directory.
Open this file in Google Chrome. Anything exciting?
Add your JavaScript to the <head> & save again:
Refresh your page in Google Chrome. Anything exciting now?
Wait, so what did we just do?
We used a function named alert.
We gave the function a string parameter: "hello world".
For now, just keep in mind that:
JavaScript must be written within <script> </script> tags.
Using window.alert() is a quick way to output data.
Just like with CSS, you can put your JavaScript into separate files.
JavaScript files have a "js" extension.
Confirm that you see a scripts.js file in your gdiIntroToJS directory.
Open index.html, and remove the <script> tag and its contents.
Just above the </body> tag, add a new <script></script>
with a src attribute
linking to your scripts.js file.
Your index.html should now look like (don't forget to save!):
Refresh your page in Google Chrome. Any guesses on what we'll see?
Open to scripts.js and add the following line:
Save the file, then refresh your page in Google Chrome.
Any guesses on what we'll see?
Now we know 2 ways of displaying
data in JavaScript.
The last one (for now) requires us to use our "dev tools".
Open your Google Chrome DevTools.
View -> Developer -> Developer Tools
Open the "console" tab
Or, if you prefer shortcuts:
Mac: Command + Option + J
Windows: Control + Shift + J
Let's get familiar with our dev tools.
These tools - specifically the console - is your new best friend.
Debugging just got a whole lot easier.
More good news:
JavaScript has errors!
Return to scripts.js and add the following line:
Save the file, then refresh your page in Google Chrome.
Any guesses on what we'll see?
Return to scripts.js and remove the
line with our intentional bug.
Save the file, then refresh your page in Google Chrome.
Any guesses on what we'll see?
Now we know 3 ways of displaying
data in JavaScript. We used...
We'll dive into the details of what these are actually doing
a bit later, just keep them in your back pocket for now.
Programming languages use a set of rules
for correct structure. This is called SYNTAX.
Incorrect syntax will cause ERRORS.
Syntax varies significantly from language to language.
JavaScript syntax requires each
statement to end with a semicolon.
Just like other languages, JavaScript allows you to leave comments within the code.
Comments are ignored when the code is run.
In JavaScript, there are 2 ways to write a comment:
A VARIABLE stores values.
It can hold different types of information, like
words and numbers. These are called DATA TYPES
and there are quite a few of them.
The value can change.
A variable can have a null value
which means it is not currently storing anything.
A VARIABLE stores values.
When you create a variable you DECLARE it.
A variable has an undefined value
if it is declared without setting a value.
New variables must have a unique name.
Variable names can only contain letters, numbers, $, or _.
Variable names cannot begin with a number.
Best Practices
"You should not be able
to tell who wrote the code."
Code can have bad style, but have correct syntax.
If you prefer a style that isn't widely accepted, have a reason for it.
Be consistent within your own code.
Today, I'm going to stick as close to the common standard as possible.
In JavaScript (and several other languages), variable names can follow different naming conventions:
Camel Case: thisIsAnExample
Pascal Case: ThisIsAnExample
Underscores: this_is_an_example
First Name |
Amy |
Twitter Handle |
@amlyhamm |
Birthday Month |
8 |
Love for JavaScript |
9.99993 |
Is a developer? |
Yes |
Let's start with First Name
Come up with a name for the variable.
Declare it using proper syntax.
Right now, firstName has an undefined value.
Initialize firstName with a value:
Note that the value is in quotes.
This is because the value is a STRING
and therefore
firstName is a string.
DATA TYPES we'll be working with for this example include:
First Name |
Amy |
Twitter Handle |
@amlyhamm |
Birthday Month |
8 |
Love for JavaScript |
9.99993 |
Is a developer? |
Yes |
To declare and initialize
each of these it could look like:
To use your variables, simply refer to the name of the variable in your code:
Let's try it!
Return to your scripts.js.
Create a variable.
Give it a valid name and a value.
Display the value.
OPERATORS are used to perform arithmetic between variables.
The variables' DATA TYPE will
determine what the operator actually does.
When used on numbers:
a + b |
Addition |
Sum of a and b |
a - b |
Subtraction |
Difference of a and b |
a * b |
Multiplication |
Product of a and b. |
a / b |
Division |
Quotient of a and b |
a % b |
Modulus |
Remainder of a divided by b |
a++ |
Increment |
Increases a by 1 |
a-- |
Decrement |
Decreases a by 1 |
Let's try it!
Return to your scripts.js.
Create 3 variables with valid names
and integer or float values.
Try some arithmetic operators.
Display your results!
The + operator can be used to perform concatenation between string variables.
you can also use += to add to the end of a string:
Let's try it!
Return to your scripts.js.
Create 3 variables with string values: a first name, middle initial, and a last name.
Put them together to make a full name.
Display your results!
A FUNCTION is a reusable block of code designed to perform a particular task.
It is INVOKED when something calls it.
Functions have NAMES and are DECLARED like variables.
An example of a FUNCTION:
Functions can accept arguments.
These parameters are part
of the function's signature.
You can use variables as ARGUMENTS.
Let's try it!
Return to your scripts.js.
Create a function named getBirthday that
accepts 3 parameters: month, day, and year.
Have the function display a
birthday date, based on the arguments.
Call the function to display your results!
Functions can RETURN values.
Returning will immediately end the function.
Let's try it!
Return to your scripts.js.
Have your getBirthday function return the result (instead of just displaying).
Call the function and set its
return value to a new variable.
Display that value of that variable.
scope is the set of variables and functions you have access to.
Scope can be global and local.
Variables declared within a function become local to the function.
This means they can only be accessed within the function.
They are deleted when the function is completed.
Function parameters work as local variables.
Variables declared outside a function become global.
This means they can be accessed
by all scripts and functions on a web page.
They are deleted when you close the web page.
If you assign a value to variable that has not been declared, it will automatically become a global variable.
Which variables have global scope?
Which variables have local scope?
Let's try it!
Return to your scripts.js.
Create a variable that has local scope.
Try to access it from outside of its scope.
What happens?
conditional statements are used to execute different blocks of code based on conditions.
The syntax looks like this:
This is where our boolean data types will come in handy.
We'll use a bunch of comparison operators with conditional statements.
a == b |
Equal |
true if a and b have the same value. |
a === b |
Identical |
true if a and b have the same value and the same type. |
a != b |
Not equal |
true if a and b do not have the same value. |
a !== b |
Not identical |
true if a and b do not have the same value or do not have the same type. |
a < b |
Less than |
true if a is less than b. |
a > b |
Greater than |
true if a is greater than b. |
a <= b |
Less than or equal to |
true if a is less than or equal to b. |
a >= b |
Greater than or equal to |
true if a is greater than or equal to b. |
Pay special attention to the ==/=== operators! It's easy to want to use =,
but that assigns a value, it doesn't compare a value.
The else statement is a block of code executed if the condition is false.
The syntax looks like this:
Let's try it together!
What will be logged in the console?
Use the else if statement to
specify a new condition if the previous condition is false.
The syntax looks like this:
Let's try it!
Return to your scripts.js.
Create a variable named age & give it a float value.
Try a bunch of different values for age and display each result.
logical operators determine what happens between variables or values.
Given that:
&& |
And |
(a < 3) && (b == 2) |
true |
|| |
Or |
(a == 5) || (b == 5) |
false
|
! |
Not |
!(a == b) |
true
|
Now you can combine conditions!
This can be simplified. Any ideas?
A while loop will repeat the same block of code over and over again until the condition is met.
The syntax looks like this:
How many times will the block of
code within the loop be executed?
An infinite loop occurs when the condition to break out of the loop can never happen.
A for loop will repeat the same block of code over and over until the counter condition is met.
The syntax looks like this:
Brief detour...
var; // what we've been using; behavior can feel unpredictable; older standard
let; // block-scoped; value may be reassigned; newer standard
const // block-scoped; can not be reassigned; newer standard
What will the value of lyrics be?
Let's step through it together.
To exit a loop before the condition is met, use the break statement.
How many times will the loop be executed?
When i === 105, the loop will break (the 6th execution)
Let's try it!
Return to your scripts.js.
Write a loop that gives you the 9's times table, so your output looks like:
Finish early?
Write a loop that will display the times table for numbers 1-12. The output looks like: