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
constsize=10;if(size>100){console.log('Big');}elseif(size>20){console.log('Medium');}elseif(size>4){console.log('Small');}else{console.log('Tiny');}// Print: Small
switch Statement
constfood='salad';switch(food){case'oyster':
console.log('The taste of the sea');break;case'pizza':
console.log('A delicious pie');break;default:
console.log('Enjoy your meal');}
JavaScript Functions {.cols-3}
Functions
// Defining the function:functionsum(num1,num2){returnnum1+num2;}// Calling the function:sum(3,6);// 9
Anonymous Functions
// Named functionfunctionrocketToMars(){return'BOOM!';}// Anonymous functionconstrocketToMars=function(){return'BOOM!';}
letplusFive=(number)=>{returnnumber+5;};// f is assigned the value of plusFiveletf=plusFive;plusFive(3);// 8// Since f has a function value, it can be invoked. f(9);// 14
Callback Functions
constisEven=(n)=>{returnn%2==0;}letprintMsg=(evenFunc,num)=>{constisNumEven=evenFunc(num);console.log(`${num} is an even number: ${isNumEven}.`)}// Pass in isEven as the callback functionprintMsg(isEven,4);// => The number 4 is an even number: True.
// Example of invalid key namesconsttrainSchedule={// Invalid because of the space between words.platformnum: 10,// Expressions cannot be keys.40-10+2: 30,// A + sign is invalid unless it is enclosed in quotations.+compartment: 'C'}
constorigNum=8;constorigObj={color: 'blue'};constchangeItUp=(num,obj)=>{num=7;obj.color='red';};changeItUp(origNum,origObj);// Will output 8 since integers are passed by value.console.log(origNum);// Will output 'red' since objects are passed // by reference and are therefore mutable.console.log(origObj.color);
// A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. constdogFactory=(name,age,breed)=>{return{name: name,age: age,breed: breed,bark(){console.log('Woof!');}};};
Methods
constengine={// method shorthand, with one argumentstart(adverb){console.log(`The engine starts up ${adverb}...`);},// anonymous arrow function expression with no argumentssputter: ()=>{console.log('The engine sputters...');},};engine.start('noisily');engine.sputter();
Getters and setters
constmyCat={_name: 'Dottie',getname(){returnthis._name;},setname(newName){this._name=newName;}};// Reference invokes the getterconsole.log(myCat.name);// Assignment invokes the settermyCat.name='Yankee';
JavaScript Classes {.cols-3}
Static Methods
classDog{constructor(name){this._name=name;}introduce(){console.log('This is '+this._name+' !');}// A static methodstaticbark(){console.log('Woof!');}}constmyDog=newDog('Buster');myDog.introduce();// Calling the static methodDog.bark();
varmoduleA=require("./module-a.js");// The .js extension is optionalvarmoduleA=require("./module-a");// Both ways will produce the same result.// Now the functionality of moduleA can be usedconsole.log(moduleA.someFunctionality)
Export
// module "moduleA.js"exportdefaultfunctioncube(x){returnx*x*x;}// In main.jsimportcubefrom'./moduleA.js';// Now the `cube` function can be used straightforwardly.console.log(cube(3));// 27
constpromise=newPromise((resolve,reject)=>{constres=true;// An asynchronous operation.if(res){resolve('Resolved!');}else{reject(Error('Error'));}});promise.then((res)=>console.log(res),(err)=>alert(err));
constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{resolve('*');},1000);});consttwoStars=(star)=>{return(star+star);};constoneDot=(star)=>{return(star+'.');};constprint=(val)=>{console.log(val);};// Chaining them all togetherpromise.then(twoStars).then(oneDot).then(print);
Creating
constexecutorFn=(resolve,reject)=>{console.log('The executor function of the promise!');};constpromise=newPromise(executorFn);
Chaining multiple .then()
constpromise=newPromise(resolve=>setTimeout(()=>resolve('dAlan'),100));promise.then(res=>{returnres==='Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')}).then((res)=>{console.log(res)},(err)=>{alert(err)});
JavaScript Async-Await {.cols-2}
Asynchronous
functionhelloWorld(){returnnewPromise(resolve=>{setTimeout(()=>{resolve('Hello World!');},2000);});}constmsg=asyncfunction(){//Async Function Expressionconstmsg=awaithelloWorld();console.log('Message:',msg);}constmsg1=async()=>{//Async Arrow Functionconstmsg=awaithelloWorld();console.log('Message:',msg);}msg();// Message: Hello World! <-- after 2 secondsmsg1();// Message: Hello World! <-- after 2 seconds