What to Expect
- Variables
- Comments
- Boolean Logic
- Loops
- Function
- Arrays
- Where can we write scripts?
- JQuery
A lot of this should be review from your Intro to Programming courses 120, 121, and 131 except in a different language.
Even though Javascript looks different from C++, logically it should be the same. So, I will briefly go over these concepts in this tutorial.
Variables
There are 5 primitive data types. They are all stored in a var object. So rather than doing
int number;
string word;
bool truth;
You would do
var number = 55;
var word = "word";
var word = 32.5; //changes it to a number
var truth = True;
The language is similar to python in that you can also like in the example above reassign variables with a completely different type. Similarly to every other language you can use any of the
I think at this point you would be wondering what the other two data types are they are undefined and null. Later I will discuss their usage.
With numbers you can use all the operators you are used to in C++, like %, /, *, +, and -
var number = 4; //number = 4
number += 2.5; //number = 6.5
number = 10%3; //number = 1
Similarly, strings manipulation is like C++
var hello = "hello world"; //double
var hi = 'hello world'; //and single quotes work
var test = "hello" + "world"; // you can combine 2 strings
var length = test.length;
var character = test[1]; //'e'
"hey"[1]; // "e"
"hello there".length // 11
Variables that are decalared but not initialized are labeled undefined. Whereas, variables have to be assigned ‘null’ to be ‘explicitly nothing’.
var iamnothing; //is undefined
iamnothing = null; //defined with null/nothing
Comments
If you haven’t noticed already comments are similar to that of C++
//I am a comment
/*
Hey,
I am a multiline comment!
*/
Boolean Logic
Here is a table of comparison operators. Most of them are also very similar to C++
Assume x = 5
Operator |
Name |
Example |
Result |
> |
Greater Than |
x > 10 |
false |
>= |
Greater Than or Equal to |
x >= 5 |
true |
< |
Less Than |
x < -50 |
false |
<= |
Less Than or Equal to |
x <= 100 |
true |
== |
Equal to |
x == ‘5’ |
true |
!= |
Not Equal to |
x != “b” |
true |
=== |
Equal value and type |
x === “5” |
false |
!== |
Not equal value or type |
x !== “5” |
true |
The last two operators are important since all variables are loosely typed. Each variable does not have a set type. That is why in javascript
5 == “5”
is true but
5 === “5”
is not.
Here is a table of logical operators. All of them should be familiar from C++
Assume x = 5 and y = 9
Operator |
Name |
Example |
Result |
&& |
AND |
x < 10 && x !== 5 |
false |
∥ |
OR |
y > 9 ∥ x == 5 |
true |
! |
NOT |
!(x == y) |
true |
Loops
While loops
Very similar to C++
while(condition){
//repeat code
}
For loops
Very similar to C++
for(initialize; condition; step){
//repeat code
}
Functions
The primary difference between C++ and Javascript is the lack of return type.
function functionName(argument list){
//some code
}
You can still return values in javascript even without the return type.
function functionName(argument list){
//some code
return "";
}
Arrays
Probably the only data structure you would use in Javascript.
Function |
What it does |
What does it return? |
push(value) |
adds “value” element to end of array |
N/A |
pop() |
removes last element in the array |
element removed |
unshift(value) |
adds “value” element to front of array |
N/A |
shift() |
removes first element in the array |
element removed |
indexOf(value) |
returns the value of the desired element or -1 if it does not exist |
index of desired element; or -1 if does not exist |
slice(start, end) |
returns elements from the start and end point specified of an array |
elements from the start and end point specified of an array |
splice(start, end) |
removes elements from the start and end point specified of an array |
elements from the start and end point specified of an array |
Here is a demo of some commonly used functions
var numbers = ["1", "2", "3"];
numbers.push("4");
//numbers = ["1", "2", "3", "4"]
numbers.pop();
//numbers = ["1", "2", "3"];
var value = numbers.pop(); //returns the removed value
//value = "3"
//numbers = ["1", "2"];
numbers.unshift("0"); //adds 0 to the front of the array
//numbers = ["0", "1", "2"]
numbers.shift();
//numbers = ["1", "2"]
value = numbers.shift(); //returns the removed value
//value = "1";
//numbers = ["2"]
numbers.unshift("1"); //adds 0 to the front of the array
//numbers = ["1", "2"]
numbers.push("3");
//numbers = ["1", "2", "3"]
numbers.push("4");
//numbers = ["1", "2", "3", "4"]
numbers.indexOf("1"); //0
numbers.indexOf("6"); //-1
var range = numbers.slice(1,3);
//range = ["2", "3"];
var all = numbers.slice();
//all = ["1", "2", "3", "4"];
//Both do not alter the original array (numbers)!
numbers.splice(1,1); //will remove the 2nd element
//numbers = ["1", "3", "4"];
Iterating
There are two ways to iterate through an array.
For Loop
Iterates through specified number of elements in an array.
var numbers = ["1", "2", "3"];
for(var i = 0; i < numbers.length; i++){
console.log(numbers[i]); // prints each element of the array
}
ForEach Loop
Iterates through each element of the array.
var numbers = ["1", "2", "3"];
numbers.forEach(function(number){
console.log(number); //prints each element in the array
});
Where can we write scripts?
There are several places where you can write scripts. You can create a script tag in the head area of an HTML document like so,
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
console.log("hello world");
</script>
<title>Home Page</title>
</head>
<body>
</body>
</html>
or (better)
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
</body>
<script type="text/javascript">
console.log("hello world");
</script>
</html>
You can also do inline scripting as well which is not recommended
<p onclick="alert('hey! notice me!')">pink colored text</p>
You can also place them in a Javascript file where you can create multiple functions you want the page to execute
var num = document.getElementById("number1").value;
var nums = document.getElementById("number2").value;
document.getElementById("alter").innerHTML = "The sum of the numbers is "+add(num, nums);
document.getElementById("alter2").innerHTML = "The difference of the numbers is "+subtract(num, nums);
function add(num1, num2){
return num1+num2;
}
function subtract(num1, num2){
return num1-num2;
}
Out of the three methods it is common convention to just use the last one. Only use the first two for testing purposes.
It is recommended you place all script tags at the bottom of the HTML file so right after the body tag, since the browser loads all the information by line order. If you are using javascript to alter your HTML, it won’t be able to change what it doesn’t know yet.
JQuery
Jquery is a popular javascript library that quickens and simplifies javascript code. If you’re interested in using it here is the JQuery Documentation
Here are a few examples:
document.getElementById("favorite");
document.getElementsByClassName("useful");
versus
$("#favorite"); //document.getElementById("favorite");
$(".useful"); //document.getElementsByClassName("useful");
How do I include JQuery?
We use either a Content Delivery Network or CDN for short which is a link online that serves content which in this case is the script file. Programmers generally use a CDN because users usually already have the CDN file link downloaded. Otherwise if your server is quick enough you can host the JQuery file locally by simply downloading the script file from their website. Make sure the JQuery file is included before your Javascript files or script tags.
Example
The html document
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!--Jquery CDN-->
<link rel="stylesheet" href="css/style2.css"/>
<title>Javascript Demo</title><!--Title of the page usually appears on tab-->
</head>
<body>
<img class="fade" src="https://i.imgur.com/6WrnLjg.jpg" height="100">
<img class="fade" src="https://i.imgur.com/BEzTVoj.jpg" height="100">
<img class="fade" src="https://i.imgur.com/ihSqFXz.png" height="100">
<img class="slide" src="https://i.imgur.com/aWmKefJ.jpg" height="100">
<img class="slide" src="https://i.imgur.com/CA54uGd.jpg" height="100">
<img class="slide" src="https://i.imgur.com/Z9dJKqw.jpg" height="100">
<div class="test">Click me!</div>
<BR><BR>
<button id="clickable">Click to Fade</button>
<button class="clickable2">Click to Fade</button>
Click this box and press some keys
<div id="play"></div>
</body>
<script src="js/script.js"></script>
</html>
.test {
color: #000;
padding: .5em;
width: 50%;
}
.inside {
background-color: black;
color: white;
}
.active {
color: #900;
}
The Javascript file
var button = document.getElementById("clickable");
$("#clickable").click(function() {
$(".fade").fadeToggle("slow", "linear");
});
$(document).keyup(function(event) {
if(event.keyCode == 68 || event.keyCode == 117) //Play around with your keys to see what keys activate the slide
$(".slide").slideUp("slow");
if(event.keyCode == 85 || event.keyCode == 100)
$(".slide").slideDown("slow");
});
$(document).keypress(function(event) {
document.getElementById("play").innerHTML += "<BR>You have pressed key "+ event.key;
});
//Recommended way
$(".clickable2").on( "click" ,function() {
$(".fade").fadeToggle("slow", "linear");
});
$( "div.test" ).on({
click: function() {
$( this ).toggleClass( "active" );
}, mouseenter: function() {
$( this ).addClass( "inside" );
}, mouseleave: function() {
$( this ).removeClass( "inside" );
}
});
Check it out here!
Try it for Yourself
Create a Javascript, CSS, and HTML document that implement the following:
- Include JQuery with a CDN
- Create a list of words starting with different letters of the alphabet (26 words)
- Create a button that toggles the slide feature with the vowel items items in a list
- Create a button that toggles the fade feature with consonant items in a list
- Create a div that shows the number of times the vowel and consonant button was pressed
- Have the created div have the same mouseleave, mouseenter, and click effect the example does
Back to CSS
References