0% found this document useful (0 votes)
13K views

Front-End - JavaScript Part 1

JavaScript is a scripting language that allows dynamic updating of web page content. It can be used to manipulate HTML and CSS. JavaScript has primitive data types like numbers, strings, Booleans, null, and undefined. Variables are used to store and label values that can later be updated. Conditional statements like if/else are used to control program flow based on comparisons. Logical operators can connect conditional expressions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13K views

Front-End - JavaScript Part 1

JavaScript is a scripting language that allows dynamic updating of web page content. It can be used to manipulate HTML and CSS. JavaScript has primitive data types like numbers, strings, Booleans, null, and undefined. Variables are used to store and label values that can later be updated. Conditional statements like if/else are used to control program flow based on comparisons. Logical operators can connect conditional expressions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Basics of JavaScript

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.)

How to learn JavaScript?


-Learn JS on its own. No HTML and/or CSS
-Use JS to manipulate HTML and CSS

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.

Basic Building Blocks


-Number
-String
-Boolean
-Null
-Undefined

JS Numbers
-JS has one number type
-Positive numbers, negative numbers, whole numbers (integers), decimal numbers.

What is NaN (Not a Number)?


NaN is a numeric value that represents something that is not a number.

Ex. 0/0
1 + NaN

Typeof Operator
-The typeof operator returns a string indicating the type of the unevaluated the operand.

Typeof Nan = Number


Variables
-Variables are like labels for values
- We can store a value and give it a name so that we can: refer back to it later; use that value to do stuff;
or change it later one.

Basic Syntax
let sample = value;

Ex:
let year = 1993;

To call it, use the name of the variable.

let currentAge = 28;

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;

*Do this when adding or subtracting 1 number: Console


let numLives = 9;
numLives += 1; - increment or numLives++;
numLives -= 1; - decrement or numLives--;

Const & Var


Const – works just like let, except you cannot change the value. (Constant)

const num = 27;


const++; - VM1047:1 Uncaught SyntaxError: Unexpected token '++'

We can use it to the following:


const pi = 3.14159;
const daysInWeek = 7;

Var - the old variable keyword


- Before let & const, var was the only way of declaring variables. These days, there isn’t really a reason to
use it.

Booleans
True or False / Yes or No values

let isMale = false;


let isActivePlayer = true;
Variables can change types – it doesn’t really make sense to change from a number to a Boolean here, but
we can.

*Demo using console: also check the variable using typeof


let age = 27;
age = false;
age = 20;

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.

let name = “Aldrin John”;

‘He said, “I am great!”’;

Indices
STRING ARE INDEXED
STRINGS
0123456
-each character has a corresponding index (a positional number)

Let str = “String”;


Str[0]; //to get the index of the str var.

str.length //property to check the length or the number of characters

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

They help us do things like:


-searching within a string
-replacing part of a string
-changing the casing of a string
”hello”. //methods will show up

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

syntax: thing.method()

//To upper case


let name = "aldrin john tamayo";
let upperCaseName = name.toUpperCase();
upperCaseName

//To lower case


let lowerCaseName = upperCaseName.toLowerCase();
lowerCaseName

//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();

String methods with arguments


-Some methods accept arguments that modify their behavior. Think of them as inputs that we can pass in.
We pass these arguments inside of the parentheses.

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.

let tvShow = "catdog";


tvShow.indexOf("cat");
tvShow.indexOf("dog");
tvShow.indexOf("z"); -1 because there’s no z in it

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);

let firstName = 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.

let item = "Macbook";


let price = 50000;
let qty = 2;
"My bestfriend bought " + qty + " " + item + ". Total amount is " + qty*price

[This is annoyng]

We use back-ticks, not single quotes.

${}, whatever I put inside the curly braces will be treated as an expression and will be evaluated.
`Math ${1 + 2 + 3}`;

`My bestfriend bought ${qty} ${item}. The amount is ${qty*price}.`;

Undefined and Null

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, Alert, & Prompt

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.

console.log(“Hello from Console”);

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.

Prompt(“Please enter your name”);

let age = prompt(“Please enter your age:”);


Age is now a string. Every input using prompt became string. To verify, use typeOf.
To convert that, use parseInt(age).
let newAge = parseInt(age);

Or

let age = Number(prompt(“Please enter your age:”));

Running Code from a file

<!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");
}

let age = 18;

if (age <= 17) {


console.log("You are no longer allowed to go out because you are a minor");
}

let rand = Math.random();


if (rand <= 1) {
console.log("Your random numberi s less than 1");
console.log(rand);
}

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.

let age = 18;

if (age <= 17) {


console.log("You are no longer allowed to go out because you are a minor");
} else if (age >= 18) {
console.log("You are allowed to go out");
}

Else
-an else statement is an alternative statement that is executed if the result of a previous test condition
evaluates to false.

let age = 65;

if (age <= 17) {


console.log("You are no longer allowed to go out because you are a minor");
} else if (age <= 64) {
console.log("You are allowed to go out");
} else {
console.log("You are no longer allowed to go out because you are a senior");
}

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.

const pass = prompt("Please enter a new password");


//password must be 8+ characters
if (pass.length >= 6) {
alert("Good password");
} else {
alert("Bad password");
}

//password cannot include space


if (pass.indexOf(" ") === -1) {
console.log("No space");
} else {
console.log("Password should not have spaces");
}
Then, change to:
const pass = prompt("Please enter a new password");

//password must be 8+ characters


