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
varmyString='Hello World';varmyNumber=42;// the meaning of life of coursevarmyBoolean=true;
ARRAYS
Defining
varmyArray=['Value 1','Value 2','Value 3'];
Retrieving a value
myArray[1];// outputs "Value 2"
Retriving length
myArray.length;// outputs 3
Iterating (using for)
for(i=0;i<myArray.length;i++){console.log(i);// logs the current interation's indexvarsomeValueFromArray=myArray[i];// stores the array value in a variableconsole.log(someValueFromArray);// logs the array value// ... additional repeating code here}
Iterating (using forEach)
myArray.forEach(function(myValue,myIndex){console.log(myValue);// logs the array valueconsole.log(myIndex);// logs the current interation's index});
Searching (by value)
varfoundIndex=myArray.indexOf('Value 2');// stores the found index in a variablevarfoundValue=myArray[foundIndex];// store the found value in a variableconsole.log(foundIndex,foundValue);// logs both the index and value (`console.log` supports infinite arguments)
Searching (for non-existence)
varfoundIndex=myArray.indexOf('Something Not Here');// stores the found index in a variableif(foundIndex===-1){console.log('not here');// logs not here}
Adding to (push())
myArray.push('Value 4');// note the above line does not require an variable additional assignmentconsole.log(myArray);// logs "['Value 1', 'Value 2', 'Value 3', 'Value 4']"
Adding to (concat())
varsomeOtherArray=['Value 4'];myArray=myArray.concat(someOtherArray);myArray=myArray.concat(['Value 5']);// note the above line requires an additional variable assignment (`myArray = ...`)// also note you pass an array into concat() instead of a valueconsole.log(myArray);// logs "['Value 1', 'Value 2', 'Value 3', 'Value 4', 'Value 5']"
OBJECTS
Defining
varcar={// define our object with the below properties and valuesmake: 'Volkswagen',// defines a stringmodel: 'Jetta',year: 2006,// defines a numberodometer: 41077,// ALOTT ;)'fuel type': 'Gasoline',// defines a string with a property including a spacecheckEngineLightOn: true,// defines a booleanfixCar: function(){// defines a function (known as an object's "method")this.checkEngineLightOn=false;// the use of `this` above is how we can modify object values from an objects function/method},drive: function(tripDistance){this.odometer=this.odometer+tripDistance;// add our trip's distnace to our car's odometer},clean: function(wash,wax,vacuum){varmessage="You've ";// initialize a string for us to concatenate values ontoif(wash){message=message+'washed ';// concat the word washed to the message}if(wax){message=message+'waxed ';}if(vacuum){message=message+'vacuumed ';}message=mesage+'your car.';returnmessage;// returns "You've washed waxed vacuumed your car." if all values are true.}};
Assigning values (using dot notation)
car.make='Nissan';// Changes the make property from 'Volkswagen' to 'Nissan'
Assigning values (using [] aka brackets**)
car['fuel type']='Diesel';// needed for properties with spaces
Retrieving a value
varmyYear=car.year;// stores the car's year in a variable named `myYear`console.log(year);// logs the cars year 2006
Executing a method
car.fixCar();// executes the `fixCar` method thus setting the check engine light to false (turning it off)
Executing a method (arguments)
car.drive(100);// executes the `drive` method thus adding 100 miles to the odometer
Executing a method (multiple arguments)
varmyCarsCleanliness=car.clean(true,false,false);// executes and stores the `clean` (performing only a wash, the first argument) method's return value in a variable `myCarsCleanliness`.console.log(myCarsCleanliness);// logs "You've washed your car."
FUNCTIONS
Defining (in global or current scope)
functionmyFunction(){// ... your logic here between the braces {}}
Defining (as a variable)
varmyFunction=function(){// ... your logic here between the braces {} }
Executing
myFunction();
Defining (multiple arguments)
functionmyFunction(someString,someBoolean,someNumber){// ... your logic here between the braces {} }
Executing (multiple arguments)
myFunction('a string', true, 1337);
CONDITIONALS
if conditional
variLikePizza=true;// store a boolean valueif(iLikePizza){// ... your logic to perform if you like pizza between the braces {}}
if/else conditional
variLikeBurgers=true;// store a boolean valueif(iLikeBurgers){// ... your logic to perform if you like burgers between the braces {}}else{// ... your logic to perform if you don't like burgers between the braces {}}
if/else if/else conditional
varsteakPreference=prompt('How do you like your steak?');// store a string value from user inputif(steakPreference==='rare'){// NOTE the triple equal, this indicates a comparison instead of an assignment// ... your logic to perform if you prefer rare steak between the braces {}}elseif(steakPreference==='medium rare'){// ... your logic to perform if you prefer medium rare steak between the braces {}}else{// ... your logic to perform if you prefer steak any other way between the braces {}}
if (multiple conditions)
// variables from abovevarage=40;if(age>18&&age<21){console.log('you can smoke but you can\'t drink');}elseif(age<18){console.log('stay healthy youngin');}else{console.log('PARTYYYYYYY');// we're 40, we party... hard.}
if/else (nested)
varisSitting=confirm('Are you sitting?');// store a boolean value from user inputif(isSitting){// NOTE the triple equal, this indicates a comparison instead of an assignmentvarlastStoodUp=prompt('How many minutes has it been since you stood up?');if(lastStoodUp>8){// ... your logic to perform if user stood up 8+ minutes ago sitting between the braces {}alert('You should stand up!');}else{// ... your logic to perform if user stood up less than or equal to 8 minutes ago sitting between the braces {}}}else{// ... your logic to perform if user isn't sitting between the braces {}}
varmyGreenAndBoldDiv=document.querySelector('.green.bold');// stores the second element above in a JavaScript variable
Setting an element's inner content
myTitleElement.textContent='My Portfolio';// sets the text of the `<h1>` above// this populates the h1 and results in this on your page:// <header><h1>My Portfolio</h1></header>
Setting an element's inner content (which includes some HTML)
myTitleElement.innerHTML='<a href="/portfolio.html">My Portfolio</a>';// this populates the h1 with HTML and results in this on your page:// <header><h1><a href="/portfolio.html">My Portfolio</a></h1></header>
Creating and manipulating a new element
mySubtitleElement=document.createElement('h2');// stores a new h2 in a JavaScript variablemySubtitleElement.textContent='My portfolio is the best!';// sets the inner text of the stored variable
Appending new element the page (using appendChild())
varmyHeader=document.getElementById('my-header');// store where we want to put our new elementmyHeader.appendChild(mySubtitleElement);// append the previously created h2 to the `<header>` element// this appends the h2 and results in this on your page:// <header><h1>My Portfolio</h1><h2>My portfolio is the best!</h2></header>
DOM Events
Keyboard Press
document.onkeyup=function(e){console.log(e.key);// logs the user's key input when they release the key};
Other Helpful Items
Combining strings (using +)
varage=40;varhello='Hello, I am Chris, I am NOT '+age+'... yet';// above line concatinates our string and age variable and stores them in a new variableconsole.log(hello);// logs "Hello, I am Chris, I am NOT 40... yet"
varage=40;varhello=`Hello, I am Chris, I am NOT ${age}... yet`;// above line concatinates our string and age variable and stores them in a new variableconsole.log(hello);// logs "Hello, I am Chris, I am NOT 40... yet"
Random Number (one of a few methods)
varmyRandomNumber=Math.floor(Math.random()*10)+1;// stores a random number between 1 and 10 in a variable named `myRandomNumber
Case Changing
varleetString='SooO LeEt';varquietString=leetString.toLowerCase();varloudString=leetString.toUpperCase();console.log(quietString,loudString);// logs "sooo leet" and "SOOO LEET"