// This is an in-line comment./* This is amulti-line comment */JavaScript provides seven different data types:
| Data Types | Examples |
|---|---|
undefined | A variable that has not been assigned a value is of type undefined. |
null | no value. |
string | 'a', 'aa', 'aaa', 'Hello!', '11 cats' |
number | 12, -1, 0.4 |
boolean | true, false |
object | A collection of properties. |
symbol | Represents a unique identifier. |
// declare a variablevarourName;// store valuesmyNumber=5;myString="myVar";// declare variables with the assignment operatorvarmyNum=0;// add, subtract, multiply and divide numbersmyVar=5+10;// 15myVar=12-6;// 6myVar=13*13;// 169myVar=16/2;// 8// increment and decrement numbersi++;// the equivalent of i = i + 1i--;// the equivalent of i = i - 1;// decimalsvarourDecimal=5.7;// float- Unlike
var,letthrows an error if you declare the same variable twice. - Variables declared with
letinside a block, statement, or expression, its scope is limited to that block, statement, or expression. - Variables declared with
constare read-only and cannot be reassigned. - Objects (including arrays and functions) assigned to a variable using
constare still mutable and only prevents the reassignment of the variable identifier.
To ensure your data doesn't change, JavaScript provides a function Object.freeze to prevent data mutation.
letobj={name: "FreeCodeCamp",review: "Awesome"};Object.freeze(obj);obj.review="bad";//will be ignored. Mutation not allowedobj.newProp="Test";// will be ignored. Mutation not allowedconsole.log(obj);// { name: "FreeCodeCamp", review:"Awesome"}// escape literal quotesvarsampleStr='Alan said, "Peter is learning JavaScript".';// this prints: Alan said, "Peter is learning JavaScript".// concatenating stringsvarourStr="I come first. "+"I come second.";// concatenating strings with +=varourStr="I come first. ";ourStr+="I come second.";// constructing strings with variablesvarourName="freeCodeCamp";varourStr="Hello, our name is "+ourName+", how are you?";// appending variables to stringsvaranAdjective="awesome!";varourStr="freeCodeCamp is ";ourStr+=anAdjective;| Code | Output |
|---|---|
\' | single quote (') |
\" | double quote (") |
\\ | backslash (\) |
\n | newline |
\r | carriage return |
\t | tab |
\b | backspace |
\f | from feed |
"Alan Peter".length;// 10letstr='a string';letsplittedStr=str.split('');// [ 'a', ' ', 's', 't', 'r', 'i', 'n', 'g' ]letjoinedStr=splittedStr.join('')// a string//first element has an index of 0varfirstLetterOfFirstName="";varfirstName="Ada";firstLetterOfFirstName=firstName[0];// A// find the las character of a stringvarfirstName="Ada";varlastLetterOfFirstName=firstName[firstName.length-1];// aconstperson={name: "Zodiac Hasbro",age: 56};// Template literal with multi-line and string interpolationconstgreeting=`Hello, my name is ${person.name}!I am ${person.age} years old.`;console.log(greeting);// Hello, my name is Zodiac Hasbro!// I am 56 years old.varsandwich=["peanut butter","jelly","bread"][// nested arrays(["Bulls",23],["White Sox",45])];varourArray=[50,60,70];varourData=ourArray[0];// equals 50// modify an array with indexesvarourArray=[50,40,30];ourArray[0]=15;// equals [15,40,30]// access multi-dimensional arrays with indexesvararr=[[1,2,3],[4,5,6],[7,8,9],[[10,11,12],13,14]];arr[3];// [[10,11,12], 13, 14]arr[3][0];// [10,11,12]arr[3][0][1];// 11// reverse an array[1,'two',3].reverse()// [ 3, 'two', 1 ]// push() to append data to the end of an arrayvararr=[1,2,3];arr.push(4);// arr is now [1,2,3,4]// pop() to "pop" a value off of the end of an arrayvarthreeArr=[1,4,6];varoneDown=threeArr.pop();console.log(oneDown);// Returns 6console.log(threeArr);// Returns [1, 4]// shift() removes the first element of an arrayvarourArray=[1,2,[3]];varremovedFromOurArray=ourArray.shift();// removedFromOurArray now equals 1 and ourArray now equals [2, [3]].// unshift() adds the element at the beginning of the arrayvarourArray=["Stimpson","J","cat"];ourArray.shift();// ourArray now equals ["J", "cat"]ourArray.unshift("Happy");// ourArray now equals ["Happy", "J", "cat"]// first parameter is the index, the second indicates the number of elements to delete.letarray=['today','was','not','so','great'];array.splice(2,2);// remove 2 elements beginning with the 3rd element// array now equals ['today', 'was', 'great']// also returns a new array containing the value of the removed elementsletarray=['I','am','feeling','really','happy'];letnewArray=array.splice(3,2);// newArray equals ['really', 'happy']// the third parameter, represents one or more elements, let us add themfunctioncolorChange(arr,index,newColor){arr.splice(index,1,newColor);returnarr;}letcolorScheme=['#878787','#a08794','#bb7e8c','#c9b6be','#d1becf'];colorScheme=colorChange(colorScheme,2,'#332327');// we have removed '#bb7e8c' and added '#332327' in its place// colorScheme now equals ['#878787', '#a08794', '#332327', '#c9b6be', '#d1becf']// Copies a given number of elements to a new array and leaves the original array untouchedletweatherConditions=['rain','snow','sleet','hail','clear'];lettodaysWeather=weatherConditions.slice(1,3);// todaysWeather equals ['snow', 'sleet'];// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']letfruits=['apples','pears','oranges','peaches','pears'];fruits.indexOf('dates')// -1fruits.indexOf('oranges')// 2fruits.indexOf('pears')// 1, the first index at which the element existsvarourPets=[{animalType: "cat",names: ["Meowzer","Fluffy","Kit-Cat"]},{animalType: "dog",names: ["Spot","Bowser","Frankie"]}];ourPets[0].names[1];// "Fluffy"ourPets[1].names[0];// "Spot"letfruits=["Banana","Orange","Apple","Mango"];fruits.includes("Mango");// true// The ES5 code below uses apply() to compute the maximum value in an array.vararr=[6,89,3,45];varmaximus=Math.max.apply(null,arr);// 89// ...arr returns an unpacked array. In other words, it spreads the array.constarr=[6,89,3,45];constmaximus=Math.max(...arr);// 89// copy an arrayletthisArray=[true,true,undefined,false,null];letthatArray=[...thisArray];// thatArray equals [true, true, undefined, false, null]// thisArray remains unchanged, and is identical to thatArray// combine arraysletthisArray=['sage','rosemary','parsley','thyme'];letthatArray=['basil','cilantro', ...thisArray,'coriander'];// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']const[a,b]=[1,2,3,4,5,6];console.log(a,b);// 1, 2// it can access any value by using commas to reach the desired indexconst[a,b,,,c]=[1,2,3,4,5,6];console.log(a,b,c);// 1, 2, 5// to collect the rest of the elements into a separate array.const[a,b, ...arr]=[1,2,3,4,5,7];console.log(a,b);// 1, 2console.log(arr);// [3, 4, 5, 7]varcat={name: "Whiskers",legs: 4,tails: 1,enemies: ["Water","Dogs"]};Accessing with dot (.) notation
varmyObj={prop1: "val1",prop2: "val2"};varprop1val=myObj.prop1;// val1varprop2val=myObj.prop2;// val2Accessing with bracket ([]) notation
varmyObj={"Space Name": "Kirk","More Space": "Spock",NoSpace: "USS Enterprise"};myObj["Space Name"];// KirkmyObj["More Space"];// SpockmyObj["NoSpace"];// USS EnterpriseAccessing with variables
vardogs={Fido: "Mutt",Hunter: "Doberman",Snoopie: "Beagle"};varmyDog="Hunter";varmyBreed=dogs[myDog];console.log(myBreed);// "Doberman"Accessing and modifying Nested Objects
letuserActivity={id: 23894201352,date: 'January 1, 2017',data: {totalUsers: 51,online: 42}};userActivity.data.online=45;// oruserActivity['data'].online=45;// oruserActivity['data']['online']=45;Creating an array from the keys of an object
letusers={Alan: {age: 27,online: false},Jeff: {age: 32,online: true},Sarah: {age: 48,online: false},Ryan: {age: 19,online: true}};functiongetArrayOfUsers(obj){letarr=[];for(letkeyinobj){arr.push(key)}returnarr;}// Updating object propertiesvarourDog={name: "Camper",legs: 4,tails: 1,friends: ["everything!"]};ourDog.name="Happy Camper";// orourDog["name"]="Happy Camper";// add new propertiesourDog.bark="bow-wow";// orourDog["bark"]="bow-wow";// delete propertiesdeleteourDog.bark;varalpha={1:"Z",2:"Y",3:"X",4:"W",
...
24:"C",25:"B",26:"A"};alpha[2];// "Y"alpha[24];// "C"varvalue=2;alpha[value];// "Y"varmyObj={top: "hat",bottom: "pants"};myObj.hasOwnProperty("top");// truemyObj.hasOwnProperty("middle");// falsevarourStorage={desk: {drawer: "stapler"},cabinet: {"top drawer": {folder1: "a file",folder2: "secrets"},"bottom drawer": "soda"}};ourStorage.cabinet["top drawer"].folder2;// "secrets"ourStorage.desk.drawer;// "stapler"// Consider the following ES5 codevarvoxel={x: 3.6,y: 7.4,z: 6.54};varx=voxel.x;// x = 3.6vary=voxel.y;// y = 7.4varz=voxel.z;// z = 6.54// the same assignment statement with ES6 destructuring syntaxconst{ x, y, z }=voxel;// x = 3.6, y = 7.4, z = 6.54// to store the values of voxel.x into a, voxel.y into b, and voxel.z into c, you have that freedom as wellconst{x: a,y: b,z: c}=voxel;// a = 3.6, b = 7.4, c = 6.54// Destructuring Variables from Nested Objectsconsta={start: {x: 5,y: 6},end: {x: 6,y: -9}};const{start: {x: startX,y: startY}}=a;console.log(startX,startY);// 5, 6// destructure the object in a function argument itself.constprofileUpdate=profileData=>{const{ name, age, nationality, location }=profileData;// do something with these variables};// this can also be done in-place:constprofileUpdate=({ name, age, nationality, location })=>{/* do something with these fields */};constgetMousePosition=(x,y)=>({x: x,y: y});// the same function rewritten to use this new syntax:constgetMousePosition=(x,y)=>({ x, y });Booleans may only be one of two values: true or false. They are basically little on-off switches, where true is "on" and false is "off". These two states are mutually exclusive.
true;false;if(conditionistrue){statementisexecuted}if(num>10){return"Bigger than 10";}else{return"10 or Less";}if(num>15){return"Bigger than 15";}elseif(num<5){return"Smaller than 5";}else{return"Between 5 and 15";}// this if statement...functionfindGreater(a,b){if(a>b){return"a is greater";}else{return"b is greater";}}// is equivalent to this ternary operatorfunctionfindGreater(a,b){returna>b ? "a is greater" : "b is greater";}// this if statement...functionfindGreaterOrEqual(a,b){if(a===b){return"a and b are equal";}elseif(a>b){return"a is greater";}else{return"b is greater";}}// is equivalent to this ternary operatorfunctionfindGreaterOrEqual(a,b){returna===b
? "a and b are equal"
: a>b
? "a is greater"
: "b is greater";}switch(num){casevalue1:
statement1;break;casevalue2:
statement2;break;
...
casevalueN:
statementN;break;}switch(num){casevalue1:
statement1;break;casevalue2:
statement2;break;
...
default:
defaultStatement;break;}switch(val){case1:
case2:
case3:
result="1, 2, or 3";break;case4:
result="4 alone";}| Operator | Meaning |
|---|---|
== | Equality |
=== | Strict Equality |
!= | Inequality |
!== | Strict Inequality |
> | Greater Than |
>= | Greater or Equal Than |
< | Less Than |
<= | Less or Equal Than |
&& | And |
| ` |
varourArray=[];vari=0;while(i<5){ourArray.push(i);i++;}varourArray=[];vari=0;do{ourArray.push(i);i++;}while(i<5);varourArray=[];vari=0;while(i<5){ourArray.push(i);i++;}// Count Backwards With a For LoopvarourArray=[];for(vari=10;i>0;i-=2){ourArray.push(i);}// Iterate Through an Arrayvararr=[10,9,8,7,6];for(vari=0;i<arr.length;i++){console.log(arr[i]);}// Nested for loopsvararr=[[1,2],[3,4],[5,6]];for(vari=0;i<arr.length;i++){for(varj=0;j<arr[i].length;j++){console.log(arr[i][j]);}}for(letvalueofmyArray){console.log(value);}functionfunctionName(){console.log("Hello World");}functionName();// call the functionfunctionourFunctionWithArgs(a,b){console.log(a-b);}ourFunctionWithArgs(10,5);// 5functionplusThree(num){returnnum+3;}varanswer=plusThree(5);// 8(function(){console.log("A cozy nest is ready");})()constmyFunc=function(){constmyVar="value";returnmyVar;};// can be rewritten like thisconstmyFunc=()=>{constmyVar="value";returnmyVar;};// and if there is no function body, and only a return valueconstmyFunc=()=>"value";// to pass parameters to an arrow functionconstdoubler=item=>item*2;FBPosts.filter(function(post){returnpost.thumbnail!==null&&post.shares>100&&post.likes>500;});// the previous function can be rewritten like thisFBPosts.filter(post=>post.thumbnail!==null&&post.shares>100&&post.likes>500);With the rest operator, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.
functionhowMany(...args){return"You have passed "+args.length+" arguments.";}console.log(howMany(0,1,2));// You have passed 3 argumentsconsole.log(howMany("string",null,[1,2,3],{}));// You have passed 4 arguments.// When defining functions within objects in ES5, we have to use the keyword functionconstperson={name: "Taylor",sayHello: function(){return`Hello! My name is ${this.name}.`;}};// With ES6, You can remove the function keyword and colonconstperson={name: "Taylor",sayHello(){return`Hello! My name is ${this.name}.`;}};| Character | Description |
|---|---|
\ | Escapes a special character. |
| ` | ` |
i | This flag is used to ignore upper and lowercase. /ignorecase/i. |
g | Search or extract a pattern more than once. |
. | The wildcard character . will match any character except new lines. |
[] | Allow you to define the characters to match. /b[au]g/ will match "bag", "bug" but not "bog". |
[a-z] | Match all the characters between a and z. |
[1-9] | Match all the numbers between 1 and 9. |
[a-z1-9] | Match all the character between a and z, and the numbers between 1 and 9. |
[^] | Match the characters not in the set. [^a-e] match all other characters except A, B, C, D, and E. |
+ | Match 1 or more occurrences of the previous character in a row. |
* | Match 0 or more occurrences of the previous character. |
? | Match 0 or 1 occurrence of the previous character. Useful for Lazy matching. |
^ | Search for patterns at the beginning of strings. |
$ | Search for patterns at the end of a string. |
\w | Equal to [A-Za-z0-9_]. Matches upper, lowercase, numbers the and underscore character (-). |
\W | Matches any nonword character. Equivalent to [^a-za-z0-9_]. |
\d | Equal to [0-9]. Match one digit. |
\D | Equal to [^0-9]. Match one non digit. |
\s | Match a whitespace. |
\S | Match everything except whitespace. |
a{2,5} | Match the letter a between 3 and 5 times. |
a{2,} | Specify only the lower number of matches. |
a{5} | Specify the exact number of matches. |
(...) | Specify a group that can be acceded with number (from 1) |
| Method | Description |
|---|---|
test() | Returns true or false if the pattern match a string or not. |
match() | Extract the actual matches found. |
replace() | Search and replace text in a string . |
// test method returns true or false if the pattern match a string or notletmyString="Hello, World!";letmyRegex=/Hello/;letresult=myRegex.test(myString);// extract the matches of a regex with the match methodletextractStr="Extract the word 'coding' from this string.";letcodingRegex=/coding/;letresult=extractStr.match(codingRegex);// Search and replaceletwrongText="The sky is silver.";letsilverRegex=/silver/;wrongText.replace(silverRegex,"blue");// Returns "The sky is blue."// search for multiple patterns using the alternation or OR operator: |letpetString="James has a pet cat.";letpetRegex=/dog|cat|bird|fish/;letresult=petRegex.test(petString);// ignore upper or lowercaseletmyString="freeCodeCamp";letfccRegex=/freeCodeCamp/i;// flag iletresult=fccRegex.test(myString);// Search or extract a pattern more than oncelettwinkleStar="Twinkle, twinkle, little star";letstarRegex=/Twinkle/gi;// a regex can have multiple flagsletresult=twinkleStar.match(starRegex);// The wildcard character . will match any character except new lines.letexampleStr="Let's have fun with regular expressions!";letunRegex=/.un/;letresult=unRegex.test(exampleStr);// define the characters to match, in this example all the vowels in quoteSampleletquoteSample="Beware of bugs in the above code; I have only proved it correct, not tried it.";letvowelRegex=/[aeiou]/gi;letresult=quoteSample.match(vowelRegex);// Match all the characters in quoteSample (between a and z)letquoteSample="The quick brown fox jumps over the lazy dog.";letalphabetRegex=/[a-z]/gi;letresult=quoteSample.match(alphabetRegex);// Match all the character between two characters and numbersletquoteSample="Blueberry 3.141592653s are delicious.";letmyRegex=/[h-s2-6]/gi;letresult=quoteSample.match(myRegex);// Match all that is not a number or a vowelletquoteSample="3 blind mice.";letmyRegex=/[^aeiou0-9]/gi;letresult=quoteSample.match(myRegex);// Match 1 or more occurrences of the previous character (* for 0 or more)letdifficultSpelling="Mississippi";letmyRegex=/s+/g;letresult=difficultSpelling.match(myRegex);// ? Match 0 or 1 occurrence of the previous character. Useful for Lazy matchinglettext="titanic";letmyRegex=/t[a-z]*?i/;letresult=text.match(myRegex);// Search for patterns at the beginning of stringsletrickyAndCal="Cal and Ricky both like racing.";letcalRegex=/^Cal/;letresult=calRegex.test(rickyAndCal);// Search for patterns at the end of a stringletcaboose="The last car on a train is the caboose";letlastRegex=/caboose$/;letresult=lastRegex.test(caboose);// \w is equal to [A-Za-z0-9_]letquoteSample="The five boxing wizards jump quickly.";letalphabetRegexV2=/\w/g;letresult=quoteSample.match(alphabetRegexV2).length;// Match only 3 to 6 letter h's in the word "Oh no"letohStr="Ohhh no";letohRegex=/Oh{3,6}no/;letresult=ohRegex.test(ohStr);// Match both the American English (favorite) and the British English (favourite) version of the wordletfavWord="favorite";letfavRegex=/favou?rite/;letresult=favRegex.test(favWord);// Groups () let you reuse patternsletrepeatNum="42 42 42";letreRegex=/^(\d+)\s\1\s\1$/;// every 1 represent the group (\d+)letresult=reRegex.test(repeatNum);// Remove all the spaces at the beginning an end of a stringlethello=" Hello, World! ";letwsRegex=/^\s+(.*\S)\s+$/;letresult=hello.replace(wsRegex,'$1');// returns 'Hello, World!'letduck={name: "Aflac",numLegs: 2,sayName: function(){return"The name of this duck is "+this.name+".";}};duck.sayName();// Returns "The name of this duck is Aflac."Constructors follow a few conventions:
- Constructors are defined with a capitalized name to distinguish them from other functions that are not constructors.
- Constructors use the keyword this to set properties of the object they will create. Inside the constructor, this refers to the new object it will create.
- Constructors define properties and behaviors instead of returning a value as other functions might.
// constructorfunctionBird(name,color){this.name=name;this.color=color;}// create a new instance of Birdletcardinal=newBird("Bruce","red");letduck=newBird("Donald","blue");// access and modify blueBird objectcardinal.name// Brucecardinal.color// redcardinal.color=green;cardinal.color// green// check if an object is an instance of a constructorcardinalinstanceofBird;// truecrowinstanceofBird;// false// check an objects own (name, color, numLegs) propertiescardinal.hasOwnProperty('color')// truecardinal.hasOwnProperty('age')// false//check an objects properties with the constructor propertycardinal.constructor===Bird;// true// use constructor.prototype to add new properties to object constructorsBird.prototype.cute=true;cardinal.cute// truecrow.cute// true// add more than one property and method to a constructorBird.prototype={constructor: Bird,// specify the constructornumLegs: 2,// new propertyeat: function(){// new methodconsole.log("nom nom nom");},describe: function(){// new methodconsole.log("My name is "+this.name);}};letchicken=newBird("Dinner","brown");chicken.numLegs// 2chicken.eat()// nom nom nomchicken.describe()// My name is DinnerfunctionAnimal(){}Animal.prototype={constructor: Animal,eat: function(){console.log("nom nom nom");}};functionCat(name){this.name=name;}// make the Cat constructor inherit the eat function from AnimalCat.prototype=Object.create(Animal.prototype);letmyCat=newCat('charles');myCat.eat()// nom nom nomAdd methods after Inheritance and override them
functionAnimal(){}Animal.prototype.eat=function(){console.log("nom nom nom");};// Dog constructorfunctionDog(){}// make the Gog constructor inherit the eat function from AnimalDog.prototype=Object.create(Animal.prototype);Dog.prototype.constructor=Dog;Dog.prototype.bark=function(){console.log("wof wof!");};// the new object will have both, the inherited eat() and its own bark() methodletbeagle=newDog();beagle.eat();// "nom nom nom"beagle.bark();// "Woof!"// override an inherited methodDog.prototype.eat=function(){return"nice meeeeat!";};letdoberman=newDog();doberman.eat()// nice meeeeat!A mixin allows unrelated objects to use a collection of functions.
letbird={name: "Donald",numLegs: 2};letboat={name: "Warrior",type: "race-boat"};// this mixin contain the glide methodconstglideMixin=function(obj){obj.glide=function(){console.log("gliding...");}}// the object is passed to the mixin and the glide method is assignedglideMixin(bird);glideMixin(boat);bird.glide();// "gliding..."boat.glide();// "gliding..."In JavaScript, a function always has access to the context in which it was created. This is called closure. Now, the property can only be accessed and changed by methods also within the constructor function. In JavaScript, this is called closure.
functionBird(){// instead of this.hatchedEgg...lethatchedEgg=10;// private propertythis.getHatchedEggCount=function(){// publicly available method that a bird object can usereturnhatchedEgg;};}letducky=newBird();ducky.hatchedEgg=2;// nothing happensducky.getHatchedEggCount;// 10An immediately invoked function expression (IIFE) is often used to group related functionality into a single object or module.
letfunModule=(function(){return{isCuteMixin: function(obj){obj.isCute=function(){returntrue;};},singMixin: function(obj){obj.sing=function(){console.log("Singing to an awesome tune");};}}})()functionDog(){}letgoodBoy=newDog;// assign the singMixin method to the goodBoy objectfunModule.singMixin(goodBoy);goodBoy.sing()// Singing to an awesome tuneES6 provides a new syntax to help create objects, the keyword class.The class syntax
is just a syntax, and not a full-fledged class based implementation of object oriented paradigm,
unlike in languages like Java, or Python, or Ruby etc.
classBook{constructor(title,author,year){this.title=title;this.author=author;this.year=year;}getSummary(){return`${this.title} was written by ${this.author} in ${this.year}`}getAge(){constyears=newDate().getFullYear()-this.year;return`${this.title} is ${years} years old`}}book=newBook('Book One','John Doe',2016);book.getSummary();// Book One was written by John Doe in 2016 book.getAge();// Book One is 3 years oldclassBook{constructor(author){this._author=author;}// gettergetwriter(){returnthis._author;}// settersetwriter(updatedAuthor){this._author=updatedAuthor;}}constlol=newBook("anonymous");console.log(lol.writer);// anonymouslol.writer="wut";console.log(lol.writer);// wutStatic methods allow using methods without instantiating an object
classBook{constructor(title,author,year){this.title=title;this.author=author;this.year=year;}staticsayHi(){return"Hi!"}}Book.sayHi();// Hi!classBook{constructor(title,author,year){this.title=title;this.author=author;this.year=year;}getSummary(){return`${this.title} was written by ${this.author} in ${this.year}`}}classMagazineextendsBook{constructor(title,author,year,month){super(title,author,year)this.month=month;}sayHi(){return"Hi!"}}mag=newMagazine('Mag','People',2019,'jan');mag.getSummary();// Mag was written by People in 2019 mag.sayHi();// Hi!varwatchList=[{"Title": "Inception","imdbRating": "8.8","Type": "movie",},{"Title": "Interstellar","imdbRating": "8.6","Type": "movie",},{"Title": "The Dark Knight","imdbRating": "9.0","Type": "movie",},{"Title": "Batman Begins","imdbRating": "7.9","Type": "movie",}];constrating=watchList.map(function(movie){return{title: movie.Title,rating: movie.imdbRating}});/* [ { title: 'Inception', rating: '8.8' }, { title: 'Interstellar', rating: '8.6' }, { title: 'The Dark Knight', rating: '9.0' }, { title: 'Batman Begins', rating: '7.9' } ] */// or...constrating=watchList.map(movie=>({title: movie.Title,rating: movie.imdbRating}));/* [ { title: 'Inception', rating: '8.8' }, { title: 'Interstellar', rating: '8.6' }, { title: 'The Dark Knight', rating: '9.0' }, { title: 'Batman Begins', rating: '7.9' } ] */The lessons in this section handle non-browser features. import won't work on a browser directly. However, we can use various tools to create code out of this to make it work in browser.
// we can choose which parts of a module or file to load into a given file.import{function}from"file_path"// We can also import variables the same way!// Import Everything from a Fileimport*asname_of_your_choicefrom"file_path"In order for import to work, though, we must first export the functions or variables we need.
Like import, export is a non-browser feature.
constcapitalizeString=(string)=>{returnstring.charAt(0).toUpperCase()+string.slice(1);}export{capitalizeString}//How to export functions.exportconstfoo="bar";//How to export variables.// Alternatively, if you would like to compact all your export statements into one line, you can take this approachconstcapitalizeString=(string)=>{returnstring.charAt(0).toUpperCase()+string.slice(1);}constfoo="bar";export{capitalizeString,foo}// use export default if only one value is being exported from a file.// It is also used to create a fallback value for a file or moduleexportdefaultfunctionadd(x,y){returnx+y;}// and to importimportaddfrom"math_functions";add(5,4);//Will return 9