You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
No issue using either single ' or double " quotes, it's all preference/styling
Loging to console
console.log('hello world!');console.log(123);console.log(true);vargreeting='Hello');console.log(greeting);console.log([1,2,3,4]);console.log({a:1,b:2})console.table({a:1,b:2})console.error('This is some error')console.clear();console.warn('This is a warning');console.time('Hello');// Time it takes to reach start to end of sectionconsole.log('hi');console.log('hi');console.log('hi');console.log('hi');console.timeEnd('Hello');
Comments
// Single Line Comment/*MultiLineComment*/
Defining Variables
var - basic javascript variable that's been around since the beinging
const - used to define a constant that cannot be changed
let - new way of assigning a variable, good for scoping
var
varname='John Doe';console.log(name);name='Steve Smith';console.log(name);// Init varvargreeting;console.log(greeting);greeting='Hello';console.log(greeting);// Can only contain letters, numbers, _, $// Can not start with a numbervarname='John';// leading with $ usually reserved to working with jquery// leading with _ usually reserved to private variables// just be safe and start with a letter// Multi word varsvarfirstName='John';// Camel case, used for most variablesvarfirst_name='Sara';// UnderscorevarFirstName='Tom';// Pascal case, usually used with classes and objectsvarfirstname;
letval;val=5;console.log(val);// 5console.log(typeofval);// numberconsole.log(val.length);// undefined - only works on strings!console.log(String(val));// Convert number to stringval=string(4+4)console.log(val);// '8'console.log(typeofval);// string
letvalval='5';val=Number(val);val=Number(true);// 1val=Number(false);// 0val=Number(null);// 0val=Number('hello');// NaN - Not a numberval=Number([1,2,3]);// NANconsole.log(val.toFixed(2));// Returns number to two decimal places
parseInt
letvalval=parseInt('100');// val = 100val=parseInt('100.34');// val = 100
parseFloat
letvalval=parseInt('100.34');// val = 100.34
Numbers/Math
constnum1=100;constnum2=50;letval;// simple math with numbersval=num1+num2;// 150val=num1*num2;// 5000val=num1-num2;// 50val=num1/num2;// 2val=num1%num2;// 0// math objectval=Math.PI;val=Math.E;val=Math.round(2.8);// round to 3val=Math.round(2.4);// round to 2val=Math.ceil(2.4);// 3val=Math.floor(2.8);// 2val=Math.sqrt(64);// 8val=Math.abs(-3);// 3val=Math.pow(8,2);//64val=Math.min(2,33,45,34,26);// 2val=Math.max(2,33,45,34,26);// 45val=Math.random();// random number 0-1val=Math.random()*20;// random number 0-19val=Math.floor(Math.random()*20+1);// random int 1-20
Strings
constfirstName='William';constlastName='Johnson';constage=30;conststr='Hello my name is Brad';consttags='web design,webdevelopment,programming';letval;val=firstName+lastName;// WilliamJohnson// Concatval=firstName+' '+lastName;// Appendval='Brad ';val+='Traversy';val='Hello, my name is '+firstName+' and I am '+age;// Escapingval='That\'s aswesome, I can\'t wait';// Lengthval=firstName.length;// don't need parens, property not method// concat()val=firstName.concat(' ',lastName);// William Johnson// Change caseval=firstname.toUpperCase();// WILLIAMval=lastName.toLowerCase();// johnson// Get character at positionval=firstName[2];// indexOf()val=firstName.indexOf('l');// 2val=firstName.lastIndexOf('l');// 3// charAt()val=firstName.charAt('2');// l// Get last charval=firstName.charAt(firstname.length-1);// m// substring()val=firstName.substring(0,4);// Will// slice()val=firstname.slice(0,4);// Willval=firstname.slice(-3);// iam// split()val=str.split(' ');// ['Hello', 'my', 'name', 'is', 'Brad']val=tags.split(',');// ['web design','web development','programming']// replace()val=str.replace('Brad','Jack');// includes() - returns bool if item is present in stringval=str.includes('Hello');// trueval=str.includes('Foo');// false
constnumbers=[43,56,33,23,44,36,5];constnumber2=newArray(22,45,33,76,54);constfruit=['Apple','Banana','Orange','Pear'];constmixed=[22,'Hello',true,undefined,null,{a:1,b:1},newDate()];// can hold any typeletval;// Get array lengthval=numbers.length;// 7// Check if is arrayval=Array.isArray(numbers);// trueval=Array.isArray("string");// false// Get single valueval=numbers[3];// 23val=numbers[0];// 43// Insert into arraynumbers[2]=100;// Find index of valueval=numbers.indexOf(36);// 5// Mutating arraysnumbers.push(250);// append to end of arraynumbers.unshift(120);// prepend to start of arraynumbers.pop();// pop item from endnumbers.shift();// remove item from start// splice()numbers.splice(1,1);// position to start, and end removalnumbers.splice(1,3);// removes 56, 33, 23// reverse()numbers.reverse();// returns array in reverse order// Concat arrayval=numbers.concat(numbers2);// array with both values in it// sort()val=fruit.sort();// sorted alphabeticallyval=numbers.sort();// sorts by first number, not what you want// use "compare function"val=numbers.sort(function(x,y){returnx-y;});// reverse sortval=numbers.sort(function(x,y){returny-x;});// find() - takes in a function for searchingfunctionunder50(num){returnnum<50;}val=numbers.find(under50);// iterates over items in list, passing value to function. Returns the first that satisfies function.console.log(numbers);console.log(val);
Object Literals
constperson={firstname: 'Steve',lastName: 'Smith',Age: 30,email: '[email protected]',hobbies: ['music','sports'],address: {city: 'Miami',state: 'FL'},getBirthYear: function(){return2017-this.age;// need to use this to make it local to the object}}letval;val=person;// Get specific valueval=person.firstName;// 'Steve'val=person['lastName'];val=person.age;// 30val=person.hobbies[1];// sportsval=person.address.state;// FLval=person['address']['city'];// Miamival=person.getBirthYear();// 1987console.log();// Array of objectsconstpeople=[{name: 'John',age: 30},{name: 'Mike'},age: 23},{name: 'Jane'},age: 32}];for(leti=0;i<people.length;i++){console.log(people[i].name);}
Date and Times
letval;consttoday=newDate();// Current date/timeletbirthday=newDate('9-10-1981 11:25:00');birthday=newDate('September 10 1981');birthday=newDate('9/10/1981');val=today;console.log(typeofval);// Dateval=birthday;// val=today.getMonth();// numerical representation of monthval=today.getDate();// numerical representation of dateval=today.getDay();// numerical representation of day of weekval=today.getFullYear();// yearval=today.getHours();// hoursval=today.getMinutes();// minute of hourval=today.getSeconds();// seconds of hourval=today.getMilliseconds();// milliseconds of hourval=today.getTime();// epoch timebirthday.setMonth(2);// March 10thbirthday.setDate(12);// March 12thbirthday.setFullYear(1985);// March 12th 1985birthday.setHours(3);birthday.setMinutes(30);birthday.setSeconds(25);console.log(val);
If Statemenets and comparison operators
constid=100;// Equal toif(id==100){console.log('CORRECT');}else{console.log('INCORRECT');}// Not Equal toif(id!=101){console.log('CORRECT');}else{console.log('INCORRECT');}// equal to value & typeif(id==='100'){console.log('CORRECT');}else{console.log('INCORRECT');}// not equal to value & typeif(id!=='100'){console.log('CORRECT');}else{console.log('INCORRECT');}// Test if undefinedif(typeofid!==undefined){console.log(`The ID is ${id}`);}else{console.log('NO ID');}// Greater or less thanif(id>200){console.log('CORRECT');}else{console.log('INCORRECT');}// if elseconstcolor='red';if(color==='red'){console.log('Color is red');}elseif(color==='blue'){console.log('Color is blue');}else{console.log('Color is not red or blue');}// Logical Operatorsconstname='Steve';constage=20;// And &&if(age>0&&age<12){console.log(`${name} is a child`);}elseif(age>=&&age<=19){console.log(`${name} is a teenager`);}else{console.log(`${name} is an adult`);}// Or ||if(age<16||age>65){console.log(`${name} can not run in race`);}else{console.log(`${name} is registered for the race`);}// Ternary operatorconsole.log(id===100 ? 'Correct': 'Incorrect');// without bracesif(id===100)console.log('Correct');elseconsole.log('Incorrect');
Switches
constcolor='red';switch(color){case'red':
console.log('Color is red');break;case'blue':
console.log('Color is blue');break;default:
console.log('Color is not red or blue');break;}letday;switch(newDate().getDay()){case0:
day='Sunday';breakcase1:
day='Monday';breakcase2:
day='Tuesday';breakcase3:
day='Wednesday';breakcase4:
day='Thursday';breakcase5:
day='Friday';breakcase6:
day='Saturday';break}console.log(`Today is ${day}`);
Functions expressions and Declarations
// declarationsfunctiongreet(){//console.log('Hello');return'Hello';}console.log(greet());// pass in arguementsfunctiongreet(firstName,lastName){//console.log('Hello');return'Hello '+firstName+' '+lastName;}console.log(greet('John','Doe'));// default parameters in es5functiongreet(firstName,lastName){if(typeoffirstName==='undefined'){firstName='John'}if(typeoflastName==='undefined'){lastName='Doe'}return'Hello '+firstName+' '+lastName;}console.log(greet());// default parameters in es6functiongreet(firstName='John',lastName='Doe'){return'Hello '+firstName+' '+lastName;}console.log(greet());// function expressions - putting a function as a variable assignmentconstsquare=function(x=3){returnx*x;};console.log(square(8));// Immidiately invokable function expressions - IIFEs// Function runs as soon as declared(function()){console.log('IFFE Ran...');})();// with parameters(function(name)){console.log('Hello '+name);})('Brad');// Property Methodsconsttodo={add: function(){console.log('Add todo..');},edit: function(id){console.log(`Edit todo ${id}`);}}todo.delete=function(id){console.log(`Delete todo ${id}`);}todo.add();todo.edit(22);todo.delete(22);
Loops and itterations
Loops
// For loopfor(leti=0;i<10;i++){console.log(i);}// continue and breakfor(leti=0;i<10;i++){if(i===2){console.log('2 is my favorite number');continue;// Goes to next itteration without continuing}if(i===5){console.log('Stop the loop');break;// kills the loop}console.log('Number '+i);}// While loopleti=0;while(i<10){console.log(`Number ${i}`);i++;}// Do while - always runs at least onceleti=0;do{console.log(`Number ${i}`);i++;}while(i<10);// Looping through arraysconstcars=['Ford','Chevy','Honda','Toyota'];for(leti=0;i<cars.length;i++){console.log(cars[i]);}// forEach array loopconstcars=['Ford','Chevy','Honda','Toyota'];cars.forEach(function(car){console.log(car);});// forEach extra parametersconstcars=['Ford','Chevy','Honda','Toyota'];cars.forEach(function(car,index,array){console.log(`${index}: ${car}`);console.log(array;)});// Map - create an array based on specified parametersconstusers=[{id:1,name: 'John'},{id:2,name: 'Sarah'},{id:3,name: 'Karen'}];constids=users.map(function(user){returnuser.id;});console.log(ids);// [1, 2, 3]// For in loop (used with objects)constuser={firstName: 'John',lastName: 'Doe',age: 40}for(letxinuser){// will set the key of each value in user to xconsole.log(x);console.log(`${x}: ${user[x]}`)}
Window Methods, Objects, Properties
// Alertwindow.alert('hello world');// Prompt - pop up with text boxconstinput=prompt();alert(input);// Confirm - pop up confirmation boxif(confirm('Are you sure?')){console.log('YES');}else{// If cancel selected...console.log('NO');}// Outter height and widthletval;val=window.outerHeight;val=window.outerWidth;// Inner height and widthletval;val=window.innerHeight;val=window.innerWidth;// Scroll points - where the scroll bar is atletval;val=window.scrollY;val=window.scrollX;// Location Object - page informationletval;val=window.location;val=window.location.hostname;val=window.location.port;val=window.location.hrefval=window.location.search;// Redirectwindow.location.href='http://google.com';// Reloadwindow.location.reload();// Hisotry Objectwindow.history.go(-1);// Goes back to last history by indexval=window.history.length;// Navigator Objectval=window.navigator;val=window.navigator.appName;val=window.navigator.appVersion;val=window.navigator.userAgent;val=window.navigator.platform;val=window.navigator.vendor;val=window.navigator.language;
Scope
// Global Scopevara=1;letb=2;constc=3;functiontest(){vara=4;letb=5;constc=6;console.log('Function Scope: ',a,b,c);}test();// Block scopeif(true){vara=4;// global a will be overritten by this line. var is weird, and is always globalletb=5;constc=6;console.log('Function Scope: ',a,b,c);}for(leta=0;a<10;a++){console.log(`Loop: ${a}`);}console.log('Global Scope: ',a,b,c);