Beginner
1. Outputs
JavaScript can "display" data in different ways: Alert box, write to document, write to HTML element and write to the console. Uncomment and execute each code to see what it does.
<!DOCTYPE html>
<html>
<head>
<title>Output</title>
</head>
<body>
<h1>Javascript Outputs</h1>
<div id="output"></div>
<script type="text/javascript">
//Alert box
window.alert("Hello World");
//Write to document
//document.write("Hello World");
//Write to HTML element
//document.getElementById("output").innerHTML = "Hello World";
//Write into the console
//console.log ("Hello World");
</script>
</body>
</html>
2. Data types
Strings
var carName = "Volvo XC60";
Numbers
var 2 = 30;
Arrays
var cars = ["Saab", "Volvo", "BMW"];
Objects
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Boolean
let value1 = true;
let value2 = false;
Null
const result = null;
3. Variables
Variables are containers for storing data (values).
var x = 5;
var y = 6;
var z = x + y;
4. Concatenation
The same + operator you use for adding two numbers can be used to concatenate two strings.
var message = "Hello";
var name = "James";
alert(message + " there," + " " + name);
5. Slice
var text = "Bread";
text.slice(0, 3);
6. Operators
Arithmetic
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
Comparison
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
Logical
&& and
|| or
! not
7. Functions
A function is a block of code designed to perform a particular task. A function is executed when "something" invokes it (calls it).
Declare and invoke(call)
function getMilk() {
console.log("leaveHouse");
console.log("moveRight");
console.log("moveLeft");
console.log("EnterShop");
console.log("payForMilk");
getMilk();
Parameters and arguments (local vars, placeholders)
Parameters - when declare/define and then arguments - when invoke/call/run
const bob = 'Bob';
const susy = 'Susy';
const anna = 'Anna';
function greet(name, second) {
console.log('Hello there ' + name);
console.log(second);
}
// greet bob
greet(4);
// greet anna
greet(anna, 'Bob');
// greet susy
greet('Susy');
Console
undefined
Hello there 4
Bob
Hello there Anna
undefined
Hello there Susy
Return The return statement stops the execution of a function and returns a value.
const wallHeight = 80;
function calculate(value) {
return value * 2.54;
}
const width = calculate(100);
const height = calculate(wallHeight);
const dimensions = [width, height];
console.log(dimensions);
Console logged
[ 254, 203.2 ]
8. Arrays
An array is a special variable, which can hold more than one value:
const friends = ['john', 'peter', 'bob', 'susy', 45, undefined, null];
let bestFriend = friends[2];
friends[4] = 'anna';
console.log(friends);
console.log(friends[4]);
console.log(bestFriend);
console.log(friends[3]);
Array methods
// Array Properties and Methods
let names = ['john', 'bobo', 'barry', 'olga', 'ben'];
//length
console.log(names.length);
console.log(names[names.length - 1]);
// concat
const lastNames = ['pepper', 'onion', 'banana'];
const allNames = names.concat(lastNames);
console.log(allNames);
// reverse
console.log(allNames.reverse());
//unshift
allNames.unshift('susy');
allNames.unshift('anna');
console.log(allNames);
//shift
allNames.shift();
allNames.shift();
allNames.shift();
allNames.shift();
console.log(allNames);
//push
allNames.push('susy');
console.log(allNames);
//pop
allNames.pop();
// allNames.pop();
// allNames.pop();
// allNames.pop();
console.log(allNames);
// splice - mutates original array
const specificNames = allNames.splice(0, 3);
console.log(specificNames);
console.log(allNames);
Intermediate
1. If-Else Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
2. While Loop
The while loop loops through a block of code as long as a specified condition is true.
while (i < 10) {
text += "The number is " + i;
i++;
}
3. For loop
for (var i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
4. Ternary Operator
// condition ? (runs if true) : (runs if false)
const value = 1 < 0;
value ? console.log('value is true') : console.log('value is false');
// if (value) {
// console.log('value is true');
// } else {
// console.log('value is false');
// }
4. HTML DOM Elements
Manipulate HTML elements. There are several ways to do this:
Finding HTML elements by id
Finding HTML elements by tag name
Finding HTML elements by class name
Finding HTML elements by CSS selectors
Finding HTML elements by HTML object collections
Advanced
1. Event Listeners
Event Handler to a document
document.getElementById("myBtn").addEventListener("click", displayDate);
Event Handler to an Element
element.addEventListener("click", function(){ alert("Hello World!"); });
2. Function Parameters and Arguments
Parameters are the names listed in the function definition. Arguments are the real values passed to (and received by) the function.
function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
3. Switch Statement
The switch statement is used to perform different actions based on different conditions.
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
4. Object Methods
JavaScript methods are actions that can be performed on objects.
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
5.String Methods
String methods help you to work with strings.
let text = " Peter Jordan";
let result = text.length;
console.log(result);
console.log(text.length);
console.log(text.toLowerCase());
console.log(text.toUpperCase());
console.log(text.charAt(0));
console.log(text.charAt(text.length - 1));
console.log(text.indexOf("e"));
console.log(text);
console.log(text.trim());
console.log(text.trim().toLowerCase().startsWith("peter"));
console.log(text.includes("eter"));
console.log(text.slice(0, 2));
console.log(text.slice(-3));
6, Callbacks
This technique allows a function to call another function
function myFirst() {
myDisplayer("Hello");
}
function mySecond() {
myDisplayer("Goodbye");
}
myFirst();
mySecond();