To interact, test and understand JS, we use the browser console.
cmd + option + J - Chrome Console
There are 5 primitive data types
Wholes, fractions & Negative numbers
// numbers
4
9.2
-3
// Math
4 + 10 // 14
6/2 // 3
5 * 2 // 10
// Modulo - Remainder
10 % 3 // 1
24 % 2 // 0
15 % 11 // 4
Any character inside quotes "...", '...' (even numbers)
// Single or Double quotes
"Hello World"
'Hello World'
// Concatenation
"Thom" + " " + "Yorke" // "Thom Yorke"
// Escape characters
"Singing \"This is how we do it!\""
"This is a backslash: \\"
// Length Property
"Hello World".lenght // 11
// Access individual chars with []
"hello"[0] // "h"
"hello"[3] // "l"
Only have two options, true or false (on or off)
Null is "explicitly nothing".
var currentPlayer = "Juan";
currentPlayer = null; // game over
Variables that are declared but not initialized.
var name;
var age;
Variables are containers that store values
There are different conventions to write variables in js:
var myVariable = myValue;
They can store any kind of value
var name = "juan";
var age = 33;
var isMarried = false;
We can recall a stored value by calling the variable name:
var name = "Thom";
"Hello " + name; // "Hello Thom"
var num = 42;
num + 3; // 45
We can also update a value in axisting variables:
var name = "Juan";
name; // "Juan"
name = "Jack";
name; // "Jack"
Variables can change their type (Dynamic typing)
Block-scoped variable
Global (immutable/constant) variable
There are a lot of methods, but the most common built-in methods in the browser are:
Resets the console.
Shows the user a message.
Asks the user for input.
Writes a message to the console.
var userName = prompt("Hello, what's your name?");
console.log("I'm Console, nice to meet you " + userName);
alert("I'm Alert, also nice to meet you " + userName);
// EXERCISE
// prompt age
var age = prompt("What's your age");
// eval age in days + leap years
var ageInDays = age * 365.25;
// print years in days
console.log("You've lived roughly: " + ageInDays + " days");
We can write JS directly between script tags, but it can become difficult to mantain.
<script>
// your JS code
</script>
Most of the time we include a separate JS file with the HTML script tag.
<script src="path/to/file" type="text/javascript"></script>
Statements –or a combination of statements– that evaluate to either true or false.
true == "1" // true
0 == false // true
null == undefined // true
NaN == NaN // false
If false, it is trhuthy and vice-versa
!"hello world" // false
!"" // true
!null //true
!0 //true
!-1 // true
!NaN // true
Falsy Values:
Everything else is truthy
var str = "";
var msg = "wuuut!";
var isFunny = "false";
!((str || msg) && isFunny) //?
Making decisions with code
if (someCondition) {
// execute this code
} else {
// execute this one
}
// smallest way
if (someCondition) {
// run this
}
// long way
if (someCondition) {
// execute this code
} else if (anotherCondition) {
// execute this other thing
} else {
// execute this one
}
...
If this returns true, nothing else runs
if this returns true, nothing else runs
// Get age and convert it to a Number (prompt always returns a String)
var age = Number(prompt("What is your age?"));
// If age is negative
if(age < 0) {
console.log("Come back once you're out of the womb");
}
// If age is 21
if(age === 21) {
console.log("Happy 21st Birthday!");
}
// If age is odd
//(not evenly divisible by two)
if(age % 2 !== 0) {
console.log("Your age is odd!");
}
// If age is a perfect square
if(age % Math.sqrt(age) === 0) {
console.log("Your age is a perfect square!");
}
Repeating things
while(someCondition) {
// execute this code
}
// Printing numbers from 1 to 5
var count = 1;
while(count < 6) {
console.log("Count is: " + count);
count++;
}
// Printing each character in a string
var str = "Hello";
var count = 0;
while(count < str.length) {
console.log(str[count]);
count++;
}
Beware of infinite loops. If the condition is never true, it will repeat until you burn your computer :P
for(init; condition; step) {
// execute this code
}
// Printing numbers from 1 to 5
for(var count = 1; count < 6; count++) {
console.log(count);
}
// Printing each character in a string
var str = "Hello";
for(var i = 0; i < str.length; i++) {
console.log(str[i]);
}
Wrap bits of code into reusable packages. One of the building blocks of JS.
// Function Declaration
function doSomething() {
console.log('Do it!');
}
// Function Expression
var doSomething = function() {
console.log('Do it!');
}
// Referring a fn()
doSomething;
// Calling/Executing a fn()
doSomething();
A value we pass to a fn(val).
// With one argument
function square(num) {
console.log(num * num);
}
square(10); // 100
square(3); // 9
// Multiple arguments
function area(length, width) {
console.log(length * width);
}
area(9,2) // 18
Sending back the output value of a fn().
Input -> function() -> Output
function square(n) {
return n * n;
}
"The square of 101 is: " + square(101);
// "The square of 101 is: 10201"
// fn() that capitalizes the first char of a given string
function capitalize(str) {
if(typeof str === "number") {
return "That's not a string!"
}
return str.charAt(0).toUpperCase() + str.slice(1);
}
var city = "quito";
capitalize(city); // "Quito"
capitalize(22); // "That's not a string!"
// Ex.
function isEven(n) {
if(n%2===0) {
return true;
} else {
return false;
}
}
// Ex shortcut
function isEven(n) {
return n % 2 === 0;
}
// Ex2
function factorial(num) {
var result = 1;
for(var i = 2; i <= num; i++) {
result *= i;
}
return result;
}
// Ex3
function kebabToSnake(str){
var nuStr str.replace(/-/g, "_");
return nuStr;
}
The context the code is executed in.
Global Scope vs. Local Scope
// Global Scope
var x = 10;
function someMath() {
console.log(x);
}
someMath(); // 10
// Local Scope
var x = 10;
function moreMath() {
var x = 99;
console.log(x);
}
moreMath(); // 99
Global scopes can be used inside a fn() but local scopes cannot be used outside a fn().
Functions that take a fn() as an argument, or return another fn().
// setInterval();
function sing() {
console.log('🎶');
console.log('lalala! lala! la!');
console.log('🎶');
}
// we pass the sing fn() without parens, because we don't execute the fn(). setInterval() does.
setInterval(sing, 2000);
// We can also define the function inside setInterval() as an anonymous fn()
setInterval(function() {
console.log("I'm an anonymous function!");
}, 3000);
[Data Structure] - Group data in comma-separated lists.
Arrays are zero-indexed.
// Initialize an empty array
var friends = [];
var friends = new Array();
// Define the array
var friends = ["Tron", "Morlis", "Alvaro", "Irene", "Carlos"];
console.log(friends[1]); // "Morlis"
// Update or add values
friends[0] = "Jose";
var friends = ["Jose", "Morlis", "Alvaro", "Irene", "Carlos"];
// Length Property
friends.length; // 5
// Can contain any type of data
var randomArr = [11, "Hello", true, {object: 1}, ["otherArrays"], null];
JS has many built-in methods to manipulate arrays.
PUSH: Adds to the end of an array
var colors = ["red", "green", "blue"];
colors.push("yellow");
// ["red", "green", "blue", "yellow"]
POP: Removes the last item from the array
var colors = ["red", "green", "blue", "yellow"];
colors.pop();
// ["red", "green", "blue"]
// pop() returns the removed el
var colorBlue = colors.pop(); // "blue"
SHIFT: remove the first item from an array.
var colors = ["red", "green", "blue"];
colors.shift();
// ["green", "blue"]
// shift() also returns the removed el
var colGreen = colors.shift(); // "green"
UNSHIFT: add to the front of an array.
var colors = ["red", "green", "blue"];
colors.unshift("yellow");
// ["yellow", "red", "green", "blue"]
INDEXOF: find the index of an item in an array
var friends = ["Jose", "Morlis", "Alvaro", "Irene", "Carlos"];
friends.indexOf("Alvaro"); // 2
// return -1 if the element is not present
friends.indexOf("Felipe"); // -1
SLICE: copy a part of an array.
var fruits = ["banana", "lemon", "orange", "apple", "mango"];
var citrus = fruits.slice(1, 3);
// citrus = ["lemon", "orange"];
// slice() doesn't modify the original array
// You can use slice() to copy an entire array
var nums = [1, 2, 3, 4];
var otherNums = nums.slice();
// otherNums = [1, 2, 3, 4]
SPLICE: remove part of an array.
var fruits = ["banana", "lemon", "tomato", "broccoli", "apple", "mango"];
var veggies = fruits.splice(2, 2); // index, quantity
// veggies = ["tomato", "broccoli"];
// fruits = ["banana", "lemon", "apple", "mango"]
var colors = ["green", "red", "green", "blue", "yellow"];
var count = 0;
while(count < colors.length) {
console.log(colors[i]);
count++;
}
// green
// red
// green
// blue
// yellow
var colors = ["green", "red", "green", "blue", "yellow"];
for(var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
// green
// red
// green
// blue
// yellow
Part of the array prototype.
arr.forEach(someFunction);
//
var colors = ["green", "red", "green", "blue", "yellow"];
colors.forEach(function(color) {
console.log(color);
})
// green
// red
// green
// blue
// yellow
{Data Structure} - key/value pair properties.
Objects can hold all sorts of data.
// Initialize an object
var person = new Object();
var person = {};
// Populate the object
person.name = "Ricardo";
...
//
var person = {
name: "Ricardo",
age: 39,
city: "Quito"
};
// Bracket notation
console.log(person["name"]); // "Ricardo"
// Dot notation -> Best way
console.log(person.age); // 39
// Update values
var dog = {
name: 'thom',
age: 4,
breed: 'Delmer',
birthday: '2013/24/05'
};
dog.name = "Thom"; // "Thom"
dog["age"] += 1; // 5
Cannot use dot notation when:
In other languajes, objects are known as dictionaries.
A method is just a function as a value of a property of the object:
var obj = {
name: "Han Solo",
age: 49,
isCool: false,
friends: ['Chewie', 'R2D2'],
speak: function(name) {
return "hello " + name + "!";
}
}
console.log(obj.speak("C3P0"));
// "hello C3P0!"
this refers to the context in which the code is executed.
var comments = {
data: ["Nice!", "Boring", "Learned a lot :)"],
print: function() {
this.data.forEach(function(el) { // this refers to the object
console.log(el);
});
}
};
comments.print();
// "Nice!"
// "Boring"
// "Learned a lot! :)"
*Namespace Collision: when two methods are named the same and override each other.