Front-End - JavaScript Part 1
Front-End - JavaScript Part 1
What is JavaScript? JavaScript is a scripting language that enables you to create dynamically updating
content, control multimedia, animate images, and pretty much everything else. (Okay, not everything, but
it is amazing what you can achieve with a few lines of JavaScript code.)
Primitive Types
Primitives are the simplest elements available in a programming language. A primitive is the smallest 'unit
of processing' available to a programmer of a given machine, or can be an atomic element of an
expression in a language.
JS Numbers
-JS has one number type
-Positive numbers, negative numbers, whole numbers (integers), decimal numbers.
Ex. 0/0
1 + NaN
Typeof Operator
-The typeof operator returns a string indicating the type of the unevaluated the operand.
Basic Syntax
let sample = value;
Ex:
let year = 1993;
year + currentAge;
let age = year + currentAge;
age = age + 1;
Updating Variables
let score = 0;
score = 10;
score = score + 10;
shorter way
score += 10;
score -= 20;
Booleans
True or False / Yes or No values
Naming a variable: camelCase(commonly used) or snake_case, no digit on the first char. Make sure that
the variable name represents the value.
String
-“String of characters.” Strings are another primitive type in JS. They represent text, and must be wrapped
in quotes.
- You can use double quotes or single quotes.
Indices
STRING ARE INDEXED
STRINGS
0123456
-each character has a corresponding index (a positional number)
Concatenation
“Aldrin John “ + “Tamayo”
let fname = “Aldrin John”;
let lname = “Tamayo”;
fname + lname;
String Methods
-Methods are built-in actions we can perform with individual strings
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
syntax: thing.method()
//To trim – will trim all the white space at the beginning and at the end of the string
let msg = " Hello World! ";
msg.trim();
Chaining methods
msg.trim().toUpperCase();
Syntax: thing.method(arg)
indexOf()
-The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it
is not present.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString
slice(startOfIndex, endOfIndex)
-method extracts a section of a string and returns it as a new string, without modifying the original string.
can accept more than 1 argument.
let name = "Aldrin John Tamayo";
name.slice(0, 6);
replace()
-method returns a new string with some or all matches of a pattern replaced by a replacement.
name.replace("Aldrin", "Coach");
let newName = name.replace("Aldrin", "Coach");
Template Literals
-are strings that allow embedded expressions, which will be evaluated and then turned into a string.
[This is annoyng]
${}, whatever I put inside the curly braces will be treated as an expression and will be evaluated.
`Math ${1 + 2 + 3}`;
Undefined
–Variables that do not have an assigned value.
let x;
Null
–Intentional absence of any value. Must be assigned.
let player = "aj";
player = null;
Math Object
-contains properties and methods for mathematical constants and functions.
Math.PI
Math.round(8.9) rounding a number
Math.abs(-1) absolute value
Math.pow(3, 3) raise
Math.floor(4.99) this will remove the decimal
JS Decision Making
Comparison Operators
-are used in conditional expressions to determine which block of code executes, thus controlling the
program flow. Comparison operators compare two values in an expression that resolves to a value of true
or false.
https://www.w3schools.com/js/js_comparisons.asp
console.log();
-is a function in JavaScript which is used to print any kind of variables defined before in it or to just print
any message that needs to be displayed to the user.
alert();
-this function will display text in a dialog box that pops up on the screen.
alert(“Test”);
prompt();
-this function will display text in a dialog box that pops up on the screen.
Or
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
console.log("Hello!");
alert("Test");
Conditional Statements
If Statements
-Only runs code if given condition is true.
-The IF statement is a decision-making statement that guides a program to make decisions based on
specified criteria. The IF statement executes one set of code if a specified condition is met (TRUE) or
another set of code evaluates to FALSE.
if (1 + 2 === 3) {
console.log("Equal");
}
Else If
-If not the first thing, maybe this other thing???
-The if/else statement executes a block of code if a specified condition is true. If the condition is false,
another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional"
Statements, which are used to perform different actions based on different conditions.
Else
-an else statement is an alternative statement that is executed if the result of a previous test condition
evaluates to false.
Nesting Conditionals
-We can nest conditionals inside conditionals.
-Nesting occurs when one programming construct is included within another. ... It reduces the amount of
code needed, while making it simple for a programmer to debug and edit. Different types of construct can
be nested within another. For example, selection can be nested within a condition-controlled loop.
Logical Operators
-A logical operator is a symbol or word used to connect two or more expressions such that the value of
the compound expression produced depends only on that of the original expressions and on the meaning
of the operator. Common logical operators include AND, OR, and NOT.
https://www.w3schools.com/js/js_comparisons.asp
if (!terms) {
alert("You did not agree to the terms and conditions");
} else {
alert("You agreed to the terms and conditions");
}
JS Arrays
-JavaScript arrays are used to store multiple values in a single variable.
-Out first data structure. Data structure simply is a collection of data.
The problem is, they are not connected to each other. This is the time that JS array will enter.
Syntax:
var arrayName = [value1, value2, value3…];
Creating Arrays:
//To make an empty array
let items = [];
Arrays are indexed. Each element has a corresponding index (counting starts at 0).
let friends = ["Michael", "Paolo", "Mark"];
0 1 2
let friends = ["Michael", "Paolo", "Mark"];
friends.push("Travis");
friends.pop();
friends.unshift("Travis");
friends.shift();
More Methods
friends.includes("TJ");
friends.indexOf("TJ");
friends.reverse();
friends.sort();
Const and Arrays
Why do people use const with arrays?
const num = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
airplaneSeats[3][1] = "Hugo";
JS Objects
Objects:
-Objects are collections of properties.
-Properties are a key-value pair.
-Rather than accessing data using an index, we use custom keys.
-Labeling our data.
const smartWatchData = {
totalSteps: 10000,
totalCaloriesBurn: 5000,
currentWeight: "67 kgs"
};
Modifying Objects
To update:
person.age = 18;
person["age"] = 18;
To add:
person.city = "Caloocan City";
person["city"] = "Caloocan City";
{
username: "Cat lover",
likes: 1000,
comment: "Meow! I am so vain!"
}
];
const student = {
firstName: "Aldrin John",
lastName: "Tamayo",
isMale: true,
grades: {
prelim: 97,
midterm: 87,
finals: 99
}
};