if (pass.length >= 6) {
//password cannot include space
if (pass.indexOf(" ") === -1) {
alert("Valid password");
} else {
alert("Password should not have spaces");
}
} else {
alert("Invalid password");
}

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

Logical AND (&&)


-Both sides must be true for the entire thing to be true.
-The logical AND ( && ) operator (logical conjunction) for a set of operands is true if and only if all of its
operands are true.

true && true //true


true && false //false
false && false //false
2 <= 6 && "x" === "x"; //true
3 > 11 && 10 >= 10; //false
"xyz".length === 3 && 2+2 === 5; //false

let username = "akosieijey";


let password = "Password.1"

const user = prompt("Enter your username:");


const pass = prompt("Enter your password:")

if (username === user && password === pass) {


alert("Credentials are correct");
} else {
alert("Invalid credentials");
}

const pass = prompt("Please enter a new password");

if (pass.length >= 8 && pass.indexOf(" ") === -1) {


alert("Valid password")
} else {
alert("Invalid password");
}

Logical OR (||) pipe character or vertical line


-If one side is true, then entire thing is true.
-The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of
its operands is true.

true || true //true


true || false //true
false || false //false

let age = prompt("What is your age?");

if (age <= 17 || age >= 65) {


alert("You are not allowed to go out!");
} else {
alert("You may go out!");
}
Logical Not
-!expression returns true of expression is false.
-will negate the value.
- The logical NOT ( ! ) operator (logical complement, negation) takes truth to falsity and vice versa.

let terms = prompt("Do you agree to the terms and conditions?");

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.

This is how we store data in a variable:

const friend1 = "Michael";


const friend2 = "Paolo";
const friend3 = "Mark";

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…];

let friends = ["Michael", "Paolo", "Mark"];

Creating Arrays:
//To make an empty array
let items = [];

//An array of strings


let friends = ["Michael", "Paolo", "Mark"];

//An array of numbers


let nums = [1, 2, 3, 4, 5];

//An array of mixed data types


let mixed = ["string", 17, true, null];

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[0]; //to get the value at the index 0


friends.length; //to get the length of an array
friends[3]; //undefined
friends[0][0]; //first index is the value, the second is the index of the value.

let friends = ["Michael", "Paolo", "Mark"];

friends[0] = "Michaela"; //to update the value of the given index


friends[3]; //undefined. To add:
friends[3] = "Travis";

Push and Pop


Push – Add to end
Pop – Remove from end

let friends = ["Michael", "Paolo", "Mark"];

friends.push("Travis");
friends.pop();

Shift and Unshift


Unshift – Add to start
Shift – Remove from start

let friends = ["Michael", "Paolo", "Mark"];

friends.unshift("Travis");
friends.shift();

More Methods

concat – merge arrays


let friends1 = ["Michael", "Paolo", "Mark"];
let friends2 = ["Travis", "TJ"];
let friends = friends1.concat(friends2);
includes – look for a value
let friends1 = ["Michael", "Paolo", "Mark"];
let friends2 = ["Travis", "TJ"];
let friends = friends1.concat(friends2);

friends.includes("TJ");

indexOf – just like string.indexOf


let friends1 = ["Michael", "Paolo", "Mark"];
let friends2 = ["Travis", "TJ"];
let friends = friends1.concat(friends2);

friends.indexOf("TJ");

reverse – reverses an array


let friends1 = ["Michael", "Paolo", "Mark"];
let friends2 = ["Travis", "TJ"];
let friends = friends1.concat(friends2);

friends.reverse();

slice – copies a portion on an array


let friends = ["Michael", "Paolo", "Mark", "TJ", "Travis"];

friends.slice(1); //index of 1 to the end


friends.slice(1, 3);

let bestfriends = friends.slice(1, 3);

splice – removes/replaces elements


let nums = [1, 3, 4, 5, 6, 7, 8, 9, 10];

nums.splice(1, 0, 2); //starting index, how many to delete, what to insert

sort – sorts an array


let friends = ["Michael", "Paolo", "Mark", "TJ", "Travis"];

friends.sort();
Const and Arrays
Why do people use const with arrays?

Multi-Dimensional Arrays / Nested Arrays


-We can store arrays inside other arrays.

const num = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

// DO NOT TOUCH!!! (please)


const airplaneSeats = [
['Ruth', 'Anthony', 'Stevie'],
['Amelia', 'Pedro', 'Maya'],
['Xavier', 'Ananya', 'Luis'],
['Luke', null, 'Deniz'],
['Rin', 'Sakura', 'Francisco']
];

// YOUR CODE GOES BELOW THIS LINE:

airplaneSeats[3][1] = "Hugo";

JS Objects

-Our second data structure.


-JavaScript objects are containers for named values called properties or methods.

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"
};

Property = Key + Value

All data types are welcome!


const person = {
firstName: "Aldrin John",
lastName: "Tamayo",
age: 28,
isMale: true,
hastTags: ["#goaldigger", "#educator", "#webdeveloper", "#softwareengineer"]
};

Accessing Data out of an Object


person["firstName"]; //by using brackets
person.firstName; //by using dot

Valid Keys – All keys are converted to strings.

Modifying Objects
To update:
person.age = 18;
person["age"] = 18;

To add:
person.city = "Caloocan City";
person["city"] = "Caloocan City";

Nesting Arrays & Objects


const blogComments = [
{
username: "Hotdog",
likes: 101,
comment: "That is awesome!"
},

{
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
}
};

You might also like