Skip to content

Instantly share code, notes, and snippets.

@DixieKorley
Created November 29, 2017 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DixieKorley/e6ba7539dadbeace578ae3a1967ab037 to your computer and use it in GitHub Desktop.
Save DixieKorley/e6ba7539dadbeace578ae3a1967ab037 to your computer and use it in GitHub Desktop.
Introduction to Javascript created by dixiekorley - https://repl.it/@dixiekorley/Introduction-to-Javascript
// Whitespace and tabs have no meaning outside of quotation marks. Tabs help with readability.
//Parentheses help with order of oprations.
2 * 3 + 5; // 11
2 * (3 + 5); // 16
//Concatenation
var foo = 'hello';
var bar = 'world';
console.log(foo + ' ' + bar); // 'hello world'
//Multiplication and Division
2 * 3; // 6
2 / 3; // 0.6666666666666
//Incrementing and decrementing
var i = 1;
var j = ++i // j equals 2, i equals 2
var k = i++ // k equals 2, i equals 3
//Addition vs. Concatenation
var foo = 1;
var bar = '2';
console.log(foo + bar); // 12 because 2 is treated as a string.
//Forcing a string to act as a number
var foo = 1;
var bar = '2';
console.log(foo + Number(bar));
//Or Unary-Plus Operator
console.log(foo + (+bar));
//Logical AND or OR Operators - Explain more on Booleans, AND, OR, NOT. AND returns first operand value and then last operand if both operands are true. OR returns the value of the first true operand, or, in cases where neither operand is truthy, it will return the last of both operands.
var foo = 1;
var bar = 0;
var baz = 2;
foo || bar; // 1 so true
bar || foo; // 1 so true
foo && bar; // 0 so false
foo && baz; // 2 so true
baz && foo; // 1 so false
//Comparison Operators
var foo = 1;
var bar = 0;
var baz = '1';
var bim = 2;
foo === bar; // false
foo !== bar; // true
foo === baz; //true (careful because baz is a string)
//Conditional Code: Flow control - when if and else block statements lets you run code only under certain conditions.
var foo = true;
var bar = false;
if (bar) {
console.log('hello!');
}
if (bar) {
//this code won't run.
}
else {
if (foo) {
//this code will run
}
else {
//this code would run if foo and bar were both false.
}
}
//T or F
//Values that evaluate to true
'0'
'any string'
[]; // empty array
{} //empty object
1; //any non-zero number
//Values that evaluate to false
0;
' '; //empty string
NaN; //Not a number
null;
undefined; //careful, undefined can be redefined
//Conditional variable assignment with the ternary operator instead of if/else statements. Ternary operator tests a condition, if the condition is true, it returns a certain value, otherwise, it returns a different value.
//set foo to 1 if bar is true;
//otherwise, set foo to 0
var foo = bar ? 1 : 0;
//Switch statements instead of if/else. Switch statements look at the value or expression, and run different blocks of code depending on the value.
switch (foo) {
case 'bar':
alert('the value was bar -- yay!');
break;
case 'baz':
alert('boo baz :(');
break;
default:
alert('everything else is just ok');
break;
}
//Switch statements are used less because one can create an object that could be reused, and tested over. E.g.
var stuffToDo = {
'bar' : function() {
alert('the value was bar -- yay!');
},
'baz' : function() {
alert('boo baz :(');
},
'default' : function() {
alert('everything else is just ok');
}
};
if (stuffToDo[foo]) {
stuffToDo[foo]();
} else {
stuffToDo['default']();
}
//Loops - statements that let you run a block of code a certain number of times
//logs 'try 0', try 1', ...., 'try 4'
for (var i = 0; i < 5; i++) {
console.log('try ' + i);
}
//The for Loop - made up of four statements and has the following structure:
//for ([initialization],[conditional],[iteration]) [loopBody]
//Initialization is executed only once, before the loop starts. Gives you an opportunity to prepare or declare any variables.
//Conditional is executed before each iteration, and its return value decides whether or not the loop is to continue.
//Iteration is executed at the end of each iteration and gives you the opportunity to change the state of important variables.
//loopBody is what runs on every iteration. It can contain anything you want.
for (var i = 0; limit = 100; i < limit; i++) {
// This block will be executed 100 times
console.log('Currently at ' + i);
// Note: the last log will be 'Currently at 99'
}
//The while loop
var i = 0;
while (i < 100) {
//This block will be executed 100 times.
console.log('Currently at ' + i);
i++; //increment i
}
//The do-while loop
do {
// Even though the condition evaluates to false
//this loop's body will still execute once.
alert('Hi there!');
} while (false);
//Breaking and continuing
//* Stopping a loop
for (var i = 0; i < 10; i++) {
if (something) {
break;
}
}
//* Skipping to the next iteration of a loop
for (var i: 0; i < 10; i++) {
if (something) {
continue;
}
//The following statement will only be executed
//If the conditional 'something' has not been met
console.log('I have been reached');
}
//Avoid using these reserved words unless with their intended meaning.
/* abstract, boolean, case, catch, const, continue, debugger, char, break, byte, class, default, delete, do, double, else, enum, export, extends, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, interface, long, native, new, package, private, protected, publi, return, short, static, super, switch, synchrinized, this, throw, throws, transient, try, typeof, var, void, volatile, while, with */
//Arrays - they are a zero-indexed lists of values and can include many types of items.
//* A simple Array
var myArray = ['hello', 'world'];
//* Accessing items in an Array
var myArray = ['hello', 'world', 'foo', 'bar'];
console.log(myArray[3]); //logs 'bar'
//*Testing the size of an Array
var myArray = ['hello', 'world'];
console.log(myArray.length); //logs 12
//*Changing the value of an array item. Not usually advised.
var myArray = ['hello', 'world'];
myArray.push('new');
//*Adding elements to an array
var myArray = ['hello', 'world'];
myArray.push('new');
//*Working with Arrays
var myArray = ['h', 'e', 'l', 'l', 'o'];
var myString = myArray.join(''); //'hello'
var mySplit = myString.split(''); // ['h', 'e', 'l', 'l', 'o']
//Objects - list containing key-value pairs. Keys can be any string, number or any JS identifier, values can be string, array, function, or even another object. When a function is in an object it is called the method of an object, if not, it is just a property of an object. Nearly everything in JS is an object - arrays, functions, numbers, even strings - and they all have properties and methods. Instead of brackets, they use curly braces.
var myObject = {
sayHello : function() {
console.log('hello');
}
myName : 'Rebecca'
};
myObject.sayHello(); //logs 'hello'
console.log(myObject.myName); //logs 'Rebecca'
//**
var myObject = {
validIdentifier: 123,
'some string': 456,
99999: 789
};
//Functions - contain blocks of code that need to be executed repeatedly. Functions can take zero or more arguments, and can optionally return a value.
//*Function declaration
function foo() { /* do something */ }
//*Named function declaration
var foo = function() {/* do something */ }
//Using Functions
//*A simple Function
var greet = function(person, greeting) {
var text = greeting + ', ' + person;
return text;
};
greet('Rebecca', 'Hello');
//*A function that returns an value
var greet = function(person, greeting) {
var text = greeting + ', ' + person;
return text;
};
console.log(greet('Rebecca', 'Hello'));
//*A function that returns another function
var greet = function(person, greeting) {
var text = greeting + ', ' + person;
return function() { console.log(text); };
};
var greeting = greet('Rebecca', 'Hello');
greeting();
//*Self executing anonymous function - produces a function expression and executes the function.
(function() {
var foo = 'Hello World';
}) ();
console.log(foo); // undefined!
//Function as arguments
//*Passing an anonymous function as an argument.
var myFn = function(fn) {
var result = fn();
console.log(result);
};
//Passing a named function as an argument
var myFn = function(fn) {
var result = fn();
console.log(result);
};
var myOtherFn = function() {
return 'hello world';
};
myFn(myOtherFn); // logs 'hello world'
//Testing Type
//*Testing the type of various variables using the typeof operator
var myFunction = function() {
console.log('hello');
};
var myObject = {
foo : 'bar'
};
var myArray = [ 'a', 'b', 'c'];
var myString = 'hello';
var myNumber = 3;
typeof myFunction; // returns 'function'
typeof myObject; //returns 'object'
typeof myArray; //returns 'object' (an array is considered an object)
typeof myString; //returns 'string'
typeof myNumber; //returns 'number'
typeof null; //returns 'object' because null is considered an object unless specified
if (myArray.push && myArray.slice && myArray.join) {
//probably an array
//this is called 'duck typing'
};
if (Object.prototype.toString.call(myArray) === '[object Array]') {
//definitely an Array
//this is widely considered as the most robust way
//to determine if a specific value is an array
};
//The this keyword
//*If you use Function.call or Function.apply to invoke a function, (this) will be set to 1st argument passed to call/apply. If first argument is null or undefined, (this) refers to global object or ((window) object in Web browsers). If you use Function.bind, (this) will be first argument passed to the bind. If the function is being invoked as a method, (this) refers to the object. Otherwise if the function is invoked as a standalone function and not attached to any object, (this) refers to the global object.
//*Function invoked using Function.call
var myObject = {
sayHello : function() {
console.log('Hi! My name is ' + this.myName);
},
myName : 'Rebecca'
};
var secondObject = {
myName : 'Colin'
};
myObject.sayHello(); // logs 'Hi! My name is Rebecca'
myObject.sayHello.call(secondObject); //logs 'Hi! My name is Colin'
//*Function created using Function.bind
var myName = 'the global object',
sayHello = function () {
console.log('Hi! My name is ' + this.myName);
},
myObject = {
myName : 'Rebecca'
};
var myObjectHello = sayHello.bind(myObject);
sayHello(); // logs 'Hi! My name is the global object'
myObjectHello(); //logs 'Hi! My name is Rebecca'
//*A function being attached to an object at runtime
var myName = 'the global object',
sayHello = function() {
console.log('Hi! My name is ' + this.Name);
},
myObject = {
myName : 'Rebecca'
},
secondObject = {
myName : 'Colin'
};
myObject.sayHello = sayHello;
secondObject.sayHello = sayHello;
sayHello(); //logs 'Hi! My name is the global object'
myObject.sayHello(); //logs 'Hi! My name is Rebecca'
secondObject.sayHello(); //logs 'Hi! My name is Colin'
//*What happens to (this) if you store a variable deep in the function.
var myNamespace = {
myObject : {
sayHello : function() {
console.log('Hi! My name is ' + this.myName);
}
myName : 'Rebecca'
}
};
var hello = myNamespace.myObject;
obj.sayHello(); //logs 'Hi! My name is Rebecca'
//Scope - variables that are available to a piece of code at a given time. When a variable is declared in a function using the var keyword, it only codes inside that function. Code outsidethe function cannot access the variable unless there are functions inside that function. Also, if you do don't define the variable with var keyword, Javascript will move the scope chain all the way up to the window scope where the variable was previously defined. If it wasn't, it will be defined in the global scope.
//*Functions have access to variables defined in the same scope
var foo = 'hello';
var sayHello = function() {
console.log(foo);
};
sayHello(); //logs 'hello'
console.log(foo); //doesn't log anything
//*Code outside the scope in which a variable was defined does not have access to the variable
var sayHello = function() {
var foo = 'hello';
console.log(foo);
}
sayHello(); //logs 'hello'
console.log(foo); //doesn't log anything
//*Variables with the same name can exist in different scopes with different values
var foo = 'world';
var sayHello = function() {
var foo = 'hello';
console.log(foo);
};
sayHello(); //logs 'hello'
console.log(foo); //logs 'world'
//*Functions can "see" changes in vairbale values after the function is defined
var myFunction = function() {
var foo = 'hello';
var myFn = function() {
console.log(foo);
};
foo = 'world';
return myFn;
};
var f = myFunction();
f(); //logs 'world' --- not good
//*Scope insanity
//a self executing anonymous function
(function() {
var baz = 1;
var bim = function() {
alert(baz);
};
bar = function() {
alert(baz);
};
})();
console.log(baz); //baz is not defined outside of the function
bar(); //bar is defined outside of the anonymous function
//because it wasn't declared with var; furthermore,
//because it was defined in the same scope as baz,
//outside of the function does not
bim(); //bim is not defined outside of the anonymous function
//so this will result in an Error
//Closures - are an extension of the concept of scope. Can also be used to resolve issues with (otherwise)
//*How to lock the value of i.
/*this won't behave as we want it to; */
/* every click will alert 5 */
for (var i = 0; i < 5; i++) {
$('<p>click me</p>').appendTo('body').click(function() {
alert(i);
});
}
//*Locking in the value of i with a closure
/* fix: 'close' the value of i inside
createFunction, so it won't change */
var createFunction = function(i) {
return function() { alert(i); };
};
for (var i = 0; i < 5; i++) {
$('<p>click me</p>').appendTo('body').click(createFunction(i));
}
//*Using a closure to access inner and outer object instances simultaneously
var outerObj = {
myName : 'outer',
outerFunction : function () {
//provide a reference to outerObj
//through innerFunction's closure
var self = this;
var innerObj = {
myName : 'inner',
innerFunction : function () {
//logs 'outer inner'
console.log(self.myName, this.myName);
}
};
innerObj.innerFunction();
console.log(this.myName); //logs 'outer'
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment