Remember, don't declare the same variable repeatedly.
//Declaring a function
function sayHello(message){
console.log(message);
}
//Executing function
sayHello('hello');
//Declaring a function
function sayHello(message1, message2){
console.log(message1);
console.log(message2);
}
//Executing function
sayHello('hello', 'world');
function getArea(height, width){
return height * width;
}
var x = getArea(10, 10);
console.log(x); // outputs 100;
Methods are actions that can be taken on objects.
Properties are values associated with an object.
length
property - returns the number of characters in the string.indexOf
method - returns the position (index) of the first occurrence of text in a string.length
var x = "name".length;
console.log(x); // x equals 4
var y = "name"
console.log(y.length); //
var username = "JonMiddaugh";
var userNameLength = username.length; //11
var isValid = (userNameLength > 20 || userNameLength < 10); //Returns false
indexOf
var x = "name".indexOf("n"); ///// x = 0;
var y = "name name name".indexOf("a"); //y = 1;
var z = "name".indexOf("z"); // z = -1;
var z = "name".indexOf("ame"); // z = 1;
var email = "jonathan.middaugh@gmail.com";
var isValidEmail = (email.indexOf('@') > -1);
console.log(isValidEmail); //true
indexOf returns -1 if the character is not found
These methods are considered global methods.
parseInt
- Attempts to convert a string to an integerparseFloat
- Attempts to convert a string to a floatparseInt
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("ten"); // returns NaN
parseInt("10 11 12"); // returns 10
parseInt("10 tacos"); // returns 10
parseInt("tacos 10"); // returns NaN
parseFloat
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("ten"); // returns NaN
parseFloat("10 11 12"); // returns 10
parseFloat("10 tacos"); // returns 10
parseFloat("tacos 10"); // returns NaN
There is a built-in method for determining if a variable is a number.
var x = "t"
//This doesn't work
var isNumber = (parseInt(x) === NaN);
var x = "t"
if (isNaN(x)){
//it is NOT a number
}else{
//It is a number
}
Arrays are used to store a collection of variables.
var list = ["A", "B", "C", "D"];
var list2 = [1, 10, 0, 3];
var list3 = [1, 'ten', '0', 3];
You can access individual items in an array by referencing its index or position. Accessing an invalid index will return
undefined
.
Arrays operate off of a "zero" based index. The first position has an index of 0.
var list = ["A", "B", "C", "D"];
console.log(list[1]); // Outputs "B"
console.log(list[0]); // Outputs "A"
console.log(list[20]); // Outputs undefined
There are several different methods to modify an array. We're going to focus primarily on one.
push
- Adds item to the end of an arraylength
- gives the count of items in the array
var x = ["a", "b", "c"];
x.push('d');
x.push('e');
console.log(x); //["a", "b", "c", "d", "e"];
Just about everything in JavaScript is an object. Primitive variables are the only things that are not actual objects.
Objects are variables that contain many variables.
var me = {
firstName: "Jon",
lastName: "Middaugh",
age: 28,
city: 'Johnson',
fullName: function(){
return this.firstName + " " + this.lastName;
}
};
console.log(me.age) //Outputs 60;
console.log(me.height); //Outputs undefined
me.height = '5\' 6"';
console.log(me.height); //Outputs 5' 6"
W3 Schools example
this
var me = {
firstName: "Jon",
lastName "Middaugh",
age: 60,
city: 'Cave Springs',
fullName: function(){
return this.firstName + " " + this.lastName;
};
};
Undefined
is the value that is given to a variable before it has a value.
var x;
console.log(x); //undefined
x = 10;
console.log(x); //10
console.log(x); //undefined
var x = 10;
console.log(x); //10
var x;
console.log(x); //undefined
x = 10;
console.log(x); //10
null
is a value given to objects that are not defined.
var x = null;
if (x !== null){
//perform logic
}
var d = document.getElementById('fdfdfdfdf');
console.log(d); //null;
It can get confusing which to use, but there is an easy solution for if statements.
var d = document.getElementById('yarg');
if (d){
//executes if not null (not found)
}
var x;
if (x){
//executes if not undefined
}
Allows you to retrieve DOM elements by their class names.
There is one major difference between this and getElementById. This one returns an HTMLCollection which is like an array.
document.getElementsByClassName('side-bar-item')
//targets elements with both user-input and invalid classes
document.getElementsByClassName('user-input invalid')
To modify the object's properties, we need to loop through them or reference a specific index.
We haven't covered loops yet so you can just reference by the index.
var elms = document.getElementsByClassName('user-input');
var elm = elms[0];
if (elm){
elm.innerHTML = "Yay!";
}
.forEach()
forEach
loops through each item in an array and executes a function for each item.
[1,2,3].forEach(function(element, index, array){
//Code
});
element
- the current iterated element.index
- the current zero based indexarray
- the full array of itemsSee the Pen Array - forEach() by Jon (@Middaugh) on CodePen.
See the Pen Array - forEach() by Jon (@Middaugh) on CodePen.
.map()
map
acts similar to forEach
but it returns a whole new array.
[1,2,3].map(function(element, index, array){
return '';
});
element
- the current iterated element.index
- the current zero based indexarray
- the full array of itemsSee the Pen Array - map() by Jon (@Middaugh) on CodePen.
.filter()
Filter iterates through an array and adds the element to the new array if it returns true.
[1,2,3].filter(function(element, index, array){
return true | false;
});
element
- the current iterated element.index
- the current zero based indexarray
- the full array of itemsSee the Pen Array - filter by Jon (@Middaugh) on CodePen.
See the Pen Array - Filter Advanced by Jon (@Middaugh) on CodePen.
.find()
Acts like filter, but only returns the first one found that matches the parameters
[1,2,3].find(function(element, index, array){
return true | false;
});
element
- the current iterated element.index
- the current zero based indexarray
- the full array of itemsSee the Pen Array - Filter Advanced by Jon (@Middaugh) on CodePen.
Sorting an array happens in place, it doesn't return a new array.
var food = ['taco', 'burger', 'hotdog'];
food.sort();
console.log(food); //['burger', 'hotdog', 'taco'];
var nums = [20, 3, 10, 1, 2]
nums.sort();
console.log(nums); //[1, 10, 2, 20, 3];
.sort
sorts by unicode character. Everything gets converted to a string before sorting.
This is what we are going to use for now
var nums = [20, 3, 10, 1, 2]
nums.sort(function(a,b){
return a - b;
});
console.log(nums); //[1, 2, 3, 10, 20];
RegExp are patterns that are used to match specific characters.
We'll use them for text searching and text replacement.
RegExps are not unique to JavaScript.
Syntax: /pattern/modifiers
var pattern = /lorem/i
var str = "hello world. Hello class. hello things";
var pattern = /hello/i;
var newStr = str.replace(pattern, 'Goodbye');
Result: 'Goodbye world. Hello class. hello things'
We can add g
to our pattern to globally replace.
var str = "hello world. Hello class. hello things";
var pattern = /hello/ig;
var newStr = str.replace(pattern, 'Goodbye');
Result: 'Goodbye world. Goodbye class. Goodbye things'
Regex Test is a method that allows us to see if a block of text contains a pattern. This leverages the RegExp object.
var str = "Lorem ipsum dolor";
var patt = new RegExp(/lorem/i);
var res = patt.test(str);
The i
flag allows 'Lorem' to match.
Constructing RegExp patterns can be really hard. I always keep a few handy.
/[a-z]/gi
- Letters only/[0-9]/gi
- Numbers only/^[a-z0-9_-]{3,16}$/
- User Name min 3 max 16/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
- Email/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
- URL Research the difference between x++ and ++x and use ++x properly in a for loop that returns an array populated with the unique values of this array:
var fruits = ["Orange", "Orange", "Apple", "Apple"];
(so result is ["Orange", "Apple"])