How is JavaScript different?
JavaScript is a programming language that drives the web:
JavaScript is used on nearly every website in the world.
JavaScript drives the front end of giant web applications like Google Maps, Gmail, and Facebook.
Please read the Introduction and Chapter 1
JavaScript is used to make dynamic webpages interactive.
If you want to know more, click here.
Like other languages in computer science, JavaScript has the following tools that we will cover:
For front-end project, JS, like HTML and CSS, is run in the browser.
Other tools in the browsers (like APIs, that we will cover later) help make JS run wonderfully!
JavaScript is a programming language and, like any language, it has its own vocabulary and grammar.
Programmers call this syntax.
A programming language's syntax is the different commands, special words and punctuation you use to put together a program.
Every programming language has its own syntax, just as English, Spanish and Mandarin each have their own vocabulary and grammar.
Remember! ‘Java’ is not the same thing as ‘JavaScript’. They are two different languages. We will be learning JavaScript.
You can use JavaScript on a server?
JavaScript lets you add interactive components to a site like photo galleries, tabbed panels, or form validation.
JavaScript is used to build complex web applications, like GMail, Google Docs, and Google Maps.
JavaScript and Java are the same programming language.
What does "syntax" mean?
What do JavaScript, HTML, and CSS have in common?
Each instruction in JS is a "statement", like:
console.log('Hello World');
Each separate instruction in JavaScript is called a 'statement'. A 'simple' statement represents a single instruction and ends with a semi-colon.
Think of a simple statement like a sentence - the semi-colon is a full stop that tells JavaScript that your statement is complete.
The Developer Tools on Chrome has a JavaScript Console.
You can use JS Console to:
A common way to track what is happening in our programs is to use the following JavaScript statement:
console.log();
You can do basic math and other functions in the console.
For instance, type 2+2
and press enter
, the console should show you the number 4
.
Try it!
The console is where you will check to make sure that your program is running the way you want it to.
Let’s practice writing a command in JavaScript.
Open JS Bin or the Console, and in the JavaScript panel, write
alert();
alert()
is a method that opens a dialogue box or modal in your browser to display a message.
We write JavaScript programs by typing multiple JavaScript statements. Similarly, we write a paragraph by writing multiple sentences.
Use variables to store values.
Declare, then initialize in 2 statements:
var x;
x = 5;
console.log(x);
Or declare and initialize in one statement:
var y = 2;
console.log(y);
Re-assign the value later:
var z = 6;
z = 1;
Variables store information we need to use in the program. A variable is a named container for a value that can vary, a value that can change.
Variables only exist when they are 'declared', when we use the var keyword and the name of the variable. e.g. var z;
A variable declaration is a simple statement, so it ends with a semi-colon (;
).
Assigning an initial value to a variable is called initializing. e.g. z = 0; You can declare AND initialize in one go (e.g. var z = 0;), or seperately (e.g. var z; z = 0;). If a variable is not declared and initialized, then it is undefined
.
Variable names cannot have spaces if they have multiple words in them. If they do have multiple word, you should use camel case.
Camel case means that if you have two words, the first word does not have a capital letter but the subsequent words do).
var
var numPeople, $mainHeader, _num, _Num;
Not OK:
var 2coolForSchool, soHappy!
const
to declare a variable whose value will be constant; it cannot change. const
prevents the variable from being redeclared or reassigned.var
.
const annieCannonsCEO = "Laura";
var teachingTeam = "New Beginnings, Unicoders, WeMac Graduates";
Useful if you’re setting a variable that you do not plan on changing.
Protects and prevents your variables from reassignment.
In compiled languages, there is an increase in runtime efficiency of your code and thus an overall performance boost vs. using plain 'ol var
.
Let's try it in JS Bin!
var message = "Hello!";
alert(message);
message = "Hello! My name is Laura!";
alert(message);
When working with a browser (not a server), it looks for the index.html file to find links to CSS and JS files.
Use the script
tag and the src
attribute to link to your JS file. This tag goes in your HTML document in the head or body:
<script src="scripts.js"></script>
You can also insert JavaScript directly into a web page inside script
tags in the head section of your HTML:
<script>
alert("Hello there.");
</script>
You can also add it right before the closing body tag. Any idea why?
Variables can be populated with any one of the data types available in JavaScript.
A string is something that would be in quotes. A string is how you would represent text, like “Beyonce”. Strings ALWAYS need to be surrounded by quotes.
In your JS Bin, enter
console.log("Beyonce");
This will have your string logged into the console so that you can see it. Try it!
Semi-colons are an important part of the syntax and appear at the end of each statement (or the end of each line) in most of your JS.
Say you want to save your name (and remember, your name is a string) because we want to use it in the program you are writing.
You can use the keyword var
like this
var name = "Laura";
‘name’ will become a keyword in a program, and “Laura” is the value assigned to it.
Variables can also store the result of any "expression":
var name = 'Gaga';
var title = 'Lady';
var greeting = 'Hello';
var formalGreeting = greeting + ', ' + title + ' ' + name;
If you want to ask your user a question in a pop up window, you can use the prompt
command. It is similar to alert.
You use prompt and then generally follow that with a string.
prompt("What is your favorite food?");
Try making several prompts in JS Bin.
What is a way that we have learned to store the information for what the user types in?
var name = prompt("What is your name?");
console.log(name);
After we prompt our user to enter their name, we want to:
How would we add more text to their name?
We must add the string using the +
sign. Notice the spaces.
var name = prompt("What is your name?");
console.log("Hello " + name);
Combining strings is Concatenation. In JS, you combine strings with a +
operator: 'one string ' + ' another string'
A madlib is a word game where one player prompts others for a list of words to substitute for blanks in a story, before reading the story aloud.
Let’s create a madlib game for our users with the following sentence:
“There once was a [adjective] programmer who wanted to use JavaScript to [verb] with the [noun]."
When we get information from a user from a prompt or a web form, JavaScript stores the data as a string not a number.
Try it out:
var sunbutter = prompt("How many sunbutter sandwiches do you have?");
var ham = prompt("How many ham sandwiches do you have?");
var totalSandwich = sunbutter + ham;
console.log(totalSandwich);
What amount do you get?
Number()
command allows you to convert number strings into numbers.
var sunbutter = prompt("How many sunbutter sandwiches do you have?");
var ham = prompt("How many ham sandwiches do you have?");
var totalSandwich = sunbutter + ham;
How could we use this to get the right number of sandwiches? You need to change to:
var totalSandwich = Number(sunbutter) + Number(ham);
console.log(totalSandwich);
Numbers do not have quotation marks around them.
A number can be an integer (also called a whole number), such as 1, 2, -10
Or a decimal number (also known as a floating point),
such as 5.4324
Numbers CANNOT by letters or symbols, including commas.
Try it!
number
.Your JS code should look like this:
var number = 47;
console.log(number);
Mathematical operators in JS can be applied to numbers. Example: To add two numbers, use the addition operator (+).
var score = 200;
score = score + 100;
Most coders use mathematical shorthand for their code. Although you can use the four operators we learned, it is helpful to see others' code.
To add something to a variable you can write:
the variable +=
the numerical value you are adding
score += 100;
This will add 100 to the variable named ‘score
’ and is easier Thank always writing score = score + 100;
.
Create variables that store information about time.
var secondsPerMin =
var minsPerHour =
var hoursPerDay =
var daysPerWeek =
var weeksPerYear =
var answer = 4 * (6-2)
What happens when you log the result?
JS did the PEMDAS for you!
Business!
var wholesalePrice = 5.45;
var retailPrice = 9.99;
var quantity = 47;
var salesTotal = retailPrice * quantity;
var profit = salesTotal - (wholesalePrice * quantity);
Try it!
The Decade Supply Calculator
true
or false
. There can be only two values. true
or false
to represent anything that has two opposites or two possible states. Think of a light switch (on or off).boole
(named after the man who started using this concept) and assign it a value of true
or false
(no quotes needed), and then console.log()
the variable.It should look like this:
var boole = true;
console.log(boole);
An array consists of a list of items.
For example, you can create a list of:
Any data type can go into an array (e.g., numbers, strings, booleans, or a combination of all of these)
Arrays enable us to organize data and are used all over the web. User profiles, friends lists, hotel room availability, TV show listings, etc., are all organized using arrays!
Syntax: var numbers = [1, 2, 3, 4, 5]
For arrays, you will need to use the square braces [ ]
and put a comma between each item inside the braces. If the array is a list of strings, remember to use quotes! Example:
var states = ["California", "Texas", "New York"];
You should make three different arrays in your JS Bin that look something like this:
var arr = ["laura", "cool", "awesome"]; //arr is often short for array
var nums = [47,15,14]; //nums is often short for numbers
var favoriteFoods = ["pizza", "ice cream", "burgers"];
The great thing about arrays is that we can reference specific items in an array using their number indices.
Each item in an array is invisibly assigned a number.
JS uses zero indexing to assign the numbers, which means that the first item is indexed as a 0
and each subsequent item's index increases by one.
var array = ["hi", "bye", "cool"];
Item | hi | bye | cool |
---|---|---|---|
Index | 0 | 1 | 2 |
Once you know the number assigned to each item, you can write code that is specific to each.
Example: To log the third item in the array in the console:
console.log(array[2]);
The console will log the third item in the array: "cool".
If I wrote console.log(array); the console would print all three items in the array. ["hi", "bye", "cool"]
var classes = [];
classes[0] = 'HTML 101';
classes[1] = 'JS 101';
classes.push('JS 102');
classes.pop();
var i = 0;
classes[i]; // ??
classes[1];
classes.pop(); //??
classes.length;
Use the JavaScript console and/or JS Bin to debug!
Take the time to read error messages carefully; they will make more and more sense the more your practice. :)
Most programs do not run perfectly the first time. Learning how to debug is essential.
Read each of the error messages carefully; what are they telling us?
Read each of the error messages carefully; what are they telling us?
Warm Fuzzy Feeling
{}
to contain everything in the object, and you write the information vertically (a key-value pair for each line of code) as opposed to an array, in which you write horizontally (on one line of code).{}
, colons :
, and commas ,
)Example of an object
var myMeals = {
breakfast: "eggs",
lunch: "burger",
dinner: "spaghetti"
};
You can store things like details about a person.
var profileObj = {
name: "Laura",
city: "San Francisco",
favoriteNumber: 47,
favoriteFoods: ["chinese", "italian", "cajun"]
};
In JS Bin, create an object for a car.
For the key-value pairs, think of things you would want to know about a car.
It should look something like this:
var car = {
color: "black",
model: "mustang",
year: 1990,
features: ["radio", "seat warmers", "power windows"]
};
We assign a variable as an object with {}
. Example:
var angelTheCat = {};
We can assign a key-value pair to the object in a couple ways:
//DOT NOTATION
angelTheCat.furColor = "orange";
//OR
//LITERALLY
var angelTheCat = {
furColor : "orange"
};
We can use dot notation to access or add key-value pairs.
var angelTheCat = {};
angelTheCat.furColor = "orange";
var furVariable = angelTheCat.furColor;
furVariable; //??
angelTheCat.furColor = "grey";
furVariable; //??
We can use bracket notion to add key-value pairs, aka properties, to objects as well.
//BRACKET NOTATION: STRING AS KEY - Notice the use of quotes.
angelTheCat["fur color"] = "orange";
//BRACKET NOTATION: NUMBER AS KEY - Notice the absence of quotes.
var facebookFriends = {};
facebookFriends[12323] = angelTheCat;
We call this a collection. Each item in the array is an object.
var cuteCats = [
{ name: "Angel", age: 18, furColor: "grey" },
{ name: "Evil", age: 14, furColor: "red" },
{ name: "Meh", age: 12, "Fur Color": "white" }
];
cuteCats[0].name = ;//?
cuteCats[1].furColor;//?
cuteCats[2]["Fur Color"] = ;//?
var doll = {
size: "large",
innerDollOne: {
size: "medium"
}
};
doll.innerDollOne.innerDollTwo = {size: "small"};
console.log(doll);
Create an object to hold information on your favorite recipe. It should have properties for:
Create an animal object. Then use dot notation or bracket notation to add these properties:
For each property, decide whether it is best to use dot notation or bracket notation.
A line of code can be commented out with //
at the start.
Comments are very important when writing code. Lots of comments make it easier for people to understand the code.
Your code will also be easier for you to understand when you revisit it after some time has passed.
In JS Bin, create a variable for each of the five different data types we covered and assign them values.
Question: What are these data types again?
Please read Chapter 2
Variables can store different "types" of data, like:
var greeting = 'Hello World';
var restaurant = "Chipotle";
var myAge = 28;
var pi = 3.14;
var catsAreBest = false;
var dogsRule = true;
var arr = ["laura", 47, ["cat","dog"]];
var goodPickupLines = {};
var notDefinedYet;
var goodPickupLines = null;
It is always changing....
ECMAScript was created to standardize JavaScript. It is now the language that we are using when we implement our JS code. Each year, new features are released.
Lots of new tools were released....
Including new ways of declaring variables.
Thank you for your attention!