投稿時間:2021-04-28 02:06:38 RSSフィード2021-04-28 02:00 分まとめ(237件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
AWS AWS - Webinar Channel Build ETL Processes with AWS Glue (Hebrew) https://www.youtube.com/watch?v=ORKc2mGpjq8 Build ETL Processes with AWS Glue Hebrew AWS Glue started out as a serverless ETL service however in the last years it has morphed into a full fledged data integration and preparation service In this session AWS Glue Principal Product manager Roy Hasson will show how AWS Glue can help you build data integration pipelines quickly and efficiently with little to no developer experience Learn what s new with Glue Spark powered execution engine Glue Studio easy to use visual job development the newly announced connector marketplace Lastly Tomer Levi Data engineer and data architect ex Intel Fundbox and current VP R amp D at Sedric would share Glue best practices and real life implementation examples Have a project to deploy on the cloud and need our help Live chat with an AWS business representative now » 2021-04-27 12:36:24
python Pythonタグが付けられた新着投稿 - Qiita GPT-3でanswerとcompletionのエンドポイントを比較する https://qiita.com/NP_Systems/items/31b8c66626320d564218 Javaは、C言語やCのような関数型言語ではなく、オブジェクト指向言語ですcurieの場合Javaは、不可逆のクラスタリングシステムであるジャーナル・コード・ライブラリJARによって記述された静的なプログラムである。 2021-04-27 21:45:36
js JavaScriptタグが付けられた新着投稿 - Qiita JavaScriptのEventフェーズについて Eventの発火順番とイベントメソッドの正体 https://qiita.com/yuta-katayama-23/items/49cab288fa2a8137ebe8 CapturingPhaseイベントが発生した場合にwindowからイベントターゲットまで下に向かって進んでいくフェーズTargetPhaseイベントターゲットに到達したフェーズ状態BubblingPhaseその後、元進んできた所を順に戻っていくフェーズJavaScriptのイベントはいつ発火するのか上記でみたように、JavaScriptのイベントにはつのフェーズがあるが、実際にイベントが発火するのはBubblingPhase※。 2021-04-27 21:44:45
js JavaScriptタグが付けられた新着投稿 - Qiita 【javascript】日付を指定の形式で出力 https://qiita.com/noenture/items/f683edf24fc2af3d6168 コードに記したYMDのような形式を作ってしまえば対処は可能。 2021-04-27 21:39:54
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) GitHubとSourceTreeを使って複数のパソコンでUnityの開発をするには https://teratail.com/questions/335472?rss=all GitHubとSourceTreeを使って複数のパソコンでUnityの開発をするには前提・実現したいことMacの方でGitHubとSourceTreeを使ったunityのバージョン管理の方法を以下のURLの通りに試してみました。 2021-04-27 21:50:57
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Pytorchを使用した教師なしクラスタリング https://teratail.com/questions/335471?rss=all Pytorchを使用した教師なしクラスタリング前提・実現したいことここに質問の内容を詳しく書いてください。 2021-04-27 21:42:24
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) appendとnth-childの組み合わせ 追加されない https://teratail.com/questions/335470?rss=all 『魚jpg』『猿jpg』『人間jpg』のつの写真があるとします。 2021-04-27 21:33:58
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) amazon linux2でroot diskがひっぱくしている。 https://teratail.com/questions/335469?rss=all その後、マウントしたものがdevnvmenですが、rootのディスクはひっ迫して取り残されたままの状態です。 2021-04-27 21:32:36
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) VB.NETでのVBAのDLLライブラリ作成について(COM相互運用機能の登録がグレー表示) https://teratail.com/questions/335468?rss=all VBNETでのVBAのDLLライブラリ作成についてCOM相互運用機能の登録がグレー表示VBNETにて、クラスライブラリdllnbsptblを作成し、ExcelnbspVBAの参照設定に登録して使用したいと考えていますが、VisualStudioのCOM相互運用機能の登録がグレー表示でチェックをすることができないため、解決方法をご教授いただければ幸いです。 2021-04-27 21:30:42
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) [opengl] 二つのオブジェクトのインスタンスを生成すると描画座標がおかしくなる原因が知りたい。 https://teratail.com/questions/335467?rss=all opengl二つのオブジェクトのインスタンスを生成すると描画座標がおかしくなる原因が知りたい。 2021-04-27 21:26:32
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) mix-blend-modeに影響されない画像をその上に置きたい https://teratail.com/questions/335466?rss=all mixblendmodeに影響されない画像をその上に置きたいCSSのmixblendmodeのmultiplyを使用して、hover時に背景画像に乗算で色がつくボタンを作成したいのですが、その上にテキスト画像が乗っており、これにはmixblendmodeの影響を受けてほしくありません。 2021-04-27 21:20:30
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 投稿サイトのコスト最小化 https://teratail.com/questions/335465?rss=all azurenbspfunctions 2021-04-27 21:17:42
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) フラグメント下部ナビゲーションボタンのアクションを無効にする方法 https://teratail.com/questions/335464?rss=all フラグメントのナビゲーションを使用しているのですが、一つのフラグメントでメソッドを使用している際、フラグメント用下部ナビゲーションを使用してフラグメントを変えてしまうとアプリが落ちてしまいます。 2021-04-27 21:11:37
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) python 固有値順に固有ベクトルを並べる https://teratail.com/questions/335463?rss=all python固有値順に固有ベクトルを並べる前提・実現したいことある行列Hの固有値と固有べクトルをeigvalnbspeigvecnbsplinalgeigHで求めれると思うのですが、その固有ベクトルをその固有値の大きさ順複素なら実部の大きさ順に並べるうまい方法はありますかここに質問の内容を詳しく書いてください。 2021-04-27 21:04:24
AWS AWSタグが付けられた新着投稿 - Qiita AWS S3 レプリケーション TLSバージョンをバケットポリシーから確認する https://qiita.com/quryu/items/568a0b3c290d7ab4ae71 AWSSレプリケーションTLSバージョンをバケットポリシーから確認する背景重要なデータのバックアップのためにクロスリージョンレプリケーションを使用していても、その転送プロトコルに欠陥があれば問題である。 2021-04-27 21:59:45
Docker dockerタグが付けられた新着投稿 - Qiita Machine-Learning-with-R-Cookbook-Second-Edition-master:dockerで機械学習(78) with R (8) https://qiita.com/kaizen_nagoya/items/cbbed4d49ebb9c479816 2021-04-27 21:39:31
golang Goタグが付けられた新着投稿 - Qiita golangでエンディアンを理解する https://qiita.com/ota-yuki/items/84c9e87f3502192c4959 エンディアンについて前提メモリアドレスはbyte単位で割り振られるデータのメモリへの格納方法が週類存在データの先頭byteを小さいアドレスに置く方式⇒ビッグエンディアンデータの先頭byteを大きいアドレスに置く方式⇒リトルエンディアンという数値進表示でxがあったときに、ビッグエンディアンでは、Go言語で書くとbytexxxxとなります。 2021-04-27 21:55:37
GCP gcpタグが付けられた新着投稿 - Qiita 【GCP】GCE+Cloud SQLでWordPressを立ち上げてみた① https://qiita.com/riku929hr/items/bbec0e254ddca39186cc fmicroを選択すると無料で使えますが、これは後から変更することが出来ます。 2021-04-27 21:47:14
技術ブログ Developers.IO MediaLiveのHTML5モーショングラフィックスオーバーレイを使ってライブ動画にダイナミックなテキスト情報を加えてみた https://dev.classmethod.jp/articles/aws-elemental-medialive-html-5-motion-graphics-overlay/ awselementalmedialiven 2021-04-27 12:50:18
技術ブログ Developers.IO AWS CopilotでFargate上に既存ツールを動作させようと四苦八苦していることについてまとめてみた https://dev.classmethod.jp/articles/try-with-aws-copilot/ awscopilot 2021-04-27 12:29:12
海外TECH DEV Community Accurate Clock in Javascript https://dev.to/aditya57/accurate-clock-in-javascript-325l Accurate Clock in Javascript Accurate Clock in Javascript Let s start coding Html code create index html and paste the following code   lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta http equiv X UA Compatible content IE edge gt lt meta name viewport content width device width initial scale gt lt link rel stylesheet href style css gt lt script src script js gt lt script gt lt title gt Time lt title gt lt head gt lt body onLoad initClock gt lt div id content gt lt div id timedate gt lt a id mon gt January lt a gt lt a id d gt lt a gt lt a id y gt lt a gt lt br gt lt a id h gt lt a gt lt a id m gt lt a gt lt a id s gt lt a gt lt a id mi gt lt a gt lt div gt lt div gt lt body gt lt html gt Css code create style css and paste the following code  body background color ddd content position absolute top left transform translate timedate font size px text align left width margin px auto color fff border left px solid ffed padding px Javascript code create script js and paste the following code  Number prototype pad function n for var r this toString r length lt n r r return r function updateClock var now new Date var milli now getMilliseconds sec now getSeconds min now getMinutes hou now getHours mo now getMonth dy now getDate yr now getFullYear var months January February March April May June July August September October November December var tags mon d y h m s mi corr months mo dy yr hou pad min pad sec pad milli for var i i lt tags length i document getElementById tags i firstChild nodeValue corr i function initClock updateClock window setInterval updateClock Preview Tryit and tell in Discussion Thanks 2021-04-27 12:51:19
海外TECH DEV Community 11 Nano shortcuts that you should know https://dev.to/bobbyiliev/11-nano-shortcuts-that-you-should-know-2od5 Nano shortcuts that you should know IntroductionProbably everyone that uses a Linux OS is familiar with what nano is But if you aren t aware don t worry Nano is a Unix and Linux operating system command line text editor What this means is that this is essentially a text editor built into your terminal How awesome is that Of course it can not be compared to other text editors like VSCode or Sublime Text or vim Nonetheless it s still handy and efficient But unfortunately most people don t use nano to it s fullest potential And the reason is being that nano keyboard shortcuts are different than what we are used to In this post we are going to explore the nano shortcuts that you must know We are going to group the shortcuts in different groups Let s start with Moving aroundOne of the most challenging thing in nano is moving around One of the most painful things is when you have to go to the end of a line and you have to press the right arrow key a million times Now I know that this sounds super lazy but imagine when you have to do this to different lines It s gonna take an annoying amount of time That s why the movement shortcuts are one of the most important to use in nano Here are the top ones that you should definitely remember Moves you to the start of the line Ctrl AMoves you to the end of the line Ctrl EMoves you one page up Ctrl YMoves you to the end of the file Ctrl V EditingAnother painful thing is when you make an error and have no idea how to undo it Well in most cases you close the file without saving the changes and start all over That s why learning the main editing shortcuts is gonna save you quite a lot of time Cut current line into cutbuffer Ctrl K Paste contents of cutbuffer Ctrl U Undo last action Alt U Redo last undone action Alt E DeletingAnd the final group is deleting Imagine you add a ton of text that you want to be removed immediately Well it sure is going to take you a long time to remove if you don t know these shortcuts Delete the word to the left Alt Bsp Delete the word to the right Ctrl Del Delete current line Alt Del ConclusionNot everybody uses Nano and some prefer vim or emacs But it is good to know some handy shortcuts which could help you if you ever need to use Nano Speaking of text editors be sure to check out this post on VScode shortcuts for Mac and Windows I hope that this helps 2021-04-27 12:49:58
海外TECH DEV Community 📅 Master Javascript Dates In 2 Minutes https://dev.to/satishnaikawadi2001/master-javascript-dates-in-2-minutes-3abi Master Javascript Dates In MinutesIn this article we will learn all the important topics related to dates in javascript with help of proper examples Date objects contain a Number that represents milliseconds since January UTC Creating A Date ObjectWe can create a Date object using Date constructor with the following syntaxes new Date current date and time as of the time of instantiation new Date value value is an integer value representing the number of milliseconds since January new Date dateString A string value representing a datenew Date year monthIndex day hours minutes seconds milliseconds Give at least a year and month Exampleslet today new Date console log today let myDay new Date January console log myDay myDay new Date T console log myDay myDay new Date the month is indexedconsole log myDay myDay new Date console log myDay Output T Z T Z T Z T Z T Z Important Instance Methods getDate Returns the day of the month for the specified date according to local time console log myDay getDate Output getDay Returns the day of the week for the specified date according to local time console log myDay getDay Output getFullYear Returns the year digits for digit years of the specified date according to local time console log myDay getFullYear Output getHours Returns the hour in the specified date according to local time console log myDay getHours Output getMinutes Returns the minutes in the specified date according to local time console log myDay getMinutes Output getSeconds Returns the seconds in the specified date according to local time console log myDay getSeconds Output getMonth Returns the month in the specified date according to local time console log myDay getMonth OutputWe also have similar methods with UTC as getUTCDate getUTCDay getUTCFullYear getUTCHours getUTCMilliseconds getUTCMinutes getUTCMonth and getUTCSeconds which will give similar results but according to universal time We also have similar setter methods with local time as well as with UTC which are setUTCDate setUTCDay setUTCFullYear setUTCHours setUTCMilliseconds setUTCMinutes setUTCMonth and setUTCSeconds which will set the particular parameters according to universal time While setDate setDay setFullYear setHours setMilliseconds setMinutes setMonth and setSeconds will set the parameters according to lacale time Important Methods To Convert Date To String toDateString Returns the date portion of the Date as a human readable string like Tue Apr toISOString Converts a date to a string following the ISO Extended Format like T Z toUTCString Converts a date to a string using the UTC timezone like Mon Jan GMT toLocaleString Returns a string with a locality sensitive representation of this date like AM Calculating Elapsed Timelet start new Date The event to time goes here doSomethingForALongTime let end new Date let elapsed end getTime start getTime elapsed time in milliseconds Get the number of seconds since the ECMAScript Epochlet seconds Math floor Date now So that is it for this article I hope you understand how to manipulate dates in javascript You can visit my Personal Blog for more articles related to programming And lastly as always Thank You for reading 2021-04-27 12:32:49
海外TECH DEV Community create-react-app alternative https://dev.to/gastonius/create-react-app-alternative-1abe create react app alternativeImagine you could use any boilerplate to create your apps Both front and back Customize it to suit your needs and from there continue evolving your boilerplate in a different layer than your apps That s basically what Aptugo is basically as that s probably of what Aptugo is It is like create react app or create vue app or create app with the twist that the template system to build your applications is easily editable multi layered atomic and circular Let me explain npm i aptugoclient ggit clone And that s it Now you can create ready to run applications in seconds with just one command aptugo new BASE templating system from Aptugo creates MERN applications but you can simply use your own templating boilerplate 2021-04-27 12:31:13
海外TECH DEV Community 🧨Never thought this way of using p/React inline/embedded 🧐 https://dev.to/karthick3018/never-thought-this-way-of-using-p-react-inline-embedded-b3p Never thought this way of using p React inline embedded Let me give you a quick explaination about the concept of this article have you heard thought of embedding a react application as CDN in a wordpress or in an angular or in a vue application is it possible if yes is it something about a micro frontend application yeah it s possible to embeed a react application like a CDN with out the complexity of a micro frontend architecture Wait what how it is possible will be the next questions will explain clearly Micro frontend is a concept of integrating two or more large applications like each will application will have its own route states etc What we re going to do is not a large application but a small one For example think of a chat bot that will have its own independent usage right can you write a single chat bot logic and use it in two different applications This way can really help you for this If not clear i ll give you a another example think of a financial tech site that has each one or two calculators in its pages The text route pictures and others can be in a wordpress or any and embeed the calculator using this approach So like these smaller concepts can be done using this and can result in a minature of micro frontend concepts likeresuablity across different application work can be splited and different domain team can work on the same application without any clash or dependency Things used in this processPreact Preact habitatwebpackbabelPreact what the heck is that do I need to learn that too come one preact is just react nothing else the bundle size of react is reduced by x times and created as preact Check out about preact here you ll find preact as a twin brother of react Why amp what is Preact But why we need to do this using preact why not react to address this point I ll ask a silly question your website needs to load fast to slow obviously faster so that is the point i ve choosen preact the resultant build of plain react application is over to kb where preact is kb I think these number are enough to choose preact but don t worry preact is just react and it can still do most of the things what react can Preact habitatThis is the library that will make plugging in Preact components and widgets in any CMS or website So this is the big and only thing you need to learn of use as a new but cool this is even simpler It s a HOC and what you need to do is just pass your main component inside this HOC and all your things will be done out the box Check this out here webpackWe need to make a minor change in the output of the bundle this need to be done in the webpack file The libraryTarget in the output must be of type umd UMD This exposes your library under all the module definitions allowing it to work with CommonJS AMD and as global variable babelBabel is just to use jsx react elements this is realated with preact you can just copy paste that s it about the setup you just need to create the logic and pass the component via habitat HOC and your requirement will be done Habitat usageI ve imported the habitat and render is the component I ve created Inside the init function i ve sent my Render component inside the habitat HOC and stored the value in a variable habitatApp Now using the value i ve received I can modify the type of render using the render function provided inline gt if this is true this will be rendered inside the particular div that you re mentioning else if it is given as false it will be rendered globally clientSpecified gt this can be used to specify the identification for the div where the app needs to be rendered Will explain this more clear later Now we re all set to launch npm run build comment will give you the production build that contains assests if any a index html bundle js bundle map js file We need to move the bundle folder to any of the cloud like netlify vercel or any other All done we need to embeed our current application to any of the other html wordpress page or application How to embeed in other application This one is even more simpler tadathat s it you ve sucessfully embeeded your preact application inside of a plain html page let me decode things async gt is used to avoid blocking of other scripts src gt is the cloud link of my build folder note you should point bundle js file not your bundle folder as a wholedata mount in mine is the things i ve mentioned earlier as inline in the preact habitat It is the place you can mention the identification of a div where it needs to render Here I ve given mine ie render the application inside a html element that has a classname of mine so it will render insidediv class mine gt Here I ve used class as a identifier you can use id as well so that s it we ve rendered our application using the CDN in the plain html page Have you noticed a thing without any express or react environment the application is running how just think will reveal this later here Limitations of this approachWill only recommend this for smaller applications Routes are not provied It can be used but there needs to be a react enivronment to run the application where without route it s not needed assets needs to be used inline or as a cloud url since we don t map it bundle folder we only point to bundle js file Thats it let me know your thoughts about this Check the complete project here Manage the Work From Home using this kitcheck my dev projects on github Follow me on twitterconnect with me on linkedIncheck my styles on codepenThanks for your timeHappy coding Keep SharingStay Safe 2021-04-27 12:29:35
海外TECH DEV Community 15 websites with free assets for web developers https://dev.to/pascavld/15-websites-with-free-assets-for-web-developers-5328 websites with free assets for web developersIf you found value in this thread you will most likely enjoy my tweets too so make sure you follow me on Twitter for more information about web development and how to improve as a developer This article was first published on my BlogIcons Download design elements for free icons photos vector illustrations and music for your videos Soundstripe Every creator s one stop shop for the best royalty free music SFX and stock video Google Fonts Making the web more beautiful fast and open through great typography Fonts in use A searchable archive of typographic design indexed by typeface format and topic Font Space Free downloads of legally licensed fonts that are perfect for your design projects The best place in the universe to search for amazing fonts Simple Icons Free SVG icons for popular brands Font Awesome Get vector icons and social logos on your website with Font Awesome the web s most popular icon set and toolkit Heroicons Beautiful hand crafted SVG icons by the makers of Tailwind CSS Unsplash Beautiful free images and photos that you can download and use for any project Shutterstock Download the best royalty free images from Shutterstock including photos vectors and illustrations Pexels Finding the perfect photo or video shouldn t take forever Envato elements Find stock video footages and photos for your next video project Squoosh Compress and compare images in your browser Logology No random generation and no symbols from a free database Everything was crafted from the ground up Looka Make a logo and build a brand you love with Looka The endI hope found this useful and if you did please let me know If you have any question feel free to DM me on Twitter 2021-04-27 12:29:30
海外TECH DEV Community 400+ JavaScript Interview Questions 🎓 With Answers 🌠 https://dev.to/worldindev/400-javascript-interview-questions-with-answers-2fcj JavaScript Interview Questions With Answers Hello World Today I prepared a huge list of Javascript Interview Questions from this awesome repo Sudheer Jonna has created lots of incredible interview questions repo Waaait don t leave this page without bookmarking save it gt Free PDF Version hereGiveaway We are giving away any course you need on Udemy Any price any course To enter you have to do the following React to this post️Subscribe to our Newsletter lt Very importantEnds May th For beginners What is JS Javascript JavaScript is a scripting or programming language that allows you to implement complex features on web pages ーevery time a web page does more than just sit there and display static information for you to look at ーdisplaying timely content updates interactive maps animated D D graphics scrolling video jukeboxes etc ーyou can bet that JavaScript is probably involved It is the third layer of the layer cake of standard web technologies MDN What it used for To put things simply JavaScript is an object orient programming language designed to make web development easier and more attractive In most cases JavaScript is used to create responsive interactive elements for web pages enhancing the user experience Things like menus animations video players interactive maps and even simple in browser games can be created quickly and easily with JavaScript JavaScript is one of the most popular programming languages in the world BitDegree What Is JavaScript Used For And Why You Should Learn It Hello World In Javascript alert Hello World ー Output data in an alert box in the browser windowconfirm Hello World ー Opens up a yes no dialog and returns true false depending on user clickconsole log Hello World ー Writes information to the browser console good for debugging purposesdocument write Hello World ー Write directly to the HTML documentprompt Remember the like ー Creates a dialogue for user input Resources to learn it Mozilla s JavaScript GuideJavaScript track on Codecademy Interactive tutorials for beginners JavaScript for Cats by Max OgdenEloquent JavaScript by Marijn HaverbekeWikibooks JavaScript bookJavaScript Lectures by Douglas CrockfordYou Don t Know JS Possibly the best book written on modern JavaScript completely readable online for free or can be bought to support the author braziljs js the right way An easy to read quick reference for JS best practices accepted coding standards and links around the Web JSbooks Directory of free JavaScript ebooks Superhero js A collection of resources about creating testing and maintaining a large JavaScript code base SJSJ Simplified JavaScript Jargon is a community driven attempt at explaining the loads of buzzwords making the current JavaScript ecosystem in a few simple words How to Write an Open Source JavaScript Library A comprehensive guide through a set of steps to publish a JavaScript open source library JavaScript Tutorials Learn Javascript online from a diverse range of user ranked online tutorials Functional Light JavaScript Pragmatic balanced FP in JavaScript Clean Code JavaScript Clean Code concepts adapted for JavaScript List at GitHub Awesome Javascript By Alexandru Gherasim At Reddit What Things Should a Serious Javascript Developer Know Right Now Scope If you don t understand this intimately then you aren t that serious about this language This is the number one point intentionally and I cannot stress it enough Architecture You don t have to be a master software architect but if you cannot perform some basic planning and put pieces together without massive layers of tooling you are an imposter Expecting frameworks and other tools to simply do it for you isn t very impressive DOM It is very common to see developers hiding from the DOM by layers of abstractions and other stupid crap querySelectors are great but are also x slower than the standard DOM methods That isn t trivial These methods are super simple so there is no valid excuse for developers fumbling over this or hiding in fear Node js If you are a serious developer should have a pretty solid grasp of how to walk the file system You should understand how to conveniently read files as text or less conveniently read files as bit for bit binary buffers Timing and asynchronous operations Events timers network requests are all asynchronous and separate from each other and exist both in Node and in the browser You have to be able to understand how to work with callbacks or promises Accessibility The interactions imposed by JavaScript can present accessibility barriers A serious JavaScript developer is already familiar with WCAG and knows how to work within its recommendations or when to push back on violating business requirements Security You need to have at least a basic understanding of security violations security controls and privacy You don t need to be a CISSP but you need to be able to supply recommendations and avoid obvious failures If you cannot get this right in the most basic sense you aren t a serious developer Data structures You need to understand how to organize data in a way that allows the fastest possible execution without compromising maintenance This is something that is learned through academic study and repeated experience writing applications Presentation and semantics You really need to have a basic understanding how to properly organize the content your users will consume and how to present in a consumable way efficiently This is something almost completely learned from experience only You might think CSS and HTML are simple skills that can be picked up when needed but you would be absolutely wrong Knowing when to avoid the bullshit Many developers lack the years of experience to be confident in their performance so some of these developers will try to fake it Don t be an imposter because everybody will see straight through it Hoping mountains of abstractions tooling frameworks compilers and other bullshit will save you just bogs down your application and screws over your teammates If you aren t confident then be honest about that and seek mentorship or get involved with open source software outside of work Source gt Remember the like ️No QuestionsWhat are the possible ways to create objects in JavaScriptWhat is prototype chainWhat is the difference between Call Apply and BindWhat is JSON and its common operationsWhat is the purpose of the array slice methodWhat is the purpose of the array splice methodWhat is the difference between slice and spliceHow do you compare Object and MapWhat is the difference between and operatorsWhat are lambda or arrow functionsWhat is a first class functionWhat is a first order functionWhat is a higher order functionWhat is a unary functionWhat is the currying functionWhat is a pure functionWhat is the purpose of the let keywordWhat is the difference between let and varWhat is the reason to choose the name let as a keywordHow do you redeclare variables in switch block without an errorWhat is the Temporal Dead ZoneWhat is IIFE Immediately Invoked Function Expression What is the benefit of using modulesWhat is memoizationWhat is HoistingWhat are classes in ESWhat are closuresWhat are modulesWhy do you need modulesWhat is scope in javascriptWhat is a service workerHow do you manipulate DOM using a service workerHow do you reuse information across service worker restartsWhat is IndexedDBWhat is web storageWhat is a post messageWhat is a cookieWhy do you need a CookieWhat are the options in a cookieHow do you delete a cookieWhat are the differences between cookie local storage and session storageWhat is the main difference between localStorage and sessionStorageHow do you access web storageWhat are the methods available on session storageWhat is a storage event and its event handlerWhy do you need web storageHow do you check web storage browser supportHow do you check web workers browser supportGive an example of web workerWhat are the restrictions of web workers on DOMWhat is a promiseWhy do you need a promiseWhat are the three states of promiseWhat is a callback functionWhy do we need callbacksWhat is a callback hellWhat is server sent eventsHow do you receive server sent event notificationsHow do you check browser support for server sent eventsWhat are the events available for server sent eventsWhat are the main rules of promiseWhat is callback in callbackWhat is promise chainingWhat is promise allWhat is the purpose of race method in promiseWhat is a strict mode in javascriptWhy do you need strict modeHow do you declare strict modeWhat is the purpose of double exclamationWhat is the purpose of delete operatorWhat is typeof operatorWhat is undefined propertyWhat is null valueWhat is the difference between null and undefinedWhat is evalWhat is the difference between window and documentHow do you access history in javascriptHow do you detect caps lock key turned on or notWhat is isNaNWhat are the differences between undeclared and undefined variablesWhat are global variablesWhat are the problems with global variablesWhat is NaN propertyWhat is the purpose of isFinite functionWhat is an event flowWhat is event bubblingWhat is event capturingHow do you submit a form using JavaScriptHow do you find operating system detailsWhat is the difference between document load and DOMContentLoaded eventsWhat is the difference between native host and user objectsWhat are the tools or techniques used for debugging JavaScript codeWhat are the pros and cons of promises over callbacksWhat is the difference between an attribute and a propertyWhat is same origin policyWhat is the purpose of void Is JavaScript a compiled or interpreted languageIs JavaScript a case sensitive languageIs there any relation between Java and JavaScriptWhat are eventsWho created javascriptWhat is the use of preventDefault methodWhat is the use of stopPropagation methodWhat are the steps involved in return falseWhat is BOMWhat is the use of setTimeoutWhat is the use of setIntervalWhy is JavaScript treated as Single threadedWhat is an event delegationWhat is ECMAScriptWhat is JSONWhat are the syntax rules of JSONWhat is the purpose JSON stringifyHow do you parse JSON stringWhy do you need JSONWhat are PWAsWhat is the purpose of clearTimeout methodWhat is the purpose of clearInterval methodHow do you redirect new page in javascriptHow do you check whether a string contains a substringHow do you validate an email in javascriptHow do you get the current url with javascriptWhat are the various url properties of location objectHow do get query string values in javascriptHow do you check if a key exists in an objectHow do you loop through or enumerate javascript objectHow do you test for an empty objectWhat is an arguments objectHow do you make first letter of the string in an uppercaseWhat are the pros and cons of for loopHow do you display the current date in javascriptHow do you compare two date objectsHow do you check if a string starts with another stringHow do you trim a string in javascriptHow do you add a key value pair in javascriptIs the notation represents a special operatorHow do you assign default values to variablesHow do you define multiline stringsWhat is an app shell modelCan we define properties for functionsWhat is the way to find the number of parameters expected by a functionWhat is a polyfillWhat are break and continue statementsWhat are js labelsWhat are the benefits of keeping declarations at the topWhat are the benefits of initializing variablesWhat are the recommendations to create new objectHow do you define JSON arraysHow do you generate random integersCan you write a random integers function to print integers with in a rangeWhat is tree shakingWhat is the need of tree shakingIs it recommended to use evalWhat is a Regular ExpressionWhat are the string methods available in Regular expressionWhat are modifiers in regular expressionWhat are regular expression patternsWhat is a RegExp objectHow do you search a string for a patternWhat is the purpose of exec methodHow do you change style of a HTML elementWhat would be the result of What is a debugger statementWhat is the purpose of breakpoints in debuggingCan I use reserved words as identifiersHow do you detect a mobile browserHow do you detect a mobile browser without regexpHow do you get the image width and height using JSHow do you make synchronous HTTP requestHow do you make asynchronous HTTP requestHow do you convert date to another timezone in javascriptWhat are the properties used to get size of windowWhat is a conditional operator in javascriptCan you apply chaining on conditional operatorWhat are the ways to execute javascript after page loadWhat is the difference between proto and prototypeGive an example where do you really need semicolonWhat is a freeze methodWhat is the purpose of freeze methodWhy do I need to use freeze methodHow do you detect a browser language preferenceHow to convert string to title case with javascriptHow do you detect javascript disabled in the pageWhat are various operators supported by javascriptWhat is a rest parameterWhat happens if you do not use rest parameter as a last argumentWhat are the bitwise operators available in javascriptWhat is a spread operatorHow do you determine whether object is frozen or notHow do you determine two values same or not using objectWhat is the purpose of using object is methodHow do you copy properties from one object to otherWhat are the applications of assign methodWhat is a proxy objectWhat is the purpose of seal methodWhat are the applications of seal methodWhat are the differences between freeze and seal methodsHow do you determine if an object is sealed or notHow do you get enumerable key and value pairsWhat is the main difference between Object values and Object entries methodHow can you get the list of keys of any objectHow do you create an object with prototypeWhat is a WeakSetWhat are the differences between WeakSet and SetList down the collection of methods available on WeakSetWhat is a WeakMapWhat are the differences between WeakMap and MapList down the collection of methods available on WeakMapWhat is the purpose of unevalHow do you encode an URLHow do you decode an URLHow do you print the contents of web pageWhat is the difference between uneval and evalWhat is an anonymous functionWhat is the precedence order between local and global variablesWhat are javascript accessorsHow do you define property on Object constructorWhat is the difference between get and definePropertyWhat are the advantages of Getters and SettersCan I add getters and setters using defineProperty methodWhat is the purpose of switch caseWhat are the conventions to be followed for the usage of swtich caseWhat are primitive data typesWhat are the different ways to access object propertiesWhat are the function parameter rulesWhat is an error objectWhen you get a syntax errorWhat are the different error names from error objectWhat are the various statements in error handlingWhat are the two types of loops in javascriptWhat is nodejsWhat is an Intl objectHow do you perform language specific date and time formattingWhat is an IteratorHow does synchronous iteration worksWhat is an event loopWhat is call stackWhat is an event queueWhat is a decoratorWhat are the properties of Intl objectWhat is an Unary operatorHow do you sort elements in an arrayWhat is the purpose of compareFunction while sorting arraysHow do you reversing an arrayHow do you find min and max value in an arrayHow do you find min and max values without Math functionsWhat is an empty statement and purpose of itHow do you get meta data of a moduleWhat is a comma operatorWhat is the advantage of a comma operatorWhat is typescriptWhat are the differences between javascript and typescriptWhat are the advantages of typescript over javascriptWhat is an object initializerWhat is a constructor methodWhat happens if you write constructor more than once in a classHow do you call the constructor of a parent classHow do you get the prototype of an objectWhat happens If I pass string type for getPrototype methodHow do you set prototype of one object to anotherHow do you check whether an object can be extendable or notHow do you prevent an object to extendWhat are the different ways to make an object non extensibleHow do you define multiple properties on an objectWhat is MEAN in javascriptWhat Is Obfuscation in javascriptWhy do you need ObfuscationWhat is MinificationWhat are the advantages of minificationWhat are the differences between Obfuscation and EncryptionWhat are the common tools used for minificationHow do you perform form validation using javascriptHow do you perform form validation without javascriptWhat are the DOM methods available for constraint validationWhat are the available constraint validation DOM propertiesWhat are the list of validity propertiesGive an example usage of rangeOverflow propertyIs enums feature available in javascriptWhat is an enumHow do you list all properties of an objectHow do you get property descriptors of an objectWhat are the attributes provided by a property descriptorHow do you extend classesHow do I modify the url without reloading the pageHow do you check whether an array includes a particular value or notHow do you compare scalar arraysHow to get the value from get parametersHow do you print numbers with commas as thousand separatorsWhat is the difference between java and javascriptIs javascript supports namespaceHow do you declare namespaceHow do you invoke javascript code in an iframe from parent pageHow do get the timezone offset from dateHow do you load CSS and JS files dynamicallyWhat are the different methods to find HTML elements in DOMWhat is jQueryWhat is V JavaScript engineWhy do we call javascript as dynamic languageWhat is a void operatorHow to set the cursor to waitHow do you create an infinite loopWhy do you need to avoid with statementWhat is the output of below for loopsList down some of the features of ESWhat is ESCan I redeclare let and const variablesIs const variable makes the value immutableWhat are default parametersWhat are template literalsHow do you write multi line strings in template literalsWhat are nesting templatesWhat are tagged templatesWhat are raw stringsWhat is destructuring assignmentWhat are default values in destructuring assignmentHow do you swap variables in destructuring assignmentWhat are enhanced object literalsWhat are dynamic importsWhat are the use cases for dynamic importsWhat are typed arraysWhat are the advantages of module loadersWhat is collationWhat is for of statementWhat is the output of below spread operator arrayIs PostMessage secureWhat are the problems with postmessage target origin as wildcardHow do you avoid receiving postMessages from attackersCan I avoid using postMessages completelyIs postMessages synchronousWhat paradigm is JavascriptWhat is the difference between internal and external javascriptIs JavaScript faster than server side scriptHow do you get the status of a checkboxWhat is the purpose of double tilde operatorHow do you convert character to ASCII codeWhat is ArrayBufferWhat is the output of below string expressionWhat is the purpose of Error objectWhat is the purpose of EvalError objectWhat are the list of cases error thrown from non strict mode to strict modeIs all objects have prototypesWhat is the difference between a parameter and an argumentWhat is the purpose of some method in arraysHow do you combine two or more arraysWhat is the difference between Shallow and Deep copyHow do you create specific number of copies of a stringHow do you return all matching strings against a regular expressionHow do you trim a string at the beginning or endingWhat is the output of below console statement with unary operatorDoes javascript uses mixinsWhat is a thunk functionWhat are asynchronous thunksWhat is the output of below function callsHow to remove all line breaks from a stringWhat is the difference between reflow and repaintWhat happens with negating an arrayWhat happens if we add two arraysWhat is the output of prepend additive operator on falsy valuesHow do you create self string using special charactersHow do you remove falsy values from an arrayHow do you get unique values of an arrayWhat is destructuring aliasesHow do you map the array values without using map methodHow do you empty an arrayHow do you rounding numbers to certain decimalsWhat is the easiest way to convert an array to an objectHow do you create an array with some dataWhat are the placeholders from console objectIs it possible to add CSS to console messagesWhat is the purpose of dir method of console objectIs it possible to debug HTML elements in consoleHow do you display data in a tabular format using console objectHow do you verify that an argument is a Number or notHow do you create copy to clipboard buttonWhat is the shortcut to get timestampHow do you flattening multi dimensional arraysWhat is the easiest multi condition checkingHow do you capture browser back buttonHow do you disable right click in the web pageWhat are wrapper objectsWhat is AJAXWhat are the different ways to deal with Asynchronous CodeHow to cancel a fetch requestWhat is web speech APIWhat is minimum timeout throttlingHow do you implement zero timeout in modern browsersWhat are tasks in event loopWhat are microtasksWhat are different event loopsWhat is the purpose of queueMicrotaskHow do you use javascript libraries in typescript fileWhat are the differences between promises and observablesWhat is heapWhat is an event tableWhat is a microTask queueWhat is the difference between shim and polyfillHow do you detect primitive or non primitive value typeWhat is babelIs Node js completely single threadedWhat are the common use cases of observablesWhat is RxJSWhat is the difference between Function constructor and function declarationWhat is a Short circuit conditionWhat is the easiest way to resize an arrayWhat is an observableWhat is the difference between function and class declarationsWhat is an async functionHow do you prevent promises swallowing errorsWhat is denoHow do you make an object iterable in javascriptWhat is a Proper Tail CallHow do you check an object is a promise or notHow to detect if a function is called as constructorWhat are the differences between arguments object and rest parameterWhat are the differences between spread operator and rest parameterWhat are the different kinds of generatorsWhat are the built in iterablesWhat are the differences between for of and for in statementsHow do you define instance and non instance propertiesWhat is the difference between isNaN and Number isNaN How to invoke an IIFE without any extra brackets Is that possible to use expressions in switch cases What is the easiest way to ignore promise errors How do style the console output using CSS Questions What are the possible ways to create objects in JavaScriptThere are many ways to create objects in javascript as belowObject constructor The simplest way to create an empty object is using the Object constructor Currently this approach is not recommended var object new Object Object s create method The create method of Object creates a new object by passing the prototype object as a parameter var object Object create null Object literal syntax The object literal syntax is equivalent to create method when it passes null as parameter var object Function constructor Create any function and apply the new operator to create object instances function Person name var object object name name object age return object var object new Person Sudheer Function constructor with prototype This is similar to function constructor but it uses prototype for their properties and methods function Person Person prototype name Sudheer var object new Person This is equivalent to an instance created with an object create method with a function prototype and then call that function with an instance and parameters as arguments function func new func x y z OR Create a new instance using function prototype var newInstance Object create func prototype Call the function var result func call newInstance x y z If the result is a non null object then use it otherwise just use the new instance console log result amp amp typeof result object result newInstance ES Class syntax ES introduces class feature to create the objects class Person constructor name this name name var object new Person Sudheer Singleton pattern A Singleton is an object which can only be instantiated one time Repeated calls to its constructor return the same instance and this way one can ensure that they don t accidentally create multiple instances var object new function this name Sudheer Back to Top What is a prototype chainPrototype chaining is used to build new types of objects based on existing ones It is similar to inheritance in a class based language The prototype on object instance is available through Object getPrototypeOf object or proto property whereas prototype on constructors function is available through Object prototype Back to Top What is the difference between Call Apply and BindThe difference between Call Apply and Bind can be explained with below examples Call The call method invokes a function with a given this value and arguments provided one by onevar employee firstName John lastName Rodson var employee firstName Jimmy lastName Baily function invite greeting greeting console log greeting this firstName this lastName greeting invite call employee Hello How are you Hello John Rodson How are you invite call employee Hello How are you Hello Jimmy Baily How are you Apply Invokes the function with a given this value and allows you to pass in arguments as an arrayvar employee firstName John lastName Rodson var employee firstName Jimmy lastName Baily function invite greeting greeting console log greeting this firstName this lastName greeting invite apply employee Hello How are you Hello John Rodson How are you invite apply employee Hello How are you Hello Jimmy Baily How are you bind returns a new function allowing you to pass any number of argumentsvar employee firstName John lastName Rodson var employee firstName Jimmy lastName Baily function invite greeting greeting console log greeting this firstName this lastName greeting var inviteEmployee invite bind employee var inviteEmployee invite bind employee inviteEmployee Hello How are you Hello John Rodson How are you inviteEmployee Hello How are you Hello Jimmy Baily How are you Call and apply are pretty interchangeable Both execute the current function immediately You need to decide whether it s easier to send in an array or a comma separated list of arguments You can remember by treating Call is for comma separated list and Apply is for Array Whereas Bind creates a new function that will have this set to the first parameter passed to bind Back to Top What is JSON and its common operationsJSON is a text based data format following JavaScript object syntax which was popularized by Douglas Crockford It is useful when you want to transmit data across a network and it is basically just a text file with an extension of json and a MIME type of application jsonParsing Converting a string to a native objectJSON parse text Stringification converting a native object to a string so it can be transmitted across the networkJSON stringify object Back to Top What is the purpose of the array slice methodThe slice method returns the selected elements in an array as a new array object It selects the elements starting at the given start argument and ends at the given optional end argument without including the last element If you omit the second argument then it selects till the end Some of the examples of this method are let arrayIntegers let arrayIntegers arrayIntegers slice returns let arrayIntegers arrayIntegers slice returns let arrayIntegers arrayIntegers slice returns Note Slice method won t mutate the original array but it returns the subset as a new array Back to Top What is the purpose of the array splice methodThe splice method is used either adds removes items to from an array and then returns the removed item The first argument specifies the array position for insertion or deletion whereas the option second argument indicates the number of elements to be deleted Each additional argument is added to the array Some of the examples of this method are let arrayIntegersOriginal let arrayIntegersOriginal let arrayIntegersOriginal let arrayIntegers arrayIntegersOriginal splice returns original array let arrayIntegers arrayIntegersOriginal splice returns original array let arrayIntegers arrayIntegersOriginal splice a b c returns original array a b c Note Splice method modifies the original array and returns the deleted array Back to Top What is the difference between slice and spliceSome of the major difference in a tabular formSliceSpliceDoesn t modify the original array immutable Modifies the original array mutable Returns the subset of original arrayReturns the deleted elements as arrayUsed to pick the elements from arrayUsed to insert or delete elements to from arrayBack to Top How do you compare Object and MapObjects are similar to Maps in that both let you set keys to values retrieve those values delete keys and detect whether something is stored at a key Due to this reason Objects have been used as Maps historically But there are important differences that make using a Map preferable in certain cases The keys of an Object are Strings and Symbols whereas they can be any value for a Map including functions objects and any primitive The keys in Map are ordered while keys added to Object are not Thus when iterating over it a Map object returns keys in order of insertion You can get the size of a Map easily with the size property while the number of properties in an Object must be determined manually A Map is an iterable and can thus be directly iterated whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them An Object has a prototype so there are default keys in the map that could collide with your keys if you re not careful As of ES this can be bypassed by using map Object create null but this is seldom done A Map may perform better in scenarios involving frequent addition and removal of key pairs Back to Top What is the difference between and operatorsJavaScript provides both strict and type converting equality comparison The strict operators take type of variable in consideration while non strict operators make type correction conversion based upon values of variables The strict operators follow the below conditions for different types Two strings are strictly equal when they have the same sequence of characters same length and same characters in corresponding positions Two numbers are strictly equal when they are numerically equal i e Having the same number value There are two special cases in this NaN is not equal to anything including NaN Positive and negative zeros are equal to one another Two Boolean operands are strictly equal if both are true or both are false Two objects are strictly equal if they refer to the same Object Null and Undefined types are not equal with but equal with i e null undefined gt false but null undefined gt trueSome of the example which covers the above cases false true false false true falsenull undefined truenull undefined false false true false false or false refer different objects in memory or false refer different objects in memoryBack to Top What are lambda or arrow functionsAn arrow function is a shorter syntax for a function expression and does not have its own this arguments super or new target These functions are best suited for non method functions and they cannot be used as constructors Back to Top What is a first class functionIn Javascript functions are first class objects First class functions means when functions in that language are treated like any other variable For example in such a language a function can be passed as an argument to other functions can be returned by another function and can be assigned as a value to a variable For example in the below example handler functions assigned to a listenerconst handler gt console log This is a click handler function document addEventListener click handler Back to Top What is a first order functionFirst order function is a function that doesn t accept another function as an argument and doesn t return a function as its return value const firstOrder gt console log I am a first order function Back to Top What is a higher order functionHigher order function is a function that accepts another function as an argument or returns a function as a return value or both const firstOrderFunc gt console log Hello I am a First order function const higherOrder ReturnFirstOrderFunc gt ReturnFirstOrderFunc higherOrder firstOrderFunc Back to Top What is a unary functionUnary function i e monadic is a function that accepts exactly one argument It stands for a single argument accepted by a function Let us take an example of unary function const unaryFunction a gt console log a Add to the given argument and display the valueBack to Top What is the currying functionCurrying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument Currying is named after a mathematician Haskell Curry By applying currying a n ary function turns it into a unary function Let s take an example of n ary function and how it turns into a currying function const multiArgFunction a b c gt a b c console log multiArgFunction const curryUnaryFunction a gt b gt c gt a b c curryUnaryFunction returns a function b gt c gt b ccurryUnaryFunction returns a function c gt ccurryUnaryFunction returns the number Curried functions are great to improve code reusability and functional composition Back to Top What is a pure functionA Pure function is a function where the return value is only determined by its arguments without any side effects i e If you call a function with the same arguments n number of times and n number of places in the application then it will always return the same value Let s take an example to see the difference between pure and impure functions Impurelet numberArray const impureAddNumber number gt numberArray push number Pureconst pureAddNumber number gt argNumberArray gt argNumberArray concat number Display the resultsconsole log impureAddNumber returns console log numberArray returns console log pureAddNumber numberArray returns console log numberArray returns As per above code snippets Push function is impure itself by altering the array and returning an push number index which is independent of parameter value Whereas Concat on the other hand takes the array and concatenates it with the other array producing a whole new array without side effects Also the return value is a concatenation of the previous array Remember that Pure functions are important as they simplify unit testing without any side effects and no need for dependency injection They also avoid tight coupling and make it harder to break your application by not having any side effects These principles are coming together with Immutability concept of ES by giving preference to const over let usage Back to Top What is the purpose of the let keywordThe let statement declares a block scope local variable Hence the variables defined with let keyword are limited in scope to the block statement or expression on which it is used Whereas variables declared with the var keyword used to define a variable globally or locally to an entire function regardless of block scope Let s take an example to demonstrate the usage let counter if counter let counter console log counter console log counter because the variable in if block won t exist here Back to Top What is the difference between let and varYou can list out the differences in a tabular formatvarletIt is been available from the beginning of JavaScriptIntroduced as part of ESIt has function scopeIt has block scopeVariables will be hoistedHoisted but not initializedLet s take an example to see the difference function userDetails username if username console log salary undefined due to hoisting console log age ReferenceError Cannot access age before initialization let age var salary console log salary accessible to due function scope console log age error age is not defined due to block scope userDetails John Back to Top What is the reason to choose the name let as a keywordlet is a mathematical statement that was adopted by early programming languages like Scheme and Basic It has been borrowed from dozens of other languages that use let already as a traditional keyword as close to var as possible Back to Top How do you redeclare variables in switch block without an errorIf you try to redeclare variables in a switch block then it will cause errors because there is only one block For example the below code block throws a syntax error as below let counter switch x case let name break case let name SyntaxError for redeclaration break To avoid this error you can create a nested block inside a case clause and create a new block scoped lexical environment let counter switch x case let name break case let name No SyntaxError for redeclaration break Back to Top What is the Temporal Dead ZoneThe Temporal Dead Zone is a behavior in JavaScript that occurs when declaring a variable with the let and const keywords but not with var In ECMAScript accessing a let or const variable before its declaration within its scope causes a ReferenceError The time span when that happens between the creation of a variable s binding and its declaration is called the temporal dead zone Let s see this behavior with an example function somemethod console log counter undefined console log counter ReferenceError var counter let counter Back to Top What is IIFE Immediately Invoked Function Expression IIFE Immediately Invoked Function Expression is a JavaScript function that runs as soon as it is defined The signature of it would be as below function logic here The primary reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the outside world i e If you try to access variables with IIFE then it throws an error as below function var message IIFE console log message console log message Error message is not definedBack to Top What is the benefit of using modulesThere are a lot of benefits to using modules in favour of a sprawling Some of the benefits are MaintainabilityReusabilityNamespacingBack to Top What is memoizationMemoization is a programming technique which attempts to increase a function s performance by caching its previously computed results Each time a memoized function is called its parameters are used to index the cache If the data is present then it can be returned without executing the entire function Otherwise the function is executed and then the result is added to the cache Let s take an example of adding function with memoization const memoizAddition gt let cache return value gt if value in cache console log Fetching from cache return cache value Here cache value cannot be used as property name starts with the number which is not a valid JavaScript identifier Hence can only be accessed using the square bracket notation else console log Calculating result let result value cache value result return result returned function from memoizAdditionconst addition memoizAddition console log addition output calculatedconsole log addition output cachedBack to Top What is HoistingHoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution Remember that JavaScript only hoists declarations not initialisation Let s take a simple example of variable hoisting console log message output undefinedvar message The variable Has been hoisted The above code looks like as below to the interpreter var message console log message message The variable Has been hoisted Back to Top What are classes in ESIn ES Javascript classes are primarily syntactic sugar over JavaScript s existing prototype based inheritance For example the prototype based inheritance written in function expression as below function Bike model color this model model this color color Bike prototype getDetails function return this model bike has this color color Whereas ES classes can be defined as an alternativeclass Bike constructor color model this color color this model model getDetails return this model bike has this color color Back to Top What are closuresA closure is the combination of a function and the lexical environment within which that function was declared i e It is an inner function that has access to the outer or enclosing function s variables The closure has three scope chainsOwn scope where variables defined between its curly bracketsOuter function s variablesGlobal variablesLet s take an example of closure concept function Welcome name var greetingInfo function message console log message name return greetingInfo var myFunction Welcome John myFunction Welcome Output Welcome JohnmyFunction Hello Mr output Hello Mr JohnAs per the above code the inner function i e greetingInfo has access to the variables in the outer function scope i e Welcome even after the outer function has returned Back to Top What are modulesModules refer to small units of independent reusable code and also act as the foundation of many JavaScript design patterns Most of the JavaScript modules export an object literal a function or a constructorBack to Top Why do you need modulesBelow are the list of benefits using modules in javascript ecosystemMaintainabilityReusabilityNamespacingBack to Top What is scope in javascriptScope is the accessibility of variables functions and objects in some particular part of your code during runtime In other words scope determines the visibility of variables and other resources in areas of your code Back to Top What is a service workerA Service worker is basically a script JavaScript file that runs in the background separate from a web page and provides features that don t need a web page or user interaction Some of the major features of service workers are Rich offline experiences offline first web application development periodic background syncs push notifications intercept and handle network requests and programmatically managing a cache of responses Back to Top How do you manipulate DOM using a service workerService worker can t access the DOM directly But it can communicate with the pages it controls by responding to messages sent via the postMessage interface and those pages can manipulate the DOM Back to Top How do you reuse information across service worker restartsThe problem with service worker is that it gets terminated when not in use and restarted when it s next needed so you cannot rely on global state within a service worker s onfetch and onmessage handlers In this case service workers will have access to IndexedDB API in order to persist and reuse across restarts Back to Top What is IndexedDBIndexedDB is a low level API for client side storage of larger amounts of structured data including files blobs This API uses indexes to enable high performance searches of this data Back to Top What is web storageWeb storage is an API that provides a mechanism by which browsers can store key value pairs locally within the user s browser in a much more intuitive fashion than using cookies The web storage provides two mechanisms for storing data on the client Local storage It stores data for current origin with no expiration date Session storage It stores data for one session and the data is lost when the browser tab is closed Back to Top What is a post messagePost message is a method that enables cross origin communication between Window objects i e between a page and a pop up that it spawned or between a page and an iframe embedded within it Generally scripts on different pages are allowed to access each other if and only if the pages follow same origin policy i e pages share the same protocol port number and host Back to Top What is a CookieA cookie is a piece of data that is stored on your computer to be accessed by your browser Cookies are saved as key value pairs For example you can create a cookie named username as below document cookie username John Back to Top Why do you need a CookieCookies are used to remember information about the user profile such as username It basically involves two steps When a user visits a web page the user profile can be stored in a cookie Next time the user visits the page the cookie remembers the user profile Back to Top What are the options in a cookieThere are few below options available for a cookie By default the cookie is deleted when the browser is closed but you can change this behavior by setting expiry date in UTC time document cookie username John expires Sat Jun UTC By default the cookie belongs to a current page But you can tell the browser what path the cookie belongs to using a path parameter document cookie username John path services Back to Top How do you delete a cookieYou can delete a cookie by setting the expiry date as a passed date You don t need to specify a cookie value in this case For example you can delete a username cookie in the current page as below document cookie username expires Fri Jun UTC path Note You should define the cookie path option to ensure that you delete the right cookie Some browsers doesn t allow to delete a cookie unless you specify a path parameter Back to Top What are the differences between cookie local storage and session storageBelow are some of the differences between cookie local storage and session storage FeatureCookieLocal storageSession storageAccessed on client or server sideBoth server side amp client sideclient side onlyclient side onlyLifetimeAs configured using Expires optionuntil deleteduntil tab is closedSSL supportSupportedNot supportedNot supportedMaximum data sizeKB MBMBBack to Top What is the main difference between localStorage and sessionStorageLocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened i e it has no expiration time whereas in sessionStorage data gets cleared when the page session ends Back to Top How do you access web storageThe Window object implements the WindowLocalStorage and WindowSessionStorage objects which has localStorage window localStorage and sessionStorage window sessionStorage properties respectively These properties create an instance of the Storage object through which data items can be set retrieved and removed for a specific domain and storage type session or local For example you can read and write on local storage objects as belowlocalStorage setItem logo document getElementById logo value localStorage getItem logo Back to Top What are the methods available on session storageThe session storage provided methods for reading writing and clearing the session data Save data to sessionStoragesessionStorage setItem key value Get saved data from sessionStoragelet data sessionStorage getItem key Remove saved data from sessionStoragesessionStorage removeItem key Remove all saved data from sessionStoragesessionStorage clear Back to Top What is a storage event and its event handlerThe StorageEvent is an event that fires when a storage area has been changed in the context of another document Whereas onstorage property is an EventHandler for processing storage events The syntax would be as below window onstorage functionRef Let s take the example usage of onstorage event handler which logs the storage key and it s valueswindow onstorage function e console log The e key key has been changed from e oldValue to e newValue Back to Top Why do you need web storageWeb storage is more secure and large amounts of data can be stored locally without affecting website performance Also the information is never transferred to the server Hence this is a more recommended approach than Cookies Back to Top How do you check web storage browser supportYou need to check browser support for localStorage and sessionStorage before using web storage if typeof Storage undefined Code for localStorage sessionStorage else Sorry No Web Storage support Back to Top How do you check web workers browser supportYou need to check browser support for web workers before using itif typeof Worker undefined code for Web worker support else Sorry No Web Worker support Back to Top Give an example of a web workerYou need to follow below steps to start using web workers for counting exampleCreate a Web Worker File You need to write a script to increment the count value Let s name it as counter jslet i function timedCount i i postMessage i setTimeout timedCount timedCount Here postMessage method is used to post a message back to the HTML pageCreate a Web Worker Object You can create a web worker object by checking for browser support Let s name this file as web worker example jsif typeof w undefined w new Worker counter js and we can receive messages from web workerw onmessage function event document getElementById message innerHTML event data Terminate a Web Worker Web workers will continue to listen for messages even after the external script is finished until it is terminated You can use the terminate method to terminate listening to the messages w terminate Reuse the Web Worker If you set the worker variable to undefined you can reuse the codew undefined Back to Top What are the restrictions of web workers on DOMWebWorkers don t have access to below javascript objects since they are defined in an external filesWindow objectDocument objectParent objectBack to Top What is a promiseA promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it s not resolved for example network error It will be in one of the possible states fulfilled rejected or pending The syntax of Promise creation looks like below const promise new Promise function resolve reject promise description The usage of a promise would be as below const promise new Promise resolve gt setTimeout gt resolve I m a Promise reject gt promise then value gt console log value The action flow of a promise will be as below Back to Top Why do you need a promisePromises are used to handle asynchronous operations They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code Back to Top What are the three states of promisePromises have three states Pending This is an initial state of the Promise before an operation beginsFulfilled This state indicates that the specified operation was completed Rejected This state indicates that the operation did not complete In this case an error value will be thrown Back to Top What is a callback functionA callback function is a function passed into another function as an argument This function is invoked inside the outer function to complete an action Let s take a simple example of how to use callback functionfunction callbackFunction name console log Hello name function outerFunction callback let name prompt Please enter your name callback name outerFunction callbackFunction Back to Top Why do we need callbacksThe callbacks are needed because javascript is an event driven language That means instead of waiting for a response javascript will keep executing while listening for other events Let s take an example with the first function invoking an API call simulated by setTimeout and the next function which logs the message function firstFunction Simulate a code delay setTimeout function console log First function called function secondFunction console log Second function called firstFunction secondFunction Output Second function called First function calledAs observed from the output javascript didn t wait for the response of the first function and the remaining code block got executed So callbacks are used in a way to make sure that certain code doesn t execute until the other code finishes execution Back to Top What is a callback hellCallback Hell is an anti pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic The callback hell looks like below async function async function async function async function Back to Top What are server sent eventsServer sent events SSE is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling These are a one way communications channel events flow from server to client only This has been used in Facebook Twitter updates stock price updates news feeds etc Back to Top How do you receive server sent event notificationsThe EventSource object is used to receive server sent event notifications For example you can receive messages from server as below if typeof EventSource undefined var source new EventSource sse generator js source onmessage function event document getElementById output innerHTML event data lt br gt Back to Top How do you check browser support for server sent eventsYou can perform browser support for server sent events before using it as below if typeof EventSource undefined Server sent events supported Let s have some code here else No server sent events supported Back to Top What are the events available for server sent eventsBelow are the list of events available for server sent events Event Description onopen It is used when a connection to the server is opened onmessage This event is used when a message is received onerror It happens when an error occurs Back to Top What are the main rules of promiseA promise must follow a specific set of rules A promise is an object that supplies a standard compliant then methodA pending promise may transition into either fulfilled or rejected stateA fulfilled or rejected promise is settled and it must not transition into any other state Once a promise is settled the value must not change Back to Top What is callback in callbackYou can nest one callback inside in another callback to execute the actions sequentially one by one This is known as callbacks in callbacks loadScript script js function script console log first script is loaded loadScript script js function script console log second script is loaded loadScript script js function script console log third script is loaded after all scripts are loaded Back to Top What is promise chainingThe process of executing a sequence of asynchronous tasks one after another using promises is known as Promise chaining Let s take an example of promise chaining for calculating the final result new Promise function resolve reject setTimeout gt resolve then function result console log result return result then function result console log result return result then function result console log result return result In the above handlers the result is passed to the chain of then handlers with the below work flow The initial promise resolves in second After that then handler is called by logging the result and then return a promise with the value of result After that the value passed to the next then handler by logging the result and return a promise with result Finally the value passed to the last then handler by logging the result and return a promise with result Back to Top What is promise allPromise all is a promise that takes an array of promises as an input an iterable and it gets resolved when all the promises get resolved or any one of them gets rejected For example the syntax of promise all method is below Promise all Promise Promise Promise then result gt console log result catch error gt console log Error in promises error Note Remember that the order of the promises output the result is maintained as per input order Back to Top What is the purpose of the race method in promisePromise race method will return the promise instance which is firstly resolved or rejected Let s take an example of race method where promise is resolved firstvar promise new Promise function resolve reject setTimeout resolve one var promise new Promise function resolve reject setTimeout resolve two Promise race promise promise then function value console log value two Both promises will resolve but promise is faster Back to Top What is a strict mode in javascriptStrict Mode is a new feature in ECMAScript that allows you to place a program or a function in a “strict operating context This way it prevents certain actions from being taken and throws more exceptions The literal expression use strict instructs the browser to use the javascript code in the Strict mode Back to Top Why do you need strict modeStrict mode is useful to write secure JavaScript by notifying bad syntax into real errors For example it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non writable property a getter only property a non existing property a non existing variable or a non existing object Back to Top How do you declare strict modeThe strict mode is declared by adding use strict to the beginning of a script or a function If declared at the beginning of a script it has global scope use strict x This will cause an error because x is not declaredand if you declare inside a function it has local scopex This will not cause an error myFunction function myFunction use strict y This will cause an error Back to Top What is the purpose of double exclamationThe double exclamation or negation ensures the resulting type is a boolean If it was falsey e g null undefined etc it will be false otherwise true For example you can test IE version using this expression as below let isIE false isIE navigator userAgent match MSIE console log isIE returns true or falseIf you don t use this expression then it returns the original value console log navigator userAgent match MSIE returns either an Array or nullNote The expression is not an operator but it is just twice of operator Back to Top What is the purpose of the delete operatorThe delete keyword is used to delete the property as well as its value var user name John age delete user age console log user name John Back to Top What is the typeof operatorYou can use the JavaScript typeof operator to find the type of a JavaScript variable It returns the type of a variable or an expression typeof John Abraham Returns string typeof Returns number Back to Top What is undefined propertyThe undefined property indicates that a variable has not been assigned a value or not declared at all The type of undefined value is undefined too var user Value is undefined type is undefinedconsole log typeof user undefinedAny variable can be emptied by setting the value to undefined user undefinedBack to Top What is null valueThe value null represents the intentional absence of any object value It is one of JavaScript s primitive values The type of null value is object You can empty the variable by setting the value to null var user null console log typeof user objectBack to Top What is the difference between null and undefinedBelow are the main differences between null and undefined NullUndefinedIt is an assignment value which indicates that variable points to no object It is not an assignment value where a variable has been declared but has not yet been assigned a value Type of null is objectType of undefined is undefinedThe null value is a primitive value that represents the null empty or non existent reference The undefined value is a primitive value used when a variable has not been assigned a value Indicates the absence of a value for a variableIndicates absence of variable itselfConverted to zero while performing primitive operationsConverted to NaN while performing primitive operationsBack to Top What is evalThe eval function evaluates JavaScript code represented as a string The string can be a JavaScript expression variable statement or sequence of statements console log eval Back to Top What is the difference between window and documentBelow are the main differences between window and document WindowDocumentIt is the root level element in any web pageIt is the direct child of the window object This is also known as Document Object Model DOM By default window object is available implicitly in the pageYou can access it via window document or document It has methods like alert confirm and properties like document locationIt provides methods like getElementById getElementByTagName createElement etcBack to Top How do you access history in javascriptThe window history object contains the browser s history You can load previous and next URLs in the history using back and next methods function goBack window history back function goForward window history forward Note You can also access history without window prefix Back to Top How do you detect caps lock key turned on or notThe mouseEvent getModifierState is used to return a boolean value that indicates whether the specified modifier key is activated or not The modifiers such as CapsLock ScrollLock and NumLock are activated when they are clicked and deactivated when they are clicked again Let s take an input element to detect the CapsLock on off behavior with an example lt input type password onmousedown enterInput event gt lt p id feedback gt lt p gt lt script gt function enterInput e var flag e getModifierState CapsLock if flag document getElementById feedback innerHTML CapsLock activated else document getElementById feedback innerHTML CapsLock not activated lt script gt Back to Top What is isNaNThe isNaN function is used to determine whether a value is an illegal number Not a Number or not i e This function returns true if the value equates to NaN Otherwise it returns false isNaN Hello trueisNaN falseBack to Top What are the differences between undeclared and undefined variablesBelow are the major differences between undeclared and undefined variables undeclaredundefinedThese variables do not exist in a program and are not declaredThese variables declared in the program but have not assigned any valueIf you try to read the value of an undeclared variable then a runtime error is encounteredIf you try to read the value of an undefined variable an undefined value is returned Back to Top What are global variablesGlobal variables are those that are available throughout the length of the code without any scope The var keyword is used to declare a local variable but if you omit it then it will become global variablemsg Hello var is missing it becomes global variableBack to Top What are the problems with global variablesThe problem with global variables is the conflict of variable names of local and global scope It is also difficult to debug and test the code that relies on global variables Back to Top What is NaN propertyThe NaN property is a global property that represents Not a Number value i e It indicates that a value is not a legal number It is very rare to use NaN in a program but it can be used as return value for few casesMath sqrt parseInt Hello Back to Top What is the purpose of isFinite functionThe isFinite function is used to determine whether a number is a finite legal number It returns false if the value is infinity infinity or NaN Not a Number otherwise it returns true isFinite Infinity falseisFinite NaN falseisFinite Infinity falseisFinite trueBack to Top What is an event flowEvent flow is the order in which event is received on the web page When you click an element that is nested in various other elements before your click actually reaches its destination or target element it must trigger the click event for each of its parent elements first starting at the top with the global window object There are two ways of event flowTop to Bottom Event Capturing Bottom to Top Event Bubbling Back to Top What is event bubblingEvent bubbling is a type of event propagation where the event first triggers on the innermost target element and then successively triggers on the ancestors parents of the target element in the same nesting hierarchy till it reaches the outermost DOM element Back to Top What is event capturingEvent capturing is a type of event propagation where the event is first captured by the outermost element and then successively triggers on the descendants children of the target element in the same nesting hierarchy till it reaches the innermost DOM element Back to Top How do you submit a form using JavaScriptYou can submit a form using JavaScript use document form submit All the form input s information is submitted using onsubmit event handlerfunction submit document form submit Back to Top How do you find operating system detailsThe window navigator object contains information about the visitor s browser OS details Some of the OS properties are available under platform property console log navigator platform Back to Top What is the difference between document load and DOMContentLoaded eventsThe DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed without waiting for assets stylesheets images and subframes to finish loading Whereas The load event is fired when the whole page has loaded including all dependent resources stylesheets images Back to Top What is the difference between native host and user objectsNative objects are objects that are part of the JavaScript language defined by the ECMAScript specification For example String Math RegExp Object Function etc core objects defined in the ECMAScript spec Host objects are objects provided by the browser or runtime environment Node For example window XmlHttpRequest DOM nodes etc are considered as host objects User objects are objects defined in the javascript code For example User objects created for profile information Back to Top What are the tools or techniques used for debugging JavaScript codeYou can use below tools or techniques for debugging javascriptChrome Devtoolsdebugger statementGood old console log statementBack to Top What are the pros and cons of promises over callbacksBelow are the list of pros and cons of promises over callbacks Pros It avoids callback hell which is unreadableEasy to write sequential asynchronous code with then Easy to write parallel asynchronous code with Promise all Solves some of the common problems of callbacks call the callback too late too early many times and swallow errors exceptions Cons It makes little complex codeYou need to load a polyfill if ES is not supportedBack to Top What is the difference between an attribute and a propertyAttributes are defined on the HTML markup whereas properties are defined on the DOM For example the below HTML element has attributes type and value lt input type text value Name gt You can retrieve the attribute value as below const input document querySelector input console log input getAttribute value Good morningconsole log input value Good morningAnd after you change the value of the text field to Good evening it becomes likeconsole log input getAttribute value Good morningconsole log input value Good eveningBack to Top What is same origin policyThe same origin policy is a policy that prevents JavaScript from making requests across domain boundaries An origin is defined as a combination of URI scheme hostname and port number If you enable this policy then it prevents a malicious script on one page from obtaining access to sensitive data on another web page using Document Object Model DOM Back to Top What is the purpose of void Void is used to prevent the page from refreshing This will be helpful to eliminate the unwanted side effect because it will return the undefined primitive value It is commonly used for HTML documents that use href JavaScript Void within anelement i e when you click a link the browser loads a new page or refreshes the same page But this behavior will be prevented using this expression For example the below link notify the message without reloading the page javascript lt a href JavaScript void onclick alert Well done gt Click Me lt a gt Back to Top Is JavaScript a compiled or interpreted languageJavaScript is an interpreted language not a compiled language An interpreter in the browser reads over the JavaScript code interprets each line and runs it Nowadays modern browsers use a technology known as Just In Time JIT compilation which compiles JavaScript to executable bytecode just as it is about to run Back to Top Is JavaScript a case sensitive languageYes JavaScript is a case sensitive language The language keywords variables function amp object names and any other identifiers must always be typed with a consistent capitalization of letters Back to Top Is there any relation between Java and JavaScriptNo they are entirely two different programming languages and have nothing to do with each other But both of them are Object Oriented Programming languages and like many other languages they follow similar syntax for basic features if else for switch break continue etc Back to Top What are eventsEvents are things that happen to HTML elements When JavaScript is used in HTML pages JavaScript can react on these events Some of the examples of HTML events are Web page has finished loadingInput field was changedButton was clickedLet s describe the behavior of click event for button element lt doctype html gt lt html gt lt head gt lt script gt function greeting alert Hello Good morning lt script gt lt head gt lt body gt lt button type button onclick greeting gt Click me lt button gt lt body gt lt html gt Back to Top Who created javascriptJavaScript was created by Brendan Eich in during his time at Netscape Communications Initially it was developed under the name Mocha but later the language was officially called LiveScript when it first shipped in beta releases of Netscape Back to Top What is the use of preventDefault methodThe preventDefault method cancels the event if it is cancelable meaning that the default action or behaviour that belongs to the event will not occur For example prevent form submission when clicking on submit button and prevent opening the page URL when clicking on hyperlink are some common use cases document getElementById link addEventListener click function event event preventDefault Note Remember that not all events are cancelable Back to Top What is the use of stopPropagation methodThe stopPropagation method is used to stop the event from bubbling up the event chain For example the below nested divs with stopPropagation method prevents default event propagation when clicking on nested div Div lt p gt Click DIV Element lt p gt lt div onclick secondFunc gt DIV lt div onclick firstFunc event gt DIV lt div gt lt div gt lt script gt function firstFunc event alert DIV event stopPropagation function secondFunc alert DIV lt script gt Back to Top What are the steps involved in return false usageThe return false statement in event handlers performs the below steps First it stops the browser s default action or behaviour It prevents the event from propagating the DOMStops callback execution and returns immediately when called Back to Top What is BOMThe Browser Object Model BOM allows JavaScript to talk to the browser It consists of the objects navigator history screen location and document which are children of the window The Browser Object Model is not standardized and can change based on different browsers Back to Top What is the use of setTimeoutThe setTimeout method is used to call a function or evaluate an expression after a specified number of milliseconds For example let s log a message after seconds using setTimeout method setTimeout function console log Good morning Back to Top What is the use of setIntervalThe setInterval method is used to call a function or evaluate an expression at specified intervals in milliseconds For example let s log a message after seconds using setInterval method setInterval function console log Good morning Back to Top Why is JavaScript treated as Single threadedJavaScript is a single threaded language Because the language specification does not allow the programmer to write code so that the interpreter can run parts of it in parallel in multiple threads or processes Whereas languages like java go C can make multi threaded and multi process programs Back to Top What is an event delegationEvent delegation is a technique for listening to events where you delegate a parent element as the listener for all of the events that happen inside it For example if you wanted to detect field changes in inside a specific form you can use event delegation technique var form document querySelector registration form Listen for changes to fields inside the form form addEventListener input function event Log the field that was changed console log event target false Back to Top What is ECMAScriptECMAScript is the scripting language that forms the basis of JavaScript ECMAScript standardized by the ECMA International standards organization in the ECMA and ECMA specifications The first edition of ECMAScript was released in Back to Top What is JSONJSON JavaScript Object Notation is a lightweight format that is used for data interchanging It is based on a subset of JavaScript language in the way objects are built in JavaScript Back to Top What are the syntax rules of JSONBelow are the list of syntax rules of JSONThe data is in name value pairsThe data is separated by commasCurly braces hold objectsSquare brackets hold arraysBack to Top What is the purpose JSON stringifyWhen sending data to a web server the data has to be in a string format You can achieve this by converting JSON object into a string using stringify method var userJSON name John age var userString JSON stringify user console log userString name John age Back to Top How do you parse JSON stringWhen receiving the data from a web server the data is always in a string format But you can convert this string value to a javascript object using parse method var userString name John age var userJSON JSON parse userString console log userJSON name John age Back to Top Why do you need JSONWhen exchanging data between a browser and a server the data can only be text Since JSON is text only it can easily be sent to and from a server and used as a data format by any programming language Back to Top What are PWAsProgressive web applications PWAs are a type of mobile app delivered through the web built using common web technologies including HTML CSS and JavaScript These PWAs are deployed to servers accessible through URLs and indexed by search engines Back to Top What is the purpose of clearTimeout methodThe clearTimeout function is used in javascript to clear the timeout which has been set by setTimeout function before that i e The return value of setTimeout function is stored in a variable and it s passed into the clearTimeout function to clear the timer For example the below setTimeout method is used to display the message after seconds This timeout can be cleared by the clearTimeout method lt script gt var msg function greeting alert Good morning function start msg setTimeout greeting function stop clearTimeout msg lt script gt Back to Top What is the purpose of clearInterval methodThe clearInterval function is used in javascript to clear the interval which has been set by setInterval function i e The return value returned by setInterval function is stored in a variable and it s passed into the clearInterval function to clear the interval For example the below setInterval method is used to display the message for every seconds This interval can be cleared by the clearInterval method lt script gt var msg function greeting alert Good morning function start msg setInterval greeting function stop clearInterval msg lt script gt Back to Top How do you redirect new page in javascriptIn vanilla javascript you can redirect to a new page using the location property of window object The syntax would be as follows function redirect window location href newPage html Back to Top How do you check whether a string contains a substringThere are possible ways to check whether a string contains a substring or not Using includes ES provided String prototype includes method to test a string contains a substring var mainString hello subString hell mainString includes subString Using indexOf In an ES or older environment you can use String prototype indexOf which returns the index of a substring If the index value is not equal to then it means the substring exists in the main string var mainString hello subString hell mainString indexOf subString Using RegEx The advanced solution is using Regular expression s test method RegExp test which allows for testing for against regular expressions var mainString hello regex hell regex test mainString Back to Top How do you validate an email in javascriptYou can validate an email in javascript using regular expressions It is recommended to do validations on the server side instead of the client side Because the javascript can be disabled on the client side function validateEmail email var re lt gt s lt gt s a zA Z a zA Z return re test String email toLowerCase Back to TopThe above regular expression accepts unicode characters How do you get the current url with javascriptYou can use window location href expression to get the current url path and you can use the same expression for updating the URL too You can also use document URL for read only purposes but this solution has issues in FF console log location href window location href Returns full URLBack to Top What are the various url properties of location objectThe below Location object properties can be used to access URL components of the page href The entire URLprotocol The protocol of the URLhost The hostname and port of the URLhostname The hostname of the URLport The port number in the URLpathname The path name of the URLsearch The query portion of the URLhash The anchor portion of the URLBack to Top How do get query string values in javascriptYou can use URLSearchParams to get query string values in javascript Let s see an example to get the client code value from URL query string const urlParams new URLSearchParams window location search const clientCode urlParams get clientCode Back to Top How do you check if a key exists in an objectYou can check whether a key exists in an object or not using three approaches Using in operator You can use the in operator whether a key exists in an object or not key in objand If you want to check if a key doesn t exist remember to use parenthesis key in obj Using hasOwnProperty method You can use hasOwnProperty to particularly test for properties of the object instance and not inherited properties obj hasOwnProperty key trueUsing undefined comparison If you access a non existing property from an object the result is undefined Let s compare the properties against undefined to determine the existence of the property const user name John console log user name undefined true console log user nickName undefined falseBack to Top How do you loop through or enumerate javascript objectYou can use the for in loop to loop through javascript object You can also make sure that the key you get is an actual property of an object and doesn t come from the prototype using hasOwnProperty method var object k value k value k value for var key in object if object hasOwnProperty key console log key gt object key k gt value Back to Top How do you test for an empty objectThere are different solutions based on ECMAScript versionsUsing Object entries ECMA You can use object entries length along with constructor type Object entries obj length amp amp obj constructor Object Since date object length is you need to check constructor check as wellUsing Object keys ECMA You can use object keys length along with constructor type Object keys obj length amp amp obj constructor Object Since date object length is you need to check constructor check as wellUsing for in with hasOwnProperty Pre ECMA You can use a for in loop along with hasOwnProperty function isEmpty obj for var prop in obj if obj hasOwnProperty prop return false return JSON stringify obj JSON stringify Back to Top What is an arguments objectThe arguments object is an Array like object accessible inside functions that contains the values of the arguments passed to that function For example let s see how to use arguments object inside sum function function sum var total for var i len arguments length i lt len i total arguments i return total sum returns Note You can t apply array methods on arguments object But you can convert into a regular array as below var argsArray Array prototype slice call arguments Back to Top How do you make first letter of the string in an uppercaseYou can create a function which uses a chain of string methods such as charAt toUpperCase and slice methods to generate a string with the first letter in uppercase function capitalizeFirstLetter string return string charAt toUpperCase string slice Back to Top What are the pros and cons of for loopThe for loop is a commonly used iteration syntax in javascript It has both pros and cons ProsWorks on every environmentYou can use break and continue flow control statements ConsToo verboseImperativeYou might face one by off errorsBack to Top How do you display the current date in javascriptYou can use new Date to generate a new Date object containing the current date and time For example let s display the current date in mm dd yyyy var today new Date var dd String today getDate padStart var mm String today getMonth padStart January is var yyyy today getFullYear today mm dd yyyy document write today Back to Top How do you compare two date objectsYou need to use date getTime method to compare date values instead of comparison operators and operators var d new Date var d new Date d console log d getTime d getTime True console log d d FalseBack to Top How do you check if a string starts with another stringYou can use ECMAScript s String prototype startsWith method to check if a string starts with another string or not But it is not yet supported in all browsers Let s see an example to see this usage Good morning startsWith Good true Good morning startsWith morning falseBack to Top How do you trim a string in javascriptJavaScript provided a trim method on string types to trim any whitespaces present at the beginning or ending of the string Hello World trim Hello WorldIf your browser lt IE doesn t support this method then you can use below polyfill if String prototype trim function Make sure we trim BOM and NBSP var rtrim s uFEFF xA s uFEFF xA g String prototype trim function return this replace rtrim Back to Top How do you add a key value pair in javascriptThere are two possible solutions to add new properties to an object Let s take a simple object to explain these solutions var object key value key value Using dot notation This solution is useful when you know the name of the property object key value Using square bracket notation This solution is useful when the name of the property is dynamically determined obj key value Back to Top Is the notation represents a special operatorNo that s not a special operator But it is a combination of standard operators one after the other A logical not A prefix decrement At first the value decremented by one and then tested to see if it is equal to zero or not for determining the truthy falsy value Back to Top How do you assign default values to variablesYou can use the logical or operator in an assignment expression to provide a default value The syntax looks like as below var a b c As per the above expression variable a will get the value of c only if b is falsy if is null false undefined empty string or NaN otherwise a will get the value of b Back to Top How do you define multiline stringsYou can define multiline string literals using the character followed by line terminator var str This is a very lengthy sentence But if you have a space after the character the code will look exactly the same but it will raise a SyntaxError Back to Top What is an app shell modelAn application shell or app shell architecture is one way to build a Progressive Web App that reliably and instantly loads on your users screens similar to what you see in native applications It is useful for getting some initial HTML to the screen fast without a network Back to Top Can we define properties for functionsYes We can define properties for functions because functions are also objects fn function x Function code goes here fn name John fn profile function y Profile code goes here Back to Top What is the way to find the number of parameters expected by a functionYou can use function length syntax to find the number of parameters expected by a function Let s take an example of sum function to calculate the sum of numbers function sum num num num num return num num num num sum length is the number of parameters expected Back to Top What is a polyfillA polyfill is a piece of JS code used to provide modern functionality on older browsers that do not natively support it For example Silverlight plugin polyfill can be used to mimic the functionality of an HTML Canvas element on Microsoft Internet Explorer Back to Top What are break and continue statementsThe break statement is used to jump out of a loop i e It breaks the loop and continues executing the code after the loop for i i lt i if i break text Number i lt br gt The continue statement is used to jump over one iteration in the loop i e It breaks one iteration in the loop if a specified condition occurs and continues with the next iteration in the loop for i i lt i if i continue text Number i lt br gt Back to Top What are js labelsThe label statement allows us to name loops and blocks in JavaScript We can then use these labels to refer back to the code later For example the below code with labels avoids printing the numbers when they are same var i j loop for i i lt i loop for j j lt j if i j continue loop console log i i j j Output is i j i j i j Back to Top What are the benefits of keeping declarations at the topIt is recommended to keep all declarations at the top of each script or function The benefits of doing this are Gives cleaner codeIt provides a single place to look for local variablesEasy to avoid unwanted global variablesIt reduces the possibility of unwanted re declarationsBack to Top What are the benefits of initializing variablesIt is recommended to initialize variables because of the below benefits It gives cleaner codeIt provides a single place to initialize variablesAvoid undefined values in the codeBack to Top What are the recommendations to create new objectIt is recommended to avoid creating new objects using new Object Instead you can initialize values based on it s type to create the objects Assign instead of new Object Assign instead of new String Assign instead of new Number Assign false instead of new Boolean Assign instead of new Array Assign instead of new RegExp Assign function instead of new Function You can define them as an example var v var v var v var v false var v var v var v function Back to Top How do you define JSON arraysJSON arrays are written inside square brackets and arrays contain javascript objects For example the JSON array of users would be as below users firstName John lastName Abrahm firstName Anna lastName Smith firstName Shane lastName Warn Back to Top How do you generate random integersYou can use Math random with Math floor to return random integers For example if you want generate random integers between to the multiplication factor should be Math floor Math random returns a random integer from to Math floor Math random returns a random integer from to Note Math random returns a random number between inclusive and exclusive Back to Top Can you write a random integers function to print integers with in a rangeYes you can create a proper random function to return a random number between min and max both included function randomInteger min max return Math floor Math random max min min randomInteger returns a random integer from to randomInteger returns a random integer from to Back to Top What is tree shakingTree shaking is a form of dead code elimination It means that unused modules will not be included in the bundle during the build process and for that it relies on the static structure of ES module syntax i e import and export Initially this has been popularized by the ES module bundler rollup Back to Top What is the need of tree shakingTree Shaking can significantly reduce the code size in any application i e The less code we send over the wire the more performant the application will be For example if we just want to create a “Hello World Application using SPA frameworks then it will take around a few MBs but by tree shaking it can bring down the size to just a few hundred KBs Tree shaking is implemented in Rollup and Webpack bundlers Back to Top Is it recommended to use evalNo it allows arbitrary code to be run which causes a security problem As we know that the eval function is used to run text as code In most of the cases it should not be necessary to use it Back to Top What is a Regular ExpressionA regular expression is a sequence of characters that forms a search pattern You can use this search pattern for searching data in a text These can be used to perform all types of text search and text replace operations Let s see the syntax format now pattern modifiers For example the regular expression or search pattern with case insensitive username would be John iBack to Top What are the string methods available in Regular expressionRegular Expressions has two string methods search and replace The search method uses an expression to search for a match and returns the position of the match var msg Hello John var n msg search John i The replace method is used to return a modified string where the pattern is replaced var msg Hello John var n msg replace John i Buttler Hello ButtlerBack to Top What are modifiers in regular expressionModifiers can be used to perform case insensitive and global searches Let s list down some of the modifiers Modifier Description i Perform case insensitive matching g Perform a global match rather than stops at first match m Perform multiline matching Let s take an example of global modifier var text Learn JS one by one var pattern one g var result text match pattern one oneBack to Top What are regular expression patternsRegular Expressions provide a group of patterns in order to match characters Basically they are categorized into types Brackets These are used to find a range of characters For example below are some use cases abc Used to find any of the characters between the brackets a b c Used to find any of the digits between the brackets a b Used to find any of the alternatives separated with Metacharacters These are characters with a special meaningFor example below are some use cases d Used to find a digit s Used to find a whitespace character b Used to find a match at the beginning or ending of a wordQuantifiers These are useful to define quantitiesFor example below are some use cases n Used to find matches for any string that contains at least one nn Used to find matches for any string that contains zero or more occurrences of nn Used to find matches for any string that contains zero or one occurrences of nBack to Top What is a RegExp objectRegExp object is a regular expression object with predefined properties and methods Let s see the simple usage of RegExp object var regexp new RegExp w console log regexp expected output w Back to Top How do you search a string for a patternYou can use the test method of regular expression in order to search a string for a pattern and return true or false depending on the result var pattern you console log pattern test How are you trueBack to Top What is the purpose of exec methodThe purpose of exec method is similar to test method but it executes a search for a match in a specified string and returns a result array or null instead of returning true false var pattern you console log pattern exec How are you you index input How are you groups undefined Back to Top How do you change the style of a HTML elementYou can change inline style or classname of a HTML element using javascriptUsing style property You can modify inline style using style property document getElementById title style fontSize px Using ClassName property It is easy to modify element class using className property document getElementById title className custom title Back to Top What would be the result of The output is going to be Since and are numeric values the result of the first two digits is going to be a numeric value The next digit is a string type value because of that the addition of numeric value and string type value is just going to be a concatenation value Back to Top What is a debugger statementThe debugger statement invokes any available debugging functionality such as setting a breakpoint If no debugging functionality is available this statement has no effect For example in the below function a debugger statement has been inserted So execution is paused at the debugger statement just like a breakpoint in the script source function getProfile code goes here debugger code goes here Back to Top What is the purpose of breakpoints in debuggingYou can set breakpoints in the javascript code once the debugger statement is executed and the debugger window pops up At each breakpoint javascript will stop executing and let you examine the JavaScript values After examining values you can resume the execution of code using the play button Back to Top Can I use reserved words as identifiersNo you cannot use the reserved words as variables labels object or function names Let s see one simple example var else hello Uncaught SyntaxError Unexpected token elseBack to Top How do you detect a mobile browserYou can use regex which returns a true or false value depending on whether or not the user is browsing with a mobile window mobilecheck function var mobileCheck false function a if android bb d meego mobile avantgo bada blackberry blazer compal elaine fennec hiptop iemobile ip hone od iris kindle lge maemo midp mmp mobile firefox netfront opera m ob in i palm os phone p ixi re plucker pocket psp series symbian treo up browser link vodafone wap windows ce xda xiino i test a gso thp i s s a wa abac ac er oo s ai ko rn al av ca co amoi an ex ny yw aptu ar ch go as te us attw au di m r s avan be ck ll nq bi lb rd bl ac az br e v w bumb bw n u c capi ccwa cdm cell chtm cldc cmd co mp nd craw da it ll ng dbte dc s devi dica dmob do c p o ds d el ai em l ul er ic k esl ez os wa ze fetc fly g u g gene gf g mo go w od gr ad un haie hcit hd m p t hei hi pt ta hp i ip hs c ht c a g p s t tp hu aw tc i go ma i iac ibro idea ig ikom imk inno ipaq iris ja t v a jbro jemu jigs kddi keji kgt klon kpt kwc kyo c k le no xi lg g k l u a w libw lynx m w mga m ma te ui xo mc ca m cr me rc ri mi o oa ts mmef mo bi de do t o v zz mt p v mwbp mywa n n n n n ne c m on tf wf wg wt nok i nzph oim op ti wv oran owg p pan a d t pdxg pg c phil pire pl ay uc pn po ck rt se prox psio pt g qa a qc i qtek r r raks rim ro ve zo s sa ge ma mm ms ny va sc h oo p sdk se c mc nd ri sgh shar sie m sk sl id sm al ar b it t so ft ny sp h v v sy mb t t ta gt lk tcl tdg tel i m tim t mo to pl sh ts m m m tx up b g si utst v v veri vi rg te vk v vm voda vulc vx wc webc whit wi g nc nw wmlb wonu x yas your zeto zte i test a substr mobileCheck true navigator userAgent navigator vendor window opera return mobileCheck Back to Top How do you detect a mobile browser without regexpYou can detect mobile browsers by simply running through a list of devices and checking if the useragent matches anything This is an alternative solution for RegExp usage function detectmob if navigator userAgent match Android i navigator userAgent match webOS i navigator userAgent match iPhone i navigator userAgent match iPad i navigator userAgent match iPod i navigator userAgent match BlackBerry i navigator userAgent match Windows Phone i return true else return false Back to Top How do you get the image width and height using JSYou can programmatically get the image and check the dimensions width and height using Javascript var img new Image img onload function console log this width x this height img src Back to Top How do you make synchronous HTTP requestBrowsers provide an XMLHttpRequest object which can be used to make synchronous HTTP requests from JavaScript function httpGet theUrl var xmlHttpReq new XMLHttpRequest xmlHttpReq open GET theUrl false false for synchronous request xmlHttpReq send null return xmlHttpReq responseText Back to Top How do you make asynchronous HTTP requestBrowsers provide an XMLHttpRequest object which can be used to make asynchronous HTTP requests from JavaScript by passing the rd parameter as true function httpGetAsync theUrl callback var xmlHttpReq new XMLHttpRequest xmlHttpReq onreadystatechange function if xmlHttpReq readyState amp amp xmlHttpReq status callback xmlHttpReq responseText xmlHttp open GET theUrl true true for asynchronous xmlHttp send null Back to Top How do you convert date to another timezone in javascriptYou can use the toLocaleString method to convert dates in one timezone to another For example let s convert current date to British English timezone as below console log event toLocaleString en GB timeZone UTC Back to Top What are the properties used to get size of windowYou can use innerWidth innerHeight clientWidth clientHeight properties of windows document element and document body objects to find the size of a window Let s use them combination of these properties to calculate the size of a window or document var width window innerWidth document documentElement clientWidth document body clientWidth var height window innerHeight document documentElement clientHeight document body clientHeight Back to Top What is a conditional operator in javascriptThe conditional ternary operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statements var isAuthenticated false console log isAuthenticated Hello welcome Sorry you are not authenticated Sorry you are not authenticatedBack to Top Can you apply chaining on conditional operatorYes you can apply chaining on conditional operators similar to if …else if …else if …else chain The syntax is going to be as below function traceValue someParam return condition value condition value condition value value The above conditional operator is equivalent to function traceValue someParam if condition return value else if condition return value else if condition return value else return value Back to Top What are the ways to execute javascript after page loadYou can execute javascript after page load in many different ways window onload window onload function document onload document onload function body onload lt body onload script gt Back to Top What is the difference between proto and prototypeThe proto object is the actual object that is used in the lookup chain to resolve methods etc Whereas prototype is the object that is used to build proto when you create an object with new new Employee proto Employee prototype new Employee prototype undefined Back to Top Give an example where do you really need semicolonIt is recommended to use semicolons after every statement in JavaScript For example in the below case it throws an error is not a function at runtime due to missing semicolon define a function var fn function semicolon missing at this line then execute some code inside a closure function and it will be interpreted as var fn function function In this case we are passing the second function as an argument to the first function and then trying to call the result of the first function call as a function Hence the second function will fail with a is not a function error at runtime Back to Top What is a freeze methodThe freeze method is used to freeze an object Freezing an object does not allow adding new properties to an object prevents from removing and prevents changing the enumerability configurability or writability of existing properties i e It returns the passed object and does not create a frozen copy const obj prop Object freeze obj obj prop Throws an error in strict mode console log obj prop Note It causes a TypeError if the argument passed is not an object Back to Top What is the purpose of freeze methodBelow are the main benefits of using freeze method It is used for freezing objects and arrays It is used to make an object immutable Back to Top Why do I need to use freeze methodIn the Object oriented paradigm an existing API contains certain elements that are not intended to be extended modified or re used outside of their current context Hence it works as the final keyword which is used in various languages Back to Top How do you detect a browser language preferenceYou can use navigator object to detect a browser language preference as below var language navigator languages amp amp navigator languages Chrome Firefox navigator language All browsers navigator userLanguage IE lt console log language Back to Top How to convert string to title case with javascriptTitle case means that the first letter of each word is capitalized You can convert a string to title case using the below function function toTitleCase str return str replace w S g function txt return txt charAt toUpperCase txt substr toLowerCase toTitleCase good morning john Good Morning JohnBack to Top How do you detect javascript disabled in the pageYou can use the lt noscript gt tag to detect javascript disabled or not The code block inside lt noscript gt gets executed when JavaScript is disabled and is typically used to display alternative content when the page generated in JavaScript lt script type javascript gt JS related code goes here lt script gt lt noscript gt lt a href next page html noJS true gt JavaScript is disabled in the page Please click Next Page lt a gt lt noscript gt Back to Top What are various operators supported by javascriptAn operator is capable of manipulating mathematical and logical computations a certain value or operand There are various operators supported by JavaScript as below Arithmetic Operators Includes Addition Subtraction Multiplication Division Modulus Increment and Decrement Comparison Operators Includes Equal Not Equal Equal with type gt Greater than gt Greater than or Equal to lt Less than lt Less than or Equal to Logical Operators Includes amp amp Logical AND Logical OR Logical NOT Assignment Operators Includes Assignment Operator Add and Assignment Operator Subtract and Assignment Operator Multiply and Assignment Divide and Assignment Modules and Assignment Ternary Operators It includes conditional Operatortypeof Operator It uses to find type of variable The syntax looks like typeof variableBack to Top What is a rest parameterRest parameter is an improved way to handle function parameters which allows us to represent an indefinite number of arguments as an array The syntax would be as below function f a b theArgs For example let s take a sum example to calculate on dynamic number of parameters function total …args let sum for let i of args sum i return sum console log fun console log fun console log fun console log fun Note Rest parameter is added in ES or ESBack to Top What happens if you do not use rest parameter as a last argumentThe rest parameter should be the last argument as its job is to collect all the remaining arguments into an array For example if you define a function like below it doesn t make any sense and will throw an error function someFunc a …b c You code goes here return Back to Top What are the bitwise operators available in javascriptBelow are the list of bitwise logical operators used in JavaScriptBitwise AND amp Bitwise OR Bitwise XOR Bitwise NOT Left Shift lt lt Sign Propagating Right Shift gt gt Zero fill Right Shift gt gt gt Back to Top What is a spread operatorSpread operator allows iterables arrays objects strings to be expanded into single arguments elements Let s take an example to see this behavior function calculateSum x y z return x y z const numbers console log calculateSum numbers Back to Top How do you determine whether object is frozen or notObject isFrozen method is used to determine if an object is frozen or not An object is frozen if all of the below conditions hold true If it is not extensible If all of its properties are non configurable If all its data properties are non writable The usage is going to be as follows const object property Welcome JS world Object freeze object console log Object isFrozen object Back to Top How do you determine two values same or not using objectThe Object is method determines whether two values are the same value For example the usage with different types of values would be Object is hello hello true Object is window window true Object is falseTwo values are the same if one of the following holds both undefinedboth nullboth true or both falseboth strings of the same length with the same characters in the same orderboth the same object means both object have same reference both numbers andboth both both NaNboth non zero and both not NaN and both have the same value Back to Top What is the purpose of using object is methodSome of the applications of Object s is method are follows It is used for comparison of two strings It is used for comparison of two numbers It is used for comparing the polarity of two numbers It is used for comparison of two objects Back to Top How do you copy properties from one object to otherYou can use the Object assign method which is used to copy the values and properties from one or more source objects to a target object It returns the target object which has properties and values copied from the target object The syntax would be as below Object assign target sources Let s take example with one source and one target object const target a b const source b c const returnedTarget Object assign target source console log target a b c console log returnedTarget a b c As observed in the above code there is a common property b from source to target so it s value has been overwritten Back to Top What are the applications of assign methodBelow are the some of main applications of Object assign method It is used for cloning an object It is used to merge objects with the same properties Back to Top What is a proxy objectThe Proxy object is used to define custom behavior for fundamental operations such as property lookup assignment enumeration function invocation etc The syntax would be as follows var p new Proxy target handler Let s take an example of proxy object var handler get function obj prop return prop in obj obj prop var p new Proxy handler p a p b null console log p a p b null console log c in p p c false In the above code it uses get handler which define the behavior of the proxy when an operation is performed on itBack to Top What is the purpose of seal methodThe Object seal method is used to seal an object by preventing new properties from being added to it and marking all existing properties as non configurable But values of present properties can still be changed as long as they are writable Let s see the below example to understand more about seal method const object property Welcome JS world Object seal object object property Welcome to object world console log Object isSealed object true delete object property You cannot delete when sealed console log object property Welcome to object worldBack to Top What are the applications of seal methodBelow are the main applications of Object seal method It is used for sealing objects and arrays It is used to make an object immutable Back to Top What are the differences between freeze and seal methodsIf an object is frozen using the Object freeze method then its properties become immutable and no changes can be made in them whereas if an object is sealed using the Object seal method then the changes can be made in the existing properties of the object Back to Top How do you determine if an object is sealed or notThe Object isSealed method is used to determine if an object is sealed or not An object is sealed if all of the below conditions hold trueIf it is not extensible If all of its properties are non configurable If it is not removable but not necessarily non writable Let s see it in the action const object property Hello Good morning Object seal object Using seal method to seal the object console log Object isSealed object checking whether the object is sealed or notBack to Top How do you get enumerable key and value pairsThe Object entries method is used to return an array of a given object s own enumerable string keyed property key value pairs in the same order as that provided by a for in loop Let s see the functionality of object entries method in an example const object a Good morning b for let key value of Object entries object console log key value a Good morning b Note The order is not guaranteed as object defined Back to Top What is the main difference between Object values and Object entries methodThe Object values method s behavior is similar to Object entries method but it returns an array of values instead key value pairs const object a Good morning b for let value of Object values object console log value Good morning Back to Top How can you get the list of keys of any objectYou can use the Object keys method which is used to return an array of a given object s own property names in the same order as we get with a normal loop For example you can get the keys of a user object const user name John gender male age console log Object keys user name gender age Back to Top How do you create an object with prototypeThe Object create method is used to create a new object with the specified prototype object and properties i e It uses an existing object as the prototype of the newly created object It returns a new object with the specified prototype object and properties const user name John printInfo function console log My name is this name const admin Object create user admin name Nick Remember that name is a property set on admin but not on user object admin printInfo My name is NickBack to Top What is a WeakSetWeakSet is used to store a collection of weakly weak references held objects The syntax would be as follows new WeakSet iterable Let s see the below example to explain it s behavior var ws new WeakSet var user ws add user ws has user true ws delete user removes user from the set ws has user false user has been removedBack to Top What are the differences between WeakSet and SetThe main difference is that references to objects in Set are strong while references to objects in WeakSet are weak i e An object in WeakSet can be garbage collected if there is no other reference to it Other differences are Sets can store any value Whereas WeakSets can store only collections of objectsWeakSet does not have size property unlike SetWeakSet does not have methods such as clear keys values entries forEach WeakSet is not iterable Back to Top List down the collection of methods available on WeakSetBelow are the list of methods available on WeakSet add value A new object is appended with the given value to the weaksetdelete value Deletes the value from the WeakSet collection has value It returns true if the value is present in the WeakSet Collection otherwise it returns false length It returns the length of weakSetObjectLet s see the functionality of all the above methods in an example var weakSetObject new WeakSet var firstObject var secondObject add value weakSetObject add firstObject weakSetObject add secondObject console log weakSetObject has firstObject true console log weakSetObject length weakSetObject delete secondObject Back to Top What is a WeakMapThe WeakMap object is a collection of key value pairs in which the keys are weakly referenced In this case keys must be objects and the values can be arbitrary values The syntax is looking like as below new WeakMap iterable Let s see the below example to explain it s behavior var ws new WeakMap var user ws set user ws has user true ws delete user removes user from the map ws has user false user has been removedBack to Top What are the differences between WeakMap and MapThe main difference is that references to key objects in Map are strong while references to key objects in WeakMap are weak i e A key object in WeakMap can be garbage collected if there is no other reference to it Other differences are Maps can store any key type Whereas WeakMaps can store only collections of key objectsWeakMap does not have size property unlike MapWeakMap does not have methods such as clear keys values entries forEach WeakMap is not iterable Back to Top List down the collection of methods available on WeakMapBelow are the list of methods available on WeakMap set key value Sets the value for the key in the WeakMap object Returns the WeakMap object delete key Removes any value associated to the key has key Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not get key Returns the value associated to the key or undefined if there is none Let s see the functionality of all the above methods in an example var weakMapObject new WeakMap var firstObject var secondObject set key value weakMapObject set firstObject John weakMapObject set secondObject console log weakMapObject has firstObject true console log weakMapObject get firstObject John weakMapObject delete secondObject Back to Top What is the purpose of unevalThe uneval is an inbuilt function which is used to create a string representation of the source code of an Object It is a top level function and is not associated with any object Let s see the below example to know more about it s functionality var a uneval a returns a String containing uneval function user returns function user Back to Top How do you encode an URLThe encodeURI function is used to encode complete URI which has special characters except amp characters var uri var encoded encodeURI uri console log encoded Back to Top How do you decode an URLThe decodeURI function is used to decode a Uniform Resource Identifier URI previously created by encodeURI var uri var encoded encodeURI uri console log encoded try console log decodeURI encoded catch e catches a malformed URI console error e Back to Top How do you print the contents of web pageThe window object provided a print method which is used to print the contents of the current window It opens a Print dialog box which lets you choose between various printing options Let s see the usage of print method in an example lt input type button value Print onclick window print gt Note In most browsers it will block while the print dialog is open Back to Top What is the difference between uneval and evalThe uneval function returns the source of a given object whereas the eval function does the opposite by evaluating that source code in a different memory area Let s see an example to clarify the difference var msg uneval function greeting return Hello Good morning var greeting eval msg greeting returns Hello Good morning Back to Top What is an anonymous functionAn anonymous function is a function without a name Anonymous functions are commonly assigned to a variable name or used as a callback function The syntax would be as below function optionalParameters do something const myFunction function Anonymous function assigned to a variable do something map function element Anonymous function used as a callback function do something Let s see the above anonymous function in an example var x function a b return a b var z x console log z Back to Top What is the precedence order between local and global variablesA local variable takes precedence over a global variable with the same name Let s see this behavior in an example var msg Good morning function greeting msg Good Evening console log msg greeting Back to Top What are javascript accessorsECMAScript introduced javascript object accessors or computed properties through getters and setters Getters uses the get keyword whereas Setters uses the set keyword var user firstName John lastName Abraham language en get lang return this language set lang lang this language lang console log user lang getter access lang as en user lang fr console log user lang setter used to set lang as frBack to Top How do you define property on Object constructorThe Object defineProperty static method is used to define a new property directly on an object or modify an existing property on an object and returns the object Let s see an example to know how to define property const newObject Object defineProperty newObject newProperty value writable false console log newObject newProperty newObject newProperty It throws an error in strict mode due to writable settingBack to Top What is the difference between get and definePropertyBoth have similar results until unless you use classes If you use get the property will be defined on the prototype of the object whereas using Object defineProperty the property will be defined on the instance it is applied to Back to Top What are the advantages of Getters and SettersBelow are the list of benefits of Getters and Setters They provide simpler syntaxThey are used for defining computed properties or accessors in JS Useful to provide equivalence relation between properties and methodsThey can provide better data qualityUseful for doing things behind the scenes with the encapsulated logic Back to Top Can I add getters and setters using defineProperty methodYes You can use the Object defineProperty method to add Getters and Setters For example the below counter object uses increment decrement add and subtract properties var obj counter Define getters Object defineProperty obj increment get function this counter Object defineProperty obj decrement get function this counter Define setters Object defineProperty obj add set function value this counter value Object defineProperty obj subtract set function value this counter value obj add obj subtract console log obj increment console log obj decrement Back to Top What is the purpose of switch caseThe switch case statement in JavaScript is used for decision making purposes In a few cases using the switch case statement is going to be more convenient than if else statements The syntax would be as below switch expression case value statement break case value statement break case valueN statementN break default statementDefault The above multi way branch statement provides an easy way to dispatch execution to different parts of code based on the value of the expression Back to Top What are the conventions to be followed for the usage of switch caseBelow are the list of conventions should be taken care The expression can be of type either number or string Duplicate values are not allowed for the expression The default statement is optional If the expression passed to switch does not match with any case value then the statement within default case will be executed The break statement is used inside the switch to terminate a statement sequence The break statement is optional But if it is omitted the execution will continue on into the next case Back to Top What are primitive data typesA primitive data type is data that has a primitive value which has no properties or methods There are types of primitive data types stringnumberbooleannullundefinedbigintsymbolBack to Top What are the different ways to access object propertiesThere are possible ways for accessing the property of an object Dot notation It uses dot for accessing the properties objectName propertySquare brackets notation It uses square brackets for property access objectName property Expression notation It uses expression in the square brackets objectName expression Back to Top What are the function parameter rulesJavaScript functions follow below rules for parameters The function definitions do not specify data types for parameters Do not perform type checking on the passed arguments Do not check the number of arguments received i e The below function follows the above rules function functionName parameter parameter parameter console log parameter functionName Back to Top What is an error objectAn error object is a built in error object that provides error information when an error occurs It has two properties name and message For example the below function logs error details try greeting Welcome catch err console log err name lt br gt err message Back to Top When you get a syntax errorA SyntaxError is thrown if you try to evaluate code with a syntax error For example the below missing quote for the function parameter throws a syntax error try eval greeting welcome Missing will produce an error catch err console log err name Back to Top What are the different error names from error objectThere are different types of error names returned from error object Error Name Description EvalError An error has occurred in the eval function RangeError An error has occurred with a number out of range ReferenceError An error due to an illegal reference SyntaxError An error due to a syntax error TypeError An error due to a type error URIError An error due to encodeURI Back to Top What are the various statements in error handlingBelow are the list of statements used in an error handling try This statement is used to test a block of code for errorscatch This statement is used to handle the errorthrow This statement is used to create custom errors finally This statement is used to execute code after try and catch regardless of the result Back to Top What are the two types of loops in javascriptEntry Controlled loops In this kind of loop type the test condition is tested before entering the loop body For example For Loop and While Loop comes under this category Exit Controlled Loops In this kind of loop type the test condition is tested or evaluated at the end of the loop body i e the loop body will execute at least once irrespective of test condition true or false For example do while loop comes under this category Back to Top What is nodejsNode js is a server side platform built on Chrome s JavaScript runtime for easily building fast and scalable network applications It is an event based non blocking asynchronous I O runtime that uses Google s V JavaScript engine and libuv library Back to Top What is an Intl objectThe Intl object is the namespace for the ECMAScript Internationalization API which provides language sensitive string comparison number formatting and date and time formatting It provides access to several constructors and language sensitive functions Back to Top How do you perform language specific date and time formattingYou can use the Intl DateTimeFormat object which is a constructor for objects that enable language sensitive date and time formatting Let s see this behavior with an example var date new Date Date UTC console log new Intl DateTimeFormat en GB format date console log new Intl DateTimeFormat en AU format date Back to Top What is an IteratorAn iterator is an object which defines a sequence and a return value upon its termination It implements the Iterator protocol with a next method which returns an object with two properties value the next value in the sequence and done which is true if the last value in the sequence has been consumed Back to Top How does synchronous iteration worksSynchronous iteration was introduced in ES and it works with below set of components Iterable It is an object which can be iterated over via a method whose key is Symbol iterator Iterator It is an object returned by invoking Symbol iterator on an iterable This iterator object wraps each iterated element in an object and returns it via next method one by one IteratorResult It is an object returned by next method The object contains two properties the value property contains an iterated element and the done property determines whether the element is the last element or not Let s demonstrate synchronous iteration with an array as below const iterable one two three const iterator iterable Symbol iterator console log iterator next value one done false console log iterator next value two done false console log iterator next value three done false console log iterator next value undefined done true Back to Top What is an event loopThe Event Loop is a queue of callback functions When an async function executes the callback function is pushed into the queue The JavaScript engine doesn t start processing the event loop until the async function has finished executing the code Note It allows Node js to perform non blocking I O operations even though JavaScript is single threaded Back to Top What is call stackCall Stack is a data structure for javascript interpreters to keep track of function calls in the program It has two major actions Whenever you call a function for its execution you are pushing it to the stack Whenever the execution is completed the function is popped out of the stack Let s take an example and it s state representation in a diagram format function hungry eatFruits function eatFruits return I m eating fruits Invoke the hungry function hungry The above code processed in a call stack as below Add the hungry function to the call stack list and execute the code Add the eatFruits function to the call stack list and execute the code Delete the eatFruits function from our call stack list Delete the hungry function from the call stack list since there are no items anymore Back to Top What is an event queueBack to Top What is a decoratorA decorator is an expression that evaluates to a function and that takes the target name and decorator descriptor as arguments Also it optionally returns a decorator descriptor to install on the target object Let s define admin decorator for user class at design time function admin isAdmin return function target target isAdmin isAdmin admin true class User console log User isAdmin true admin false class User console log User isAdmin falseBack to Top What are the properties of Intl objectBelow are the list of properties available on Intl object Collator These are the objects that enable language sensitive string comparison DateTimeFormat These are the objects that enable language sensitive date and time formatting ListFormat These are the objects that enable language sensitive list formatting NumberFormat Objects that enable language sensitive number formatting PluralRules Objects that enable plural sensitive formatting and language specific rules for plurals RelativeTimeFormat Objects that enable language sensitive relative time formatting Back to Top What is an Unary operatorThe unary operator is used to convert a variable to a number If the variable cannot be converted it will still become a number but with the value NaN Let s see this behavior in an action var x var y x console log typeof x typeof y string number var a Hello var b a console log typeof a typeof b b string number NaNBack to Top How do you sort elements in an arrayThe sort method is used to sort the elements of an array in place and returns the sorted array The example usage would be as below var months Aug Sep Jan June months sort console log months Aug Jan June Sep Back to Top What is the purpose of compareFunction while sorting arraysThe compareFunction is used to define the sort order If omitted the array elements are converted to strings then sorted according to each character s Unicode code point value Let s take an example to see the usage of compareFunction let numbers numbers sort a b gt b a console log numbers Back to Top How do you reversing an arrayYou can use the reverse method to reverse the elements in an array This method is useful to sort an array in descending order Let s see the usage of reverse method in an example let numbers numbers sort a b gt b a numbers reverse console log numbers Back to Top How do you find min and max value in an arrayYou can use Math min and Math max methods on array variables to find the minimum and maximum elements within an array Let s create two functions to find the min and max value with in an array var marks function findMin arr return Math min apply null arr function findMax arr return Math max apply null arr console log findMin marks console log findMax marks Back to Top How do you find min and max values without Math functionsYou can write functions which loop through an array comparing each value with the lowest value or highest value to find the min and max values Let s create those functions to find min and max values var marks function findMin arr var length arr length var min Infinity while length if arr length lt min min arr len return min function findMax arr var length arr length var max Infinity while len if arr length gt max max arr length return max console log findMin marks console log findMax marks Back to Top What is an empty statement and purpose of itThe empty statement is a semicolon indicating that no statement will be executed even if JavaScript syntax requires one Since there is no action with an empty statement you might think that it s usage is quite less but the empty statement is occasionally useful when you want to create a loop that has an empty body For example you can initialize an array with zero values as below Initialize an array a for int i i lt a length a i Back to Top How do you get metadata of a moduleYou can use the import meta object which is a meta property exposing context specific meta data to a JavaScript module It contains information about the current module such as the module s URL In browsers you might get different meta data than NodeJS lt script type module src welcome module js gt lt script gt console log import meta url file home user welcome module js Back to Top What is a comma operatorThe comma operator is used to evaluate each of its operands from left to right and returns the value of the last operand This is totally different from comma usage within arrays objects and function arguments and parameters For example the usage for numeric expressions would be as below var x x x x console log x Back to Top What is the advantage of a comma operatorIt is normally used to include multiple expressions in a location that requires a single expression One of the common usages of this comma operator is to supply multiple parameters in a for loop For example the below for loop uses multiple expressions in a single location using comma operator for var a b a lt a b You can also use the comma operator in a return statement where it processes before returning function myFunction var a return a a Back to Top What is typescriptTypeScript is a typed superset of JavaScript created by Microsoft that adds optional types classes async await and many other features and compiles to plain JavaScript Angular built entirely in TypeScript and used as a primary language You can install it globally as npm install g typescriptLet s see a simple example of TypeScript usage function greeting name string string return Hello name let user Sudheer console log greeting user The greeting method allows only string type as argument Back to Top What are the differences between javascript and typescriptBelow are the list of differences between javascript and typescript feature typescript javascript Language paradigm Object oriented programming language Scripting language Typing support Supports static typing It has dynamic typing Modules Supported Not supported Interface It has interfaces concept Doesn t support interfaces Optional parameters Functions support optional parameters No support of optional parameters for functions Back to Top What are the advantages of typescript over javascriptBelow are some of the advantages of typescript over javascript TypeScript is able to find compile time errors at the development time only and it makes sures less runtime errors Whereas javascript is an interpreted language TypeScript is strongly typed or supports static typing which allows for checking type correctness at compile time This is not available in javascript TypeScript compiler can compile the ts files into ES ES and ES unlike ES features of javascript which may not be supported in some browsers Back to Top What is an object initializerAn object initializer is an expression that describes the initialization of an Object The syntax for this expression is represented as a comma delimited list of zero or more pairs of property names and associated values of an object enclosed in curly braces This is also known as literal notation It is one of the ways to create an object var initObject a John b c console log initObject a JohnBack to Top What is a constructor methodThe constructor method is a special method for creating and initializing an object created within a class If you do not specify a constructor method a default constructor is used The example usage of constructor would be as below class Employee constructor this name John var employeeObject new Employee console log employeeObject name JohnBack to Top What happens if you write constructor more than once in a classThe constructor in a class is a special method and it should be defined only once in a class i e If you write a constructor method more than once in a class it will throw a SyntaxError error class Employee constructor this name John constructor Uncaught SyntaxError A class may only have one constructor this age var employeeObject new Employee console log employeeObject name Back to Top How do you call the constructor of a parent classYou can use the super keyword to call the constructor of a parent class Remember that super must be called before using this reference Otherwise it will cause a reference error Let s the usage of it class Square extends Rectangle constructor length super length length this name Square get area return this width this height set area value this area value Back to Top How do you get the prototype of an objectYou can use the Object getPrototypeOf obj method to return the prototype of the specified object i e The value of the internal prototype property If there are no inherited properties then null value is returned const newPrototype const newObject Object create newPrototype console log Object getPrototypeOf newObject newPrototype trueBack to Top What happens If I pass string type for getPrototype methodIn ES it will throw a TypeError exception if the obj parameter isn t an object Whereas in ES the parameter will be coerced to an Object ES Object getPrototypeOf James TypeError James is not an object ES Object getPrototypeOf James String prototypeBack to Top How do you set prototype of one object to anotherYou can use the Object setPrototypeOf method that sets the prototype i e the internal Prototype property of a specified object to another object or null For example if you want to set prototype of a square object to rectangle object would be as follows Object setPrototypeOf Square prototype Rectangle prototype Object setPrototypeOf null Back to Top How do you check whether an object can be extendable or notThe Object isExtensible method is used to determine if an object is extendable or not i e Whether it can have new properties added to it or not const newObject console log Object isExtensible newObject trueNote By default all the objects are extendable i e The new properties can be added or modified Back to Top How do you prevent an object to extendThe Object preventExtensions method is used to prevent new properties from ever being added to an object In other words it prevents future extensions to the object Let s see the usage of this property const newObject Object preventExtensions newObject NOT extendable try Object defineProperty newObject newProperty Adding new property value catch e console log e TypeError Cannot define property newProperty object is not extensible Back to Top What are the different ways to make an object non extensibleYou can mark an object non extensible in ways Object preventExtensionsObject sealObject freeze var newObject Object preventExtensions newObject Prevent objects are non extensible Object isExtensible newObject false var sealedObject Object seal Sealed objects are non extensible Object isExtensible sealedObject false var frozenObject Object freeze Frozen objects are non extensible Object isExtensible frozenObject falseBack to Top How do you define multiple properties on an objectThe Object defineProperties method is used to define new or modify existing properties directly on an object and returning the object Let s define multiple properties on an empty object const newObject Object defineProperties newObject newProperty value John writable true newProperty Back to Top What is MEAN in javascriptThe MEAN MongoDB Express AngularJS and Node js stack is the most popular open source JavaScript software tech stack available for building dynamic web apps where you can write both the server side and client side halves of the web project entirely in JavaScript Back to Top What Is Obfuscation in javascriptObfuscation is the deliberate act of creating obfuscated javascript code i e source or machine code that is difficult for humans to understand It is something similar to encryption but a machine can understand the code and execute it Let s see the below function before Obfuscation function greeting console log Hello welcome to JS world And after the code Obfuscation it would be appeared as below eval function p a c k e d e function c return c if replace String while c d c k c c k function e return d e e function return w c while c if k c p p replace new RegExp b e c b g k c return p console greeting function log Hello JS to welcome world split Back to Top Why do you need ObfuscationBelow are the few reasons for Obfuscation The Code size will be reduced So data transfers between server and client will be fast It hides the business logic from outside world and protects the code from othersReverse engineering is highly difficultThe download time will be reducedBack to Top What is MinificationMinification is the process of removing all unnecessary characters empty spaces are removed and variables will be renamed without changing it s functionality It is also a type of obfuscation Back to Top What are the advantages of minificationNormally it is recommended to use minification for heavy traffic and intensive requirements of resources It reduces file sizes with below benefits Decreases loading times of a web pageSaves bandwidth usagesBack to Top What are the differences between Obfuscation and EncryptionBelow are the main differences between Obfuscation and Encryption Feature Obfuscation Encryption Definition Changing the form of any data in any other form Changing the form of information to an unreadable format by using a key A key to decode It can be decoded without any key It is required Target data format It will be converted to a complex form Converted into an unreadable format Back to Top What are the common tools used for minificationThere are many online offline tools to minify the javascript files Google s Closure CompilerUglifyJSjsminjavascript minifier com prettydiff comBack to Top How do you perform form validation using javascriptJavaScript can be used to perform HTML form validation For example if the form field is empty the function needs to notify and return false to prevent the form being submitted Lets perform user login in an html form lt form name myForm onsubmit return validateForm method post gt User name lt input type text name uname gt lt input type submit value Submit gt lt form gt And the validation on user login is below function validateForm var x document forms myForm uname value if x alert The username shouldn t be empty return false Back to Top How do you perform form validation without javascriptYou can perform HTML form validation automatically without using javascript The validation enabled by applying the required attribute to prevent form submission when the input is empty lt form method post gt lt input type text name uname required gt lt input type submit value Submit gt lt form gt Note Automatic form validation does not work in Internet Explorer or earlier Back to Top What are the DOM methods available for constraint validationThe below DOM methods are available for constraint validation on an invalid input checkValidity It returns true if an input element contains valid data setCustomValidity It is used to set the validationMessage property of an input element Let s take an user login form with DOM validations function myFunction var userName document getElementById uname if userName checkValidity document getElementById message innerHTML userName validationMessage else document getElementById message innerHTML Entered a valid username Back to Top What are the available constraint validation DOM propertiesBelow are the list of some of the constraint validation DOM properties available validity It provides a list of boolean properties related to the validity of an input element validationMessage It displays the message when the validity is false willValidate It indicates if an input element will be validated or not Back to Top What are the list of validity propertiesThe validity property of an input element provides a set of properties related to the validity of data customError It returns true if a custom validity message is set patternMismatch It returns true if an element s value does not match its pattern attribute rangeOverflow It returns true if an element s value is greater than its max attribute rangeUnderflow It returns true if an element s value is less than its min attribute stepMismatch It returns true if an element s value is invalid according to step attribute tooLong It returns true if an element s value exceeds its maxLength attribute typeMismatch It returns true if an element s value is invalid according to type attribute valueMissing It returns true if an element with a required attribute has no value valid It returns true if an element s value is valid Back to Top Give an example usage of rangeOverflow propertyIf an element s value is greater than its max attribute then rangeOverflow property returns true For example the below form submission throws an error if the value is more than lt input id age type number max gt lt button onclick myOverflowFunction gt OK lt button gt javascript function myOverflowFunction if document getElementById age validity rangeOverflow alert The mentioned age is not allowed Back to Top table of contents Is enums feature available in javascriptNo javascript does not natively support enums But there are different kinds of solutions to simulate them even though they may not provide exact equivalents For example you can use freeze or seal on object var DaysEnum Object freeze monday tuesday wednesday Back to Top What is an enumAn enum is a type restricting variables to one value from a predefined set of constants JavaScript has no enums but typescript provides built in enum support enum Color RED GREEN BLUE Back to Top How do you list all properties of an objectYou can use the Object getOwnPropertyNames method which returns an array of all properties found directly in a given object Let s the usage of it in an example const newObject a b c console log Object getOwnPropertyNames newObject a b c Back to Top How do you get property descriptors of an objectYou can use the Object getOwnPropertyDescriptors method which returns all own property descriptors of a given object The example usage of this method is below const newObject a b c const descriptorsObject Object getOwnPropertyDescriptors newObject console log descriptorsObject a writable true console log descriptorsObject a configurable true console log descriptorsObject a enumerable true console log descriptorsObject a value Back to Top What are the attributes provided by a property descriptorA property descriptor is a record which has the following attributesvalue The value associated with the propertywritable Determines whether the value associated with the property can be changed or notconfigurable Returns true if the type of this property descriptor can be changed and if the property can be deleted from the corresponding object enumerable Determines whether the property appears during enumeration of the properties on the corresponding object or not set A function which serves as a setter for the propertyget A function which serves as a getter for the propertyBack to Top How do you extend classesThe extends keyword is used in class declarations expressions to create a class which is a child of another class It can be used to subclass custom classes as well as built in objects The syntax would be as below class ChildClass extends ParentClass Let s take an example of Square subclass from Polygon parent class class Square extends Rectangle constructor length super length length this name Square get area return this width this height set area value this area value Back to Top How do I modify the url without reloading the pageThe window location url property will be helpful to modify the url but it reloads the page HTML introduced the history pushState and history replaceState methods which allow you to add and modify history entries respectively For example you can use pushState as below window history pushState page Title page html Back to Top How do you check whether an array includes a particular value or notThe Array includes method is used to determine whether an array includes a particular value among its entries by returning either true or false Let s see an example to find an element numeric and string within an array var numericArray console log numericArray includes true var stringArray green yellow blue console log stringArray includes blue trueBack to Top How do you compare scalar arraysYou can use length and every method of arrays to compare two scalar compared directly using arrays The combination of these expressions can give the expected result const arrayFirst const arraySecond console log arrayFirst length arraySecond length amp amp arrayFirst every value index gt value arraySecond index true If you would like to compare arrays irrespective of order then you should sort them before javascript const arrayFirst const arraySecond console log arrayFirst length arraySecond length amp amp arrayFirst sort every value index gt value arraySecond index true Back to Top How to get the value from get parametersThe new URL object accepts the url string and searchParams property of this object can be used to access the get parameters Remember that you may need to use polyfill or window location to access the URL in older browsers including IE javascript let urlString y amp z window location href let url new URL urlString let parameterZ url searchParams get z console log parameterZ Back to Top How do you print numbers with commas as thousand separatorsYou can use the Number prototype toLocaleString method which returns a string with a language sensitive representation such as thousand separator currency etc of this number javascript function convertToThousandFormat x return x toLocaleString console log convertToThousandFormat Back to Top What is the difference between java and javascriptBoth are totally unrelated programming languages and no relation between them Java is statically typed compiled runs on its own VM Whereas Javascript is dynamically typed interpreted and runs in a browser and nodejs environments Let s see the major differences in a tabular format Feature Java JavaScript Typed It s a strongly typed language It s a dynamic typed language Paradigm Object oriented programming Prototype based programming Scoping Block scoped Function scoped Concurrency Thread based event based Memory Uses more memory Uses less memory Hence it will be used for web pages Back to Top Is javascript supports namespaceJavaScript doesn t support namespace by default So if you create any element function method object variable then it becomes global and pollutes the global namespace Let s take an example of defining two functions without any namespace javascript function func console log This is a first definition function func console log This is a second definition func This is a second definition It always calls the second function definition In this case namespace will solve the name collision problem Back to Top How do you declare namespaceEven though JavaScript lacks namespaces we can use Objects IIFE to create namespaces Using Object Literal Notation Let s wrap variables and functions inside an Object literal which acts as a namespace After that you can access them using object notation javascript var namespaceOne function func console log This is a first definition var namespaceTwo function func console log This is a second definition namespaceOne func This is a first definition namespaceTwo func This is a second definition Using IIFE Immediately invoked function expression The outer pair of parentheses of IIFE creates a local scope for all the code inside of it and makes the anonymous function a function expression Due to that you can create the same function in two different function expressions to act as a namespace javascript function function fun console log This is a first definition fun function function fun console log This is a second definition fun Using a block and a let const declaration In ECMAScript you can simply use a block and a let declaration to restrict the scope of a variable to a block javascript let myFunction function fun console log This is a first definition myFunction myFunction ReferenceError myFunction is not defined let myFunction function fun console log This is a second definition myFunction myFunction ReferenceError myFunction is not defined Back to Top How do you invoke javascript code in an iframe from parent pageInitially iFrame needs to be accessed using either document getElementBy or window frames After that contentWindow property of iFrame gives the access for targetFunction javascript document getElementById targetFrame contentWindow targetFunction window frames frameElement contentWindow targetFunction Accessing iframe this way may not work in latest versions chrome and firefox Back to Top How do get the timezone offset from dateYou can use the getTimezoneOffset method of the date object This method returns the time zone difference in minutes from current locale host system settings to UTC javascript var offset new Date getTimezoneOffset console log offset Back to Top How do you load CSS and JS files dynamicallyYou can create both link and script elements in the DOM and append them as child to head tag Let s create a function to add script and style resources as below javascript function loadAssets filename filetype if filetype css External CSS file var fileReference document createElement link fileReference setAttribute rel stylesheet fileReference setAttribute type text css fileReference setAttribute href filename else if filetype js External JavaScript file var fileReference document createElement script fileReference setAttribute type text javascript fileReference setAttribute src filename if typeof fileReference undefined document getElementsByTagName head appendChild fileReference Back to Top What are the different methods to find HTML elements in DOMIf you want to access any element in an HTML page you need to start with accessing the document object Later you can use any of the below methods to find the HTML element document getElementById id It finds an element by Iddocument getElementsByTagName name It finds an element by tag namedocument getElementsByClassName name It finds an element by class nameBack to Top What is jQueryjQuery is a popular cross browser JavaScript library that provides Document Object Model DOM traversal event handling animations and AJAX interactions by minimizing the discrepancies across browsers It is widely famous with its philosophy of “Write less do more For example you can display welcome message on the page load using jQuery as below javascript document ready function It selects the document and apply the function on page load alert Welcome to jQuery world Note You can download it from jquery s official site or install it from CDNs like google Back to Top What is V JavaScript engineV is an open source high performance JavaScript engine used by the Google Chrome browser written in C It is also being used in the node js project It implements ECMAScript and WebAssembly and runs on Windows or later macOS and Linux systems that use x IA ARM or MIPS processors Note It can run standalone or can be embedded into any C application Back to Top Why do we call javascript as dynamic languageJavaScript is a loosely typed or a dynamic language because variables in JavaScript are not directly associated with any particular value type and any variable can be assigned reassigned with values of all types javascript let age age is a number now age old age is a string now age true age is a boolean Back to Top What is a void operatorThe void operator evaluates the given expression and then returns undefined i e without returning value The syntax would be as below javascript void expression void expression Let s display a message without any redirection or reload javascript lt a href javascript void alert Welcome to JS world gt Click here to see a message lt a gt Note This operator is often used to obtain the undefined primitive value using void Back to Top How to set the cursor to waitThe cursor can be set to wait in JavaScript by using the property cursor Let s perform this behavior on page load using the below function javascript function myFunction window document body style cursor wait and this function invoked on page load html lt body onload myFunction gt Back to Top How do you create an infinite loopYou can create infinite loops using for and while loops without using any expressions The for loop construct or syntax is better approach in terms of ESLint and code optimizer tools javascript for while true Back to Top Why do you need to avoid with statementJavaScript s with statement was intended to provide a shorthand for writing recurring accesses to objects So it can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty Let s take an example where it is used to avoid redundancy when accessing an object several times javascript a b c greeting welcome a b c age Using with it turns this into javascript with a b c greeting welcome age But this with statement creates performance problems since one cannot predict whether an argument will refer to a real variable or to a property inside the with argument Back to Top What is the output of below for loops javascript for var i i lt i global scope setTimeout gt console log i for let i i lt i block scope setTimeout gt console log i The output of the above for loops is and Explanation Due to the event queue loop of javascript the setTimeout callback function is called after the loop has been executed Since the variable i is declared with the var keyword it became a global variable and the value was equal to using iteration when the time setTimeout function is invoked Hence the output of the first loop is Whereas in the second loop the variable i is declared as the let keyword it becomes a block scoped variable and it holds a new value for each iteration Hence the output of the first loop is Back to Top List down some of the features of ESBelow are the list of some new features of ES Support for constants or immutable variablesBlock scope support for variables constants and functionsArrow functionsDefault parametersRest and Spread ParametersTemplate LiteralsMulti line StringsDestructuring AssignmentEnhanced Object LiteralsPromisesClassesModulesBack to Top What is ESES is the sixth edition of the javascript language and it was released in June It was initially known as ECMAScript ES and later renamed to ECMAScript Almost all the modern browsers support ES but for the old browsers there are many transpilers like Babel js etc Back to Top Can I redeclare let and const variablesNo you cannot redeclare let and const variables If you do it throws below error bash Uncaught SyntaxError Identifier someVariable has already been declared Explanation The variable declaration with var keyword refers to a function scope and the variable is treated as if it were declared at the top of the enclosing scope due to hoisting feature So all the multiple declarations contributing to the same hoisted variable without any error Let s take an example of re declaring variables in the same scope for both var and let const variables javascript var name John function myFunc var name Nick var name Abraham Re assigned in the same function block alert name Abraham myFunc alert name John The block scoped multi declaration throws syntax error javascript let name John function myFunc let name Nick let name Abraham Uncaught SyntaxError Identifier name has already been declared alert name myFunc alert name Back to Top Is const variable makes the value immutableNo the const variable doesn t make the value immutable But it disallows subsequent assignments i e You can declare with assignment but can t assign another value later javascript const userList userList push John Can mutate even though it can t re assign console log userList John Back to Top What are default parametersIn E we need to depend on logical OR operators to handle default values of function parameters Whereas in ES Default function parameters feature allows parameters to be initialized with default values if no value or undefined is passed Let s compare the behavior with an examples javascript ES var calculateArea function height width height height width width return width height console log calculateArea The default parameters makes the initialization more simpler javascript ES var calculateArea function height width return width height console log calculateArea Back to Top What are template literalsTemplate literals or template strings are string literals allowing embedded expressions These are enclosed by the back tick character instead of double or single quotes In E this feature enables using dynamic expressions as below javascript var greeting Welcome to JS World Mr firstName lastName In ES you need break string like below javascript var greeting Welcome to JS World Mr firstName lastName Note You can use multi line strings and string interpolation features with template literals Back to Top table of contents How do you write multi line strings in template literalsIn ES you would have to use newline escape characters n and concatenation symbols in order to get multi line strings javascript console log This is string sentence n This is string sentence Whereas in ES You don t need to mention any newline sequence character javascript console log This is string sentence This is string sentence Back to Top What are nesting templatesThe nesting template is a feature supported within template literals syntax to allow inner backticks inside a placeholder within the template For example the below nesting template is used to display the icons based on user permissions whereas outer template checks for platform type javascript const iconStyles icon isMobilePlatform icon user isAuthorized submit disabled You can write the above use case without nesting template features as well However the nesting template feature is more compact and readable javascript Without nesting templates const iconStyles icon isMobilePlatform user isAuthorized icon submit icon disabled Back to Top What are tagged templatesTagged templates are the advanced form of templates in which tags allow you to parse template literals with a function The tag function accepts the first parameter as an array of strings and remaining parameters as expressions This function can also return manipulated strings based on parameters Let s see the usage of this tagged template behavior of an IT professional skill set in an organization javascript var user John var skill JavaScript var experience var user Kane var skill JavaScript var experience function myInfoTag strings userExp experienceExp skillExp var str strings Mr Ms var str strings is a an var str strings in var expertiseStr if experienceExp gt expertiseStr expert developer else if skillExp gt amp amp skillExp lt expertiseStr senior developer else expertiseStr junior developer return str userExp str expertiseStr str skillExp var output myInfoTag Mr Ms user is a an experience in skill var output myInfoTag Mr Ms user is a an experience in skill console log output Mr Ms John is a an expert developer in JavaScript console log output Mr Ms Kane is a an junior developer in JavaScriptBack to Top What are raw stringsES provides a raw strings feature using the String raw method which is used to get the raw string form of template strings This feature allows you to access the raw strings as they were entered without processing escape sequences For example the usage would be as below javascript var calculationString String raw The sum of numbers is n console log calculationString The sum of numbers is If you don t use raw strings the newline character sequence will be processed by displaying the output in multiple linesjavascript var calculationString The sum of numbers is n console log calculationString The sum of numbers is Also the raw property is available on the first argument to the tag functionjavascript function tag strings console log strings raw Back to Top What is destructuring assignmentThe destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables Let s get the month values from an array using destructuring assignmentjavascript var one two three JAN FEB MARCH console log one JAN console log two FEB console log three MARCH and you can get user properties of an object using destructuring assignment javascript var name age name John age console log name John console log age Back to Top What are default values in destructuring assignmentA variable can be assigned a default value when the value unpacked from the array or object is undefined during destructuring assignment It helps to avoid setting default values separately for each assignment Let s take an example for both arrays and object use cases Arrays destructuring javascript var x y z x y z console log x console log y console log z Objects destructuring javascript var x y z x console log x console log y console log z Back to Top How do you swap variables in destructuring assignmentIf you don t use destructuring assignment swapping two values requires a temporary variable Whereas using a destructuring feature two variable values can be swapped in one destructuring expression Let s swap two number variables in array destructuring assignment javascript var x y x y y x console log x console log y Back to Top What are enhanced object literalsObject literals make it easy to quickly create objects with properties inside the curly braces For example it provides shorter syntax for common object property definition as below javascript ES var x y obj x y console log obj x y ES var x y obj x x y y console log obj x y Back to Top What are dynamic importsThe dynamic imports using import function syntax allows us to load modules on demand by using promises or the async await syntax Currently this feature is in stage proposal The main advantage of dynamic imports is reduction of our bundle s sizes the size payload response of our requests and overall improvements in the user experience The syntax of dynamic imports would be as below javascript import Module then Module gt Module method Back to Top What are the use cases for dynamic importsBelow are some of the use cases of using dynamic imports over static imports Import a module on demand or conditionally For example if you want to load a polyfill on legacy browserjavascript if isLegacyBrowser import ··· then ··· Compute the module specifier at runtime For example you can use it for internationalization javascript import messages getLocale js then ··· Import a module from within a regular script instead a module Back to Top What are typed arraysTyped arrays are array like objects from ECMAScript API for handling binary data JavaScript provides Typed array types IntArray An array of bit signed integersIntArray An array of bit signed integersIntArray An array of bit signed integersUintArray An array of bit unsigned integersUintArray An array of bit unsigned integersUintArray An array of bit unsigned integersFloatArray An array of bit floating point numbersFloatArray An array of bit floating point numbersFor example you can create an array of bit signed integers as belowjavascript const a new IntArray You can pre allocate n bytes const bytes const a new IntArray bytes Back to Top What are the advantages of module loadersThe module loaders provides the below features Dynamic loadingState isolationGlobal namespace isolationCompilation hooksNested virtualizationBack to Top What is collationCollation is used for sorting a set of strings and searching within a set of strings It is parameterized by locale and aware of Unicode Let s take comparison and sorting features Comparison javascript var list ä a z In German ä sorts with a Whereas in Swedish ä sorts after z var lnDE new Intl Collator de var lnSV new Intl Collator sv console log lnDE compare ä z true console log lnSV compare ä z trueSorting javascript var list ä a z In German ä sorts with a Whereas in Swedish ä sorts after z var lnDE new Intl Collator de var lnSV new Intl Collator sv console log list sort lnDE compare a ä z console log list sort lnSV compare a z ä Back to Top What is for of statementThe for of statement creates a loop iterating over iterable objects or elements such as built in String Array Array like objects like arguments or NodeList TypedArray Map Set and user defined iterables The basic usage of for of statement on arrays would be as below javascript let arrayIterable for let value of arrayIterable value console log value Back to Top What is the output of below spread operator arrayjavascript John Resig The output of the array is J o h n R e s i g Explanation The string is an iterable type and the spread operator within an array maps every character of an iterable to one element Hence each character of a string becomes an element within an Array Back to Top Is PostMessage secureYes postMessages can be considered very secure as long as the programmer developer is careful about checking the origin and source of an arriving message But if you try to send receive a message without verifying its source will create cross site scripting attacks Back to Top What are the problems with postmessage target origin as wildcardThe second argument of postMessage method specifies which origin is allowed to receive the message If you use the wildcard “ as an argument then any origin is allowed to receive the message In this case there is no way for the sender window to know if the target window is at the target origin when sending the message If the target window has been navigated to another origin the other origin would receive the data Hence this may lead to XSS vulnerabilities javascript targetWindow postMessage message Back to Top How do you avoid receiving postMessages from attackersSince the listener listens for any message an attacker can trick the application by sending a message from the attacker s origin which gives an impression that the receiver received the message from the actual sender s window You can avoid this issue by validating the origin of the message on the receiver s end using the “message origin attribute For examples let s check the sender s origin on receiver side www some receiver com javascript Listener on window addEventListener message function message if http www some sender com test message origin console log You received the data from valid sender message data Back to Top Can I avoid using postMessages completelyYou cannot avoid using postMessages completely or Even though your application doesn t use postMessage considering the risks a lot of third party scripts use postMessage to communicate with the third party service So your application might be using postMessage without your knowledge Back to Top Is postMessages synchronousThe postMessages are synchronous in IE browser but they are asynchronous in IE and all other modern browsers i e IE Firefox Chrome Safari Due to this asynchronous behaviour we use a callback mechanism when the postMessage is returned Back to Top What paradigm is JavascriptJavaScript is a multi paradigm language supporting imperative procedural programming Object Oriented Programming and functional programming JavaScript supports Object Oriented Programming with prototypical inheritance Back to Top What is the difference between internal and external javascriptInternal JavaScript It is the source code within the script tag External JavaScript The source code is stored in an external file stored with js extension and referred with in the tag Back to Top Is JavaScript faster than server side scriptYes JavaScript is faster than server side script Because JavaScript is a client side script it does not require any web server s help for its computation or calculation So JavaScript is always faster than any server side script like ASP PHP etc Back to Top How do you get the status of a checkboxYou can apply the checked property on the selected checkbox in the DOM If the value is True means the checkbox is checked otherwise it is unchecked For example the below HTML checkbox element can be access using javascript as below html lt input type checkbox name checkboxname value Agree gt Agree the conditions lt br gt javascript console log document getElementById checkboxname checked true or falseBack to Top What is the purpose of double tilde operatorThe double tilde operator is known as double NOT bitwise operator This operator is going to be a quicker substitute for Math floor Back to Top How do you convert character to ASCII codeYou can use the String prototype charCodeAt method to convert string characters to ASCII numbers For example let s find ASCII code for the first letter of ABC string javascript ABC charCodeAt returns Whereas String fromCharCode method converts numbers to equal ASCII characters javascript String fromCharCode returns ABC Back to Top What is ArrayBufferAn ArrayBuffer object is used to represent a generic fixed length raw binary data buffer You can create it as below javascript let buffer new ArrayBuffer create a buffer of length alert buffer byteLength To manipulate an ArrayBuffer we need to use a “view object javascript Create a DataView referring to the buffer let view new DataView buffer Back to Top What is the output of below string expressionjavascript console log Welcome to JS world The output of the above expression is W Explanation The bracket notation with specific index on a string returns the character at a specific location Hence it returns the character W of the string Since this is not supported in IE and below versions you may need to use the charAt method to get the desired result Back to Top What is the purpose of Error objectThe Error constructor creates an error object and the instances of error objects are thrown when runtime errors occur The Error object can also be used as a base object for user defined exceptions The syntax of error object would be as below javascript new Error message fileName lineNumber You can throw user defined exceptions or errors using Error object in try catch block as below javascript try if withdraw gt balance throw new Error Oops You don t have enough balance catch e console log e name e message Back to Top What is the purpose of EvalError objectThe EvalError object indicates an error regarding the global eval function Even though this exception is not thrown by JavaScript anymore the EvalError object remains for compatibility The syntax of this expression would be as below javascript new EvalError message fileName lineNumber You can throw EvalError with in try catch block as below javascript try throw new EvalError Eval function error someFile js catch e console log e message e name e fileName Eval function error EvalError someFile js Back to Top What are the list of cases error thrown from non strict mode to strict modeWhen you apply use strict syntax some of the below cases will throw a SyntaxError before executing the scriptWhen you use Octal syntaxjavascript var n Using with statementWhen you use delete operator on a variable nameUsing eval or arguments as variable or function argument nameWhen you use newly reserved keywordsWhen you declare a function in a blockjavascript if someCondition function f Hence the errors from above cases are helpful to avoid errors in development production environments Back to Top Is all objects have prototypesNo All objects have prototypes except for the base object which is created by the user or an object that is created using the new keyword Back to Top What is the difference between a parameter and an argumentParameter is the variable name of a function definition whereas an argument represents the value given to a function when it is invoked Let s explain this with a simple functionjavascript function myFunction parameter parameter parameter console log arguments argument console log arguments argument console log arguments argument myFunction argument argument argument Back to Top What is the purpose of some method in arraysThe some method is used to test whether at least one element in the array passes the test implemented by the provided function The method returns a boolean value Let s take an example to test for any odd elements javascript var array var odd element gt element console log array some odd true the odd element exists Back to Top How do you combine two or more arraysThe concat method is used to join two or more arrays by returning a new array containing all the elements The syntax would be as below javascript array concat array array arrayX Let s take an example of array s concatenation with veggies and fruits arrays javascript var veggies Tomato Carrot Cabbage var fruits Apple Orange Pears var veggiesAndFruits veggies concat fruits console log veggiesAndFruits Tomato Carrot Cabbage Apple Orange PearsBack to Top What is the difference between Shallow and Deep copyThere are two ways to copy an object Shallow Copy Shallow copy is a bitwise copy of an object A new object is created that has an exact copy of the values in the original object If any of the fields of the object are references to other objects just the reference addresses are copied i e only the memory address is copied Examplejavascript var empDetails name John age expertise Software Developer to create a duplicatejavascript var empDetailsShallowCopy empDetails Shallow copying if we change some property value in the duplicate one like this javascript empDetailsShallowCopy name Johnson The above statement will also change the name of empDetails since we have a shallow copy That means we re losing the original data as well Deep copy A deep copy copies all fields and makes copies of dynamically allocated memory pointed to by the fields A deep copy occurs when an object is copied along with the objects to which it refers Examplejavascript var empDetails name John age expertise Software Developer Create a deep copy by using the properties from the original object into new variablejavascript var empDetailsDeepCopy name empDetails name age empDetails age expertise empDetails expertise Now if you change empDetailsDeepCopy name it will only affect empDetailsDeepCopy amp not empDetailsBack to Top How do you create specific number of copies of a stringThe repeat method is used to construct and return a new string which contains the specified number of copies of the string on which it was called concatenated together Remember that this method has been added to the ECMAScript specification Let s take an example of Hello string to repeat it times javascript Hello repeat HelloHelloHelloHello How do you return all matching strings against a regular expressionThe matchAll method can be used to return an iterator of all results matching a string against a regular expression For example the below example returns an array of matching string results against a regular expression javascript let regexp Hello d g let greeting HelloHelloHello let greetingList greeting matchAll regexp console log greetingList Hello console log greetingList Hello console log greetingList HelloBack to Top How do you trim a string at the beginning or endingThe trim method of string prototype is used to trim on both sides of a string But if you want to trim especially at the beginning or ending of the string then you can use trimStart trimLeft and trimEnd trimRight methods Let s see an example of these methods on a greeting message javascript var greeting Hello Goodmorning console log greeting Hello Goodmorning console log greeting trimStart Hello Goodmorning console log greeting trimLeft Hello Goodmorning console log greeting trimEnd Hello Goodmorning console log greeting trimRight Hello Goodmorning Back to Top What is the output of below console statement with unary operatorLet s take console statement with unary operator as given below javascript console log Hello The output of the above console log statement returns NaN Because the element is prefixed by the unary operator and the JavaScript interpreter will try to convert that element into a number type Since the conversion fails the value of the statement results in NaN value Back to Top Does javascript uses mixinsBack to Top What is a thunk functionA thunk is just a function which delays the evaluation of the value It doesn t take any arguments but gives the value whenever you invoke the thunk i e It is used not to execute now but it will be sometime in the future Let s take a synchronous example javascript const add x y gt x y const thunk gt add thunk Back to Top What are asynchronous thunksThe asynchronous thunks are useful to make network requests Let s see an example of network requests javascript function fetchData fn fetch then response gt response json then json gt fn json const asyncThunk function return fetchData function getData data console log data asyncThunk The getData function won t be called immediately but it will be invoked only when the data is available from API endpoint The setTimeout function is also used to make our code asynchronous The best real time example is redux state management library which uses the asynchronous thunks to delay the actions to dispatch Back to Top What is the output of below function callsCode snippet javascript const circle radius diameter return this radius perimeter gt Math PI this radius console log circle diameter console log circle perimeter Output The output is and NaN Remember that diameter is a regular function whereas the value of perimeter is an arrow function The this keyword of a regular function i e diameter refers to the surrounding scope which is a class i e Shape object Whereas this keyword of perimeter function refers to the surrounding scope which is a window object Since there is no radius property on window objects it returns an undefined value and the multiple of number value returns NaN value Back to Top How to remove all line breaks from a stringThe easiest approach is using regular expressions to detect and replace newlines in the string In this case we use replace function along with string to replace with which in our case is an empty string javascript function remove linebreaks var message return message replace r n gm In the above expression g and m are for global and multiline flags Back to Top What is the difference between reflow and repaintA repaint occurs when changes are made which affect the visibility of an element but not its layout Examples of this include outline visibility or background color A reflow involves changes that affect the layout of a portion of the page or the whole page Resizing the browser window changing the font content changing such as user typing text using JavaScript methods involving computed styles adding or removing elements from the DOM and changing an element s classes are a few of the things that can trigger reflow Reflow of an element causes the subsequent reflow of all child and ancestor elements as well as any elements following it in the DOM Back to Top What happens with negating an arrayNegating an array with character will coerce the array into a boolean Since Arrays are considered to be truthy So negating it will return false javascript console log falseBack to Top What happens if we add two arraysIf you add two arrays together it will convert them both to strings and concatenate them For example the result of adding arrays would be as below javascript console log a b ab console log console log false because returns false Back to Top What is the output of prepend additive operator on falsy valuesIf you prepend the additive operator on falsy values null undefined NaN false the falsy value converts to a number value zero Let s display them on browser console as below javascript console log null console log undefined NaN console log false console log NaN NaN console log Back to Top How do you create self string using special charactersThe self string can be formed with the combination of characters You need to remember the below conventions to achieve this pattern Since Arrays are truthful values negating the arrays will produce false falseAs per JavaScript coercion rules the addition of arrays together will toString them Prepend an array with operator will convert an array to false the negation will make it true and finally converting the result will produce value By applying the above rules we can derive below conditionsjavascript false Now the character pattern would be created as below javascript s e l f Back to Top How do you remove falsy values from an arrayYou can apply the filter method on the array by passing Boolean as a parameter This way it removes all falsy values undefined null false and from the array javascript const myArray false null undefined myArray filter Boolean is same as myArray filter x gt x Back to Top How do you get unique values of an arrayYou can get unique values of an array with the combination of Set and rest expression spread syntax javascript console log new Set Back to Top What is destructuring aliasesSometimes you would like to have a destructured variable with a different name than the property name In that case you ll use a newName to specify a name for the variable This process is called destructuring aliases javascript const obj x Grabs obj x as as otherName const x otherName obj Back to Top How do you map the array values without using map methodYou can map the array values without using the map method by just using the from method of Array Let s map city names from Countries array javascript const countries name India capital Delhi name US capital Washington name Russia capital Moscow name Singapore capital Singapore name China capital Beijing name France capital Paris const cityNames Array from countries capital gt capital console log cityNames Delhi Washington Moscow Singapore Beijing Paris Back to Top How do you empty an arrayYou can empty an array quickly by setting the array length to zero javascript let cities Singapore Delhi London cities length cities becomes Back to Top How do you rounding numbers to certain decimalsYou can round numbers to a certain number of decimals using toFixed method from native javascript javascript let pie pie pie toFixed Back to Top What is the easiest way to convert an array to an objectYou can convert an array to an object with the same data using spread operator javascript var fruits banana apple orange watermelon var fruitsObject fruits console log fruitsObject banana apple orange watermelon Back to Top How do you create an array with some dataYou can create an array with some data or an array with the same values using fill method javascript var newArray new Array fill console log newArray Back to Top What are the placeholders from console objectBelow are the list of placeholders available from console object o ーIt takes an object s ーIt takes a string d ーIt is used for a decimal or integerThese placeholders can be represented in the console log as belowjavascript const user name John id city Delhi console log Hello s your details o are available in the object form John user Hello John your details name John id city Delhi are available in objectBack to Top Is it possible to add CSS to console messagesYes you can apply CSS styles to console messages similar to html text on the web page javascript console log c The text has blue color with large font and red background color blue font size x large background red The text will be displayed as below Note All CSS styles can be applied to console messages Back to Top What is the purpose of dir method of console objectThe console dir is used to display an interactive list of the properties of the specified JavaScript object as JSON javascript const user name John id city Delhi console dir user The user object displayed in JSON representation Back to Top Is it possible to debug HTML elements in consoleYes it is possible to get and debug HTML elements in the console just like inspecting elements javascript const element document getElementsByTagName body console log element It prints the HTML element in the console Back to Top How do you display data in a tabular format using console objectThe console table is used to display data in the console in a tabular format to visualize complex arrays or objects js const users name John id city Delhi name Max id city London name Rod id city Paris console table users The data visualized in a table format Not Remember that console table is not supported in IE Back to Top How do you verify that an argument is a Number or notThe combination of IsNaN and isFinite methods are used to confirm whether an argument is a number or not javascript function isNumber n return isNaN parseFloat n amp amp isFinite n Back to Top How do you create copy to clipboard buttonYou need to select the content using select method of the input element and execute the copy command with execCommand i e execCommand copy You can also execute other system commands like cut and paste javascript document querySelector copy button onclick function Select the content document querySelector copy input select Copy to the clipboard document execCommand copy Back to Top What is the shortcut to get timestampYou can use new Date getTime to get the current timestamp There is an alternative shortcut to get the value javascript console log new Date console log Date now Back to Top How do you flattening multi dimensional arraysFlattening bi dimensional arrays is trivial with Spread operator javascript const biDimensionalArr const flattenArr concat biDimensionalArr But you can make it work with multi dimensional arrays by recursive calls javascript function flattenMultiArray arr const flattened concat arr return flattened some item gt Array isArray item flattenMultiArray flattened flattened const multiDimensionalArr const flatArr flattenMultiArray multiDimensionalArr Back to Top What is the easiest multi condition checkingYou can use indexOf to compare input with multiple values instead of checking each value as one condition javascript Verbose approach if input first input input second input someFunction Shortcut if first second indexOf input someFunction Back to Top How do you capture browser back buttonThe window onbeforeunload method is used to capture browser back button events This is helpful to warn users about losing the current data javascript window onbeforeunload function alert You work will be lost Back to Top How do you disable right click in the web pageThe right click on the page can be disabled by returning false from the oncontextmenu attribute on the body element html lt body oncontextmenu return false gt Back to Top What are wrapper objectsPrimitive Values like string number and boolean don t have properties and methods but they are temporarily converted or coerced to an object Wrapper object when you try to perform actions on them For example if you apply toUpperCase method on a primitive string value it does not throw an error but returns uppercase of the string javascript let name john console log name toUpperCase Behind the scenes treated as console log new String name toUpperCase i e Every primitive except null and undefined have Wrapper Objects and the list of wrapper objects are String Number Boolean Symbol and BigInt Back to Top What is AJAXAJAX stands for Asynchronous JavaScript and XML and it is a group of related technologies HTML CSS JavaScript XMLHttpRequest API etc used to display data asynchronously i e We can send data to the server and get data from the server without reloading the web page Back to Top What are the different ways to deal with Asynchronous CodeBelow are the list of different ways to deal with Asynchronous code CallbacksPromisesAsync awaitThird party libraries such as async js bluebird etcBack to Top How to cancel a fetch requestUntil a few days back One shortcoming of native promises is no direct way to cancel a fetch request But the new AbortController from js specification allows you to use a signal to abort one or multiple fetch calls The basic flow of cancelling a fetch request would be as below Create an AbortController instanceGet the signal property of an instance and pass the signal as a fetch option for signalCall the AbortController s abort property to cancel all fetches that use that signalFor example let s pass the same signal to multiple fetch calls will cancel all requests with that signal javascript const controller new AbortController const signal controller fetch http localhost signal then response gt console log Request is complete catch e gt if e name AbortError We know it s been canceled fetch http localhost signal then response gt console log Request is complete catch e gt if e name AbortError We know it s been canceled Wait seconds to abort both requests setTimeout gt controller abort Back to Top What is web speech APIWeb speech API is used to enable modern browsers recognize and synthesize speech i e voice data into web apps This API has been introduced by WC Community in the year It has two main parts SpeechRecognition Asynchronous Speech Recognition or Speech to Text It provides the ability to recognize voice context from an audio input and respond accordingly This is accessed by the SpeechRecognition interface The below example shows on how to use this API to get text from speech javascript window SpeechRecognition window webkitSpeechRecognition window SpeechRecognition webkitSpeechRecognition for Chrome and SpeechRecognition for FF const recognition new window SpeechRecognition recognition onresult event gt SpeechRecognitionEvent type const speechToText event results transcript console log speechToText recognition start In this API browser is going to ask you for permission to use your microphoneSpeechSynthesis Text to Speech It provides the ability to recognize voice context from an audio input and respond This is accessed by the SpeechSynthesis interface For example the below code is used to get voice speech from text javascript if speechSynthesis in window var speech new SpeechSynthesisUtterance Hello World speech lang en US window speechSynthesis speak speech The above examples can be tested on chrome browser s developer console Note This API is still a working draft and only available in Chrome and Firefox browsers ofcourse Chrome only implemented the specification Back to Top What is minimum timeout throttlingBoth browser and NodeJS javascript environments throttles with a minimum delay that is greater than ms That means even though setting a delay of ms will not happen instantaneously Browsers They have a minimum delay of ms This throttle occurs when successive calls are triggered due to callback nesting certain depth or after a certain number of successive intervals Note The older browsers have a minimum delay of ms Nodejs They have a minimum delay of ms This throttle happens when the delay is larger than or less than The best example to explain this timeout throttling behavior is the order of below code snippet javascript function runMeFirst console log My script is initialized setTimeout runMeFirst console log Script loaded and the output would be incmd Script loaded My script is initializedIf you don t use setTimeout the order of logs will be sequential javascript function runMeFirst console log My script is initialized runMeFirst console log Script loaded and the output is cmd My script is initialized Script loadedBack to Top How do you implement zero timeout in modern browsersYou can t use setTimeout fn to execute the code immediately due to minimum delay of greater than ms But you can use window postMessage to achieve this behavior Back to Top What are tasks in event loopA task is any javascript code program which is scheduled to be run by the standard mechanisms such as initially starting to run a program run an event callback or an interval or timeout being fired All these tasks are scheduled on a task queue Below are the list of use cases to add tasks to the task queue When a new javascript program is executed directly from console or running by the lt script gt element the task will be added to the task queue When an event fires the event callback added to task queueWhen a setTimeout or setInterval is reached the corresponding callback added to task queueBack to Top What is microtaskMicrotask is the javascript code which needs to be executed immediately after the currently executing task microtask is completed They are kind of blocking in nature i e The main thread will be blocked until the microtask queue is empty The main sources of microtasks are Promise resolve Promise reject MutationObservers IntersectionObservers etcNote All of these microtasks are processed in the same turn of the event loop Back to Top What are different event loopsBack to Top What is the purpose of queueMicrotaskBack to Top How do you use javascript libraries in typescript fileIt is known that not all JavaScript libraries or frameworks have TypeScript declaration files But if you still want to use libraries or frameworks in our TypeScript files without getting compilation errors the only solution is declare keyword along with a variable declaration For example let s imagine you have a library called customLibrary that doesn t have a TypeScript declaration and have a namespace called customLibrary in the global namespace You can use this library in typescript code as below javascript declare var customLibrary In the runtime typescript will provide the type to the customLibrary variable as any type The another alternative without using declare keyword is belowjavascript var customLibrary any Back to Top What are the differences between promises and observablesSome of the major difference in a tabular form Promises Observables Emits only a single value at a time Emits multiple values over a period of time stream of values ranging from to multiple Eager in nature they are going to be called immediately Lazy in nature they require subscription to be invoked Promise is always asynchronous even though it resolved immediately Observable can be either synchronous or asynchronous Doesn t provide any operators Provides operators such as map forEach filter reduce retry and retryWhen etc Cannot be canceled Canceled by using unsubscribe method Back to Top What is heapHeap Or memory heap is the memory location where objects are stored when we define variables i e This is the place where all the memory allocations and de allocation take place Both heap and call stack are two containers of JS runtime Whenever runtime comes across variables and function declarations in the code it stores them in the Heap Back to Top What is an event tableEvent Table is a data structure that stores and keeps track of all the events which will be executed asynchronously like after some time interval or after the resolution of some API requests i e Whenever you call a setTimeout function or invoke async operation it is added to the Event Table It doesn t not execute functions on it s own The main purpose of the event table is to keep track of events and send them to the Event Queue as shown in the below diagram Back to Top What is a microTask queueMicrotask Queue is the new queue where all the tasks initiated by promise objects get processed before the callback queue The microtasks queue are processed before the next rendering and painting jobs But if these microtasks are running for a long time then it leads to visual degradation Back to Top What is the difference between shim and polyfillA shim is a library that brings a new API to an older environment using only the means of that environment It isn t necessarily restricted to a web application For example es shim js is used to emulate ES features on older browsers mainly pre IE Whereas polyfill is a piece of code or plugin that provides the technology that you the developer expect the browser to provide natively In a simple sentence A polyfill is a shim for a browser API Back to Top How do you detect primitive or non primitive value typeIn JavaScript primitive types include boolean string number BigInt null Symbol and undefined Whereas non primitive types include the Objects But you can easily identify them with the below function javascript var myPrimitive var myNonPrimitive function isPrimitive val return Object val val isPrimitive myPrimitive isPrimitive myNonPrimitive If the value is a primitive data type the Object constructor creates a new wrapper object for the value But If the value is a non primitive data type an object the Object constructor will give the same object Back to Top What is babelBabel is a JavaScript transpiler to convert ECMAScript code into a backwards compatible version of JavaScript in current and older browsers or environments Some of the main features are listed below Transform syntaxPolyfill features that are missing in your target environment using babel polyfill Source code transformations or codemods Back to Top Is Node js completely single threadedNode is a single thread but some of the functions included in the Node js standard library e g fs module functions are not single threaded i e Their logic runs outside of the Node js single thread to improve the speed and performance of a program Back to Top What are the common use cases of observablesSome of the most common use cases of observables are web sockets with push notifications user input changes repeating intervals etcBack to Top What is RxJSRxJS Reactive Extensions for JavaScript is a library for implementing reactive programming using observables that makes it easier to compose asynchronous or callback based code It also provides utility functions for creating and working with observables Back to Top What is the difference between Function constructor and function declarationThe functions which are created with Function constructor do not create closures to their creation contexts but they are always created in the global scope i e the function can access its own local variables and global scope variables only Whereas function declarations can access outer function variables closures too Let s see this difference with an example Function Constructor javascript var a function createFunction var a return new Function return a console log createFunction Function declaration javascript var a function createFunction var a return function func return a console log createFunction Back to Top What is a Short circuit conditionShort circuit conditions are meant for condensed way of writing simple if statements Let s demonstrate the scenario using an example If you would like to login to a portal with an authentication condition the expression would be as below javascript if authenticate loginToPorta Since the javascript logical operators evaluated from left to right the above expression can be simplified using amp amp logical operatorjavascript authenticate amp amp loginToPorta Back to Top What is the easiest way to resize an arrayThe length property of an array is useful to resize or empty an array quickly Let s apply length property on number array to resize the number of elements from to javascript var array console log array length array length console log array length console log array and the array can be emptied toojavascript var array array length console log array length console log array Back to Top What is an observableAn Observable is basically a function that can return a stream of values either synchronously or asynchronously to an observer over time The consumer can get the value by calling subscribe method Let s look at a simple example of an Observablejavascript import Observable from rxjs const observable new Observable observer gt setTimeout gt observer next Message from a Observable observable subscribe value gt console log value Note Observables are not part of the JavaScript language yet but they are being proposed to be added to the languageBack to Top What is the difference between function and class declarationsThe main difference between function declarations and class declarations is hoisting The function declarations are hoisted but not class declarations Classes javascript const user new User ReferenceError class User Constructor Function javascript const user new User No error function User Back to Top What is an async functionAn async function is a function declared with the async keyword which enables asynchronous promise based behavior to be written in a cleaner style by avoiding promise chains These functions can contain zero or more await expressions Let s take a below async function example javascript async function logger let data await fetch pause until fetch returns console log data logger It is basically syntax sugar over ES promises and generators Back to Top How do you prevent promises swallowing errorsWhile using asynchronous code JavaScript s ES promises can make your life a lot easier without having callback pyramids and error handling on every second line But Promises have some pitfalls and the biggest one is swallowing errors by default Let s say you expect to print an error to the console for all the below cases javascript Promise resolve promised value then function throw new Error error Promise reject error value catch function throw new Error error new Promise function resolve reject throw new Error error But there are many modern JavaScript environments that won t print any errors You can fix this problem in different ways Add catch block at the end of each chain You can add catch block to the end of each of your promise chainsjavascript Promise resolve promised value then function throw new Error error catch function error console error error stack But it is quite difficult to type for each promise chain and verbose too Add done method You can replace first solution s then and catch blocks with done methodjavascript Promise resolve promised value done function throw new Error error Let s say you want to fetch data using HTTP and later perform processing on the resulting data asynchronously You can write done block as below javascript getDataFromHttp then function result return processDataAsync result done function processed displayData processed In future if the processing library API changed to synchronous then you can remove done block as below javascript getDataFromHttp then function result return displayData processDataAsync result and then you forgot to add done block to then block leads to silent errors Extend ES Promises by Bluebird Bluebird extends the ES Promises API to avoid the issue in the second solution This library has a “default onRejection handler which will print all errors from rejected Promises to stderr After installation you can process unhandled rejectionsjavascript Promise onPossiblyUnhandledRejection function error throw error and discard a rejection just handle it with an empty catchjavascript Promise reject error value catch function Back to Top What is denoDeno is a simple modern and secure runtime for JavaScript and TypeScript that uses V JavaScript engine and the Rust programming language Back to Top How do you make an object iterable in javascriptBy default plain objects are not iterable But you can make the object iterable by defining a Symbol iterator property on it Let s demonstrate this with an example javascript const collection one two three Symbol iterator const values Object keys this let i return next gt return value this values i done i gt values length const iterator collection Symbol iterator console log iterator next → value done false console log iterator next → value done false console log iterator next → value done false console log iterator next → value undefined done true The above process can be simplified using a generator function javascript const collection one two three Symbol iterator function for let key in this yield this key const iterator collection Symbol iterator console log iterator next value done false console log iterator next value done false console log iterator next value done false console log iterator next value undefined done true Back to Top What is a Proper Tail CallFirst we should know about tail call before talking about Proper Tail Call A tail call is a subroutine or function call performed as the final action of a calling function Whereas Proper tail call PTC is a technique where the program or code will not create additional stack frames for a recursion when the function call is a tail call For example the below classic or head recursion of factorial function relies on stack for each step Each step need to be processed upto n factorial n javascript function factorial n if n return return n factorial n console log factorial But if you use Tail recursion functions they keep passing all the necessary data it needs down the recursion without relying on the stack javascript function factorial n acc if n return acc return factorial n n acc console log factorial The above pattern returns the same output as the first one But the accumulator keeps track of total as an argument without using stack memory on recursive calls Back to Top How do you check an object is a promise or notIf you don t know if a value is a promise or not wrapping the value as Promise resolve value which returns a promisejavascript function isPromise object if Promise amp amp Promise resolve return Promise resolve object object else throw Promise not supported in your environment var i var promise new Promise function resolve reject resolve console log isPromise i false console log isPromise p trueAnother way is to check for then handler typejavascript function isPromise value return Boolean value amp amp typeof value then function var i var promise new Promise function resolve reject resolve console log isPromise i false console log isPromise promise trueBack to Top How to detect if a function is called as constructorYou can use new target pseudo property to detect whether a function was called as a constructor using the new operator or as a regular function call If a constructor or function invoked using the new operator new target returns a reference to the constructor or function For function calls new target is undefined javascript function Myfunc if new target console log called with new else console log not called with new new Myfunc called with new Myfunc not called with new Myfunc call not called with newBack to Top What are the differences between arguments object and rest parameterThere are three main differences between arguments object and rest parametersThe arguments object is an array like but not an array Whereas the rest parameters are array instances The arguments object does not support methods such as sort map forEach or pop Whereas these methods can be used in rest parameters The rest parameters are only the ones that haven t been given a separate name while the arguments object contains all arguments passed to the functionBack to Top What are the differences between spread operator and rest parameterRest parameter collects all remaining elements into an array Whereas Spread operator allows iterables arrays objects strings to be expanded into single arguments elements i e Rest parameter is opposite to the spread operator Back to Top What are the different kinds of generatorsThere are five kinds of generators Generator function declaration javascript function myGenFunc yield yield yield const genObj myGenFunc Generator function expressions javascriptconst myGenFunc function yield yield yield const genObj myGenFunc Generator method definitions in object literals javascript const myObj myGeneratorMethod yield yield yield const genObj myObj myGeneratorMethod Generator method definitions in class javascript class MyClass myGeneratorMethod yield yield yield const myObject new MyClass const genObj myObject myGeneratorMethod Generator as a computed property javascriptconst SomeObj Symbol iterator yield yield yield console log Array from SomeObj Back to Top What are the built in iterablesBelow are the list of built in iterables in javascript Arrays and TypedArraysStrings Iterate over each character or Unicode code pointsMaps iterate over its key value pairsSets iterates over their elementsarguments An array like special variable in functionsDOM collection such as NodeListBack to Top What are the differences between for of and for in statementsBoth for in and for of statements iterate over js data structures The only difference is over what they iterate for in iterates over all enumerable property keys of an objectfor of iterates over the values of an iterable object Let s explain this difference with an example javascript let arr a b c arr newProp newVlue key are the property keys for let key in arr console log key value are the property values for let value of arr console log value Since for in loop iterates over the keys of the object the first loop logs and newProp while iterating over the array object The for of loop iterates over the values of a arr data structure and logs a b c in the console Back to Top How do you define instance and non instance propertiesThe Instance properties must be defined inside of class methods For example name and age properties defined insider constructor as below javascript class Person constructor name age this name name this age age But Static class and prototype data properties must be defined outside of the ClassBody declaration Let s assign the age value for Person class as below javascript Person staticAge Person prototype prototypeAge Back to Top What is the difference between isNaN and Number isNaN isNaN The global function isNaN converts the argument to a Number and returns true if the resulting value is NaN Number isNaN This method does not convert the argument But it returns true when the type is a Number and value is NaN Let s see the difference with an example javascript isNaN hello true Number isNaN hello falseBack to Top How to invoke an IIFE without any extra brackets Immediately Invoked Function Expressions IIFE requires a pair of parenthesis to wrap the function which contains set of statements js function dt console log dt toLocaleTimeString new Date Since both IIFE and void operator discard the result of an expression you can avoid the extra brackets using void operator for IIFE as below js void function dt console log dt toLocaleTimeString new Date Back to Top Is that possible to use expressions in switch cases You might have seen expressions used in switch condition but it is also possible to use for switch cases by assigning true value for the switch condition Let s see the weather condition based on temparature as an example js const weather function getWeather temp switch true case temp lt return freezing case temp lt return cold case temp lt return cool default return unknown Back to Top What is the easiest way to ignore promise errors The easiest and safest way to ignore promise errors is void that error This approach is ESLint friendly too js await promise catch e gt void e Back to Top How do style the console output using CSS You can add CSS styling to the console output using the CSS format content specifier c The console string message can be appended after the specifier and CSS style in another argument Let s print the red the color text using console log and CSS specifier as below js console log cThis is a red text color red It is also possible to add more styles for the content For example the font size can be modified for the above textjs console log cThis is a red text with bigger font color red font size px Back to Top Coding Exercise What is the output of below codejavascriptvar car new Vehicle Honda white UK console log car function Vehicle model color year country this model model this color color this year year this country country Undefined ReferenceError null model Honda color white year country UK Answer Answer The function declarations are hoisted similar to any variables So the placement for Vehicle function declaration doesn t make any difference Back to Top What is the output of below codejavascriptfunction foo let x y x y return x console log foo typeof x typeof y undefined and undefined ReferenceError X is not defined undefined and number number and numberAnswer Answer Of course the return value of foo is due to the increment operator But the statement let x y declares a local variable x Whereas y declared as a global variable accidentally This statement is equivalent to javascript let x window y x window y Since the block scoped variable x is undefined outside of the function the type will be undefined too Whereas the global variable y is available outside the function the value is and type is number Back to Top What is the output of below codejavascriptfunction main console log A setTimeout function print console log B console log C main A B and C B A and C A and C A C and BAnswer Answer The statements order is based on the event loop mechanism The order of statements follows the below order At first the main function is pushed to the stack Then the browser pushes the fist statement of the main function i e A s console log to the stack executing and popping out immediately But setTimeout statement moved to Browser API to apply the delay for callback In the meantime C s console log added to stack executed and popped out The callback of setTimeout moved from Browser API to message queue The main function popped out from stack because there are no statements to execute The callback moved from message queue to the stack since the stack is empty The console log for B is added to the stack and display on the console Back to Top What is the output of below equality checkjavascriptconsole log false trueAnswer Answer This is due to the float point math problem Since the floating point numbers are encoded in binary format the addition operations on them lead to rounding errors Hence the comparison of floating points doesn t give expected results You can find more details about the explanation here com Back to Top What is the output of below codejavascriptvar y if function f y typeof f console log y function object ReferenceError undefinedAnswer Answer The main points in the above code snippets are You can see function expression instead function declaration inside if statement So it always returns true Since it is not declared or assigned anywhere f is undefined and typeof f is undefined too In other words it is same as javascriptvar y if foo y typeof f console log y Note It returns object for MS Edge browserBack to Top What is the output of below codejavascriptfunction foo return message Hello World console log foo Hello World Object message Hello World Undefined SyntaxErrorAnswer Answer This is a semicolon issue Normally semicolons are optional in JavaScript So if there are any statements in this case return missing semicolon it is automatically inserted immediately Hence the function returned as undefined Whereas if the opening curly brace is along with the return keyword then the function is going to be returned as expected javascriptfunction foo return message Hello World console log foo message Hello World Back to Top What is the output of below codejavascriptvar myChars a b c d delete myChars console log myChars console log myChars console log myChars length empty b c d empty null b c d empty empty b c d undefined null b c d undefined Answer Answer The delete operator will delete the object property but it will not reindex the array or change its length So the number or elements or length of the array won t be changed If you try to print myChars then you can observe that it doesn t set an undefined value rather the property is removed from the array The newer versions of Chrome use empty instead of undefined to make the difference a bit clearer Back to Top What is the output of below code in latest Chromejavascriptvar array new Array console log array var array array console log array var array console log array undefined × undefined × undefined × empty × empty × empty × null × null × null × Answer Answer The latest chrome versions display sparse array they are filled with holes using this empty x n notation Whereas the older versions have undefined x n notation Note The latest version of FF displays n empty slots notation Back to Top What is the output of below codejavascriptconst obj prop function return prop return prop return console log obj prop console log obj prop console log obj prop return return return undefinedAnswer Answer ES provides method definitions and property shorthands for objects So both prop and prop are treated as regular function values Back to Top What is the output of below codejavascriptconsole log lt lt console log gt gt true true true false SyntaxError SyntaxError false falseAnswer Answer The important point is that if the statement contains the same operators e g lt or gt then it can be evaluated from left to right The first statement follows the below order console log lt lt console log true lt console log lt True converted as during comparison TrueWhereas the second statement follows the below order console log gt gt console log true gt console log gt False converted as during comparison FalseBack to Top What is the output of below code in non strict modejavascriptfunction printNumbers first second first console log first second first printNumbers SyntaxError Duplicate parameter name not allowed in this context Answer Answer In non strict mode the regular JavaScript functions allow duplicate named parameters The above code snippet has duplicate parameters on st and rd parameters The value of the first parameter is mapped to the third argument which is passed to the function Hence the rd argument overrides the first parameter Note In strict mode duplicate parameters will throw a Syntax Error Back to Top What is the output of below codejavascriptconst printNumbersArrow first second first gt console log first second first printNumbersArrow SyntaxError Duplicate parameter name not allowed in this context Answer Answer Unlike regular functions the arrow functions doesn t not allow duplicate parameters in either strict or non strict mode So you can see SyntaxError in the console Back to Top What is the output of below codejavascriptconst arrowFunc gt arguments length console log arrowFunc ReferenceError arguments is not defined undefined nullAnswer Answer Arrow functions do not have an arguments super this or new target bindings So any reference to arguments variable tries to resolve to a binding in a lexically enclosing environment In this case the arguments variable is not defined outside of the arrow function Hence you will receive a reference error Where as the normal function provides the number of arguments passed to the function javascriptconst func function return arguments length console log func But If you still want to use an arrow function then rest operator on arguments provides the expected arguments javascriptconst arrowFunc args gt args length console log arrowFunc Back to Top What is the output of below codejavascriptconsole log String prototype trimLeft name trimLeft console log String prototype trimLeft name trimStart True False False TrueAnswer Answer In order to be consistent with functions like String prototype padStart the standard method name for trimming the whitespaces is considered as trimStart Due to web web compatibility reasons the old method name trimLeft still acts as an alias for trimStart Hence the prototype for trimLeft is always trimStart Back to Top What is the output of below codejavascriptconsole log Math max undefined Infinity InfinityAnswer Answer Infinity is the initial comparant because almost every other value is bigger So when no arguments are provided Infinity is going to be returned Note Zero number of arguments is a valid case Back to Top What is the output of below codejavascriptconsole log console log True True True False False False False TrueAnswer Answer As per the comparison algorithm in the ECMAScript specification ECMA the above expression converted into JS as below javascript Number valueOf toString So it doesn t matter about number brackets around the number it is always converted to a number in the expression Back to Top What is the output of below codejavascriptconsole log console log NaN NaNAnswer Answer The concatenation operator is applicable for both number and string types So if any operand is string type then both operands concatenated as strings Whereas subtract operator tries to convert the operands as number type Back to Top What is the output of below codejavascriptconsole log false if console log I m True else console log I m False True I m True True I m False False I m True False I m FalseAnswer Answer In comparison operators the expression converted to Number valueOf toString which is resolved to false Whereas just becomes a truthy value without any conversion because there is no comparison operator What is the output of below codejavascriptconsole log SyntaxError Answer Answer The operator is not meant or defined for arrays So it converts arrays into strings and concatenates them Back to Top What is the output of below codejavascriptconst numbers new Set console log numbers const browser new Set Firefox console log browser F i r e f o x F i r e o x F i r e o x F i r e f o x Answer Answer Since Set object is a collection of unique values it won t allow duplicate values in the collection At the same time it is case sensitive data structure Back to Top What is the output of below codejavascriptconsole log NaN NaN True FalseAnswer Answer JavaScript follows IEEE spec standards As per this spec NaNs are never equal for floating point numbers Back to Top What is the output of below codejavascriptlet numbers NaN console log numbers indexOf NaN NaN SyntaxError Answer Answer The indexOf uses strict equality operator internally and NaN NaN evaluates to false Since indexOf won t be able to find NaN inside an array it returns always But you can use Array prototype findIndex method to find out the index of NaN in an array or You can use Array prototype includes to check if NaN is present in an array or not javascriptlet numbers NaN console log numbers findIndex Number isNaN console log numbers includes Number isNaN true Back to Top What is the output of below codejavascriptlet a b console log a b SyntaxError Answer Answer When using rest parameters trailing commas are not allowed and will throw a SyntaxError If you remove the trailing comma then it displays st answer javascriptlet a b console log a b Back to Top What is the output of below codejavascriptasync function func return console log func Promise lt fulfilled gt SyntaxError Promise lt rejected gt Answer Answer Async functions always return a promise But even if the return value of an async function is not explicitly a promise it will be implicitly wrapped in a promise The above async function is equivalent to below expression javascriptfunction func return Promise resolve Back to Top What is the output of below codejavascriptasync function func await console log func Promise lt fulfilled gt SyntaxError Promise lt resolved gt undefined Answer Answer The await expression returns value with promise resolution and the code after each await expression can be treated as existing in a then callback In this case there is no return expression at the end of the function Hence the default return value of undefined is returned as the resolution of the promise The above async function is equivalent to below expression javascriptfunction func return Promise resolve then gt undefined Back to Top What is the output of below codejavascriptfunction delay return new Promise resolve gt setTimeout resolve async function delayedLog item await delay console log item async function processArray array array forEach item gt await delayedLog item processArray SyntaxError Answer Answer Even though “processArray is an async function the anonymous function that we use for forEach is synchronous If you use await inside a synchronous function then it throws a syntax error Back to Top What is the output of below codejavascriptfunction delay return new Promise resolve gt setTimeout resolve async function delayedLog item await delay console log item async function process array array forEach async item gt await delayedLog item console log Process completed process and Process completed and Process completed Process completed and Process completed and Answer Answer The forEach method will not wait until all items are finished but it just runs the tasks and goes next Hence the last statement is displayed first followed by a sequence of promise resolutions But you control the array sequence using for of loop javascriptasync function processArray array for const item of array await delayedLog item console log Process completed Back to Top What is the output of below codejavascriptvar set new Set set add add add NaN add undefined add NaN console log set Set NaN undefined Set NaN undefined Set NaN undefined NaN Set NaN undefined NaN Answer Answer Set has few exceptions from equality check All NaN values are equal Both and considered as different valuesBack to Top What is the output of below codejavascriptconst sym Symbol one const sym Symbol one const sym Symbol for two const sym Symbol for two cnsooe log sym sym sym sym true true true false false true false falseAnswer Answer Symbol follows below conventions Every symbol value returned from Symbol is unique irrespective of the optional string Symbol for function creates a symbol in a global symbol registry list But it doesn t necessarily create a new symbol on every call it checks first if a symbol with the given key is already present in the registry and returns the symbol if it is found Otherwise a new symbol created in the registry Note The symbol description is just useful for debugging purposes Back to Top What is the output of below codejavascriptconst sym new Symbol one console log sym SyntaxError one Symbol one SymbolAnswer Answer Symbol is a just a standard function and not an object constructor unlike other primitives new Boolean new String and new Number So if you try to call it with the new operator will result in a TypeErrorBack to Top What is the output of below codejavascriptlet myNumber let myString if typeof myNumber string console log It is not a string else console log It is a string if typeof myString number console log It is not a number else console log It is a number SyntaxError It is not a string It is not a number It is not a string It is a number It is a string It is a number Answer Answer The return value of typeof myNumber OR typeof myString is always the truthy value either number or string Since operator converts the value to a boolean value the value of both typeof myNumber or typeof myString is always false Hence the if condition fails and control goes to else block Back to Top What is the output of below codejavascriptconsole log JSON stringify myArray one undefined function Symbol console log JSON stringify Symbol for one one Symbol for one myArray one undefined Symbol myArray one null null null myArray one null null null Symbol for one one Symbol for one myArray one undefined function Symbol Answer Answer The symbols has below constraints The undefined Functions and Symbols are not valid JSON values So those values are either omitted in an object or changed to null in an array Hence it returns null values for the value array All Symbol keyed properties will be completely ignored Hence it returns an empty object Back to Top What is the output of below codejavascriptclass A constructor console log new target name class B extends A constructor super new A new B A A A BAnswer Answer Using constructors new target refers to the constructor points to the class definition of class which is initialized that was directly invoked by new This also applies to the case if the constructor is in a parent class and was delegated from a child constructor Back to Top What is the output of below codejavascriptconst x y console log x y SyntaxErrorAnswer Answer It throws a syntax error because the rest element should not have a trailing comma You should always consider using a rest operator as the last element Back to Top What is the output of below codejavascriptconst a x b y a console log x console log y undefined undefinedAnswer Answer The object property follows below rules The object properties can be retrieved and assigned to a variable with a different name The property assigned a default value when the retrieved value is undefined Back to Top What is the output of below codejavascriptfunction area length width console log length width area Error undefined Answer Answer If you leave out the right hand side assignment for the destructuring object the function will look for at least one argument to be supplied when invoked Otherwise you will receive an error Error Cannot read property length of undefined as mentioned above You can avoid the error with either of the below changes Pass at least an empty object javascriptfunction area length width console log length width area Assign default empty object javascriptfunction area length width console log length width area Back to Top What is the output of below codejavascriptconst props id name John id name Jack id name Tom const name props console log name Tom Error undefined JohnAnswer Answer It is possible to combine Array and Object destructuring In this case the third element in the array props accessed first followed by name property in the object Back to Top What is the output of below codejavascriptfunction checkType num console log typeof num checkType checkType undefined checkType checkType null number undefined string object undefined undefined string object number number string object number number number numberAnswer Answer If the function argument is set implicitly not passing argument or explicitly to undefined the value of the argument is the default parameter Whereas for other falsy values or null the value of the argument is passed as a parameter Hence the result of function calls categorized as below The first two function calls logs number type since the type of default value is number The type of and null values are string and object type respectively Back to Top What is the output of below codejavascriptfunction add item items items push item return items console log add Orange console log add Apple Orange Orange Apple Orange Apple Answer Answer Since the default argument is evaluated at call time a new object is created each time the function is called So in this case the new array is created and an element pushed to the default empty array Back to Top What is the output of below codejavascriptfunction greet greeting name message greeting name console log greeting name message greet Hello John greet Hello John Good morning SyntaxError Hello John Hello John Hello John Good morning Answer Answer Since parameters defined earlier are available to later default parameters this code snippet doesn t throw any error Back to Top What is the output of below codejavascriptfunction outer f inner function inner return Inner outer ReferenceError InnerAnswer Answer The functions and variables declared in the function body cannot be referred from default value parameter initializers If you still try to access it throws a run time ReferenceError i e inner is not defined Back to Top What is the output of below codejavascriptfunction myFun x y manyMoreArgs console log manyMoreArgs myFun myFun undefined SyntaxError undefined Answer Answer The rest parameter is used to hold the remaining parameters of a function and it becomes an empty array if the argument is not provided Back to Top What is the output of below codejavascriptconst obj key value const array obj console log array key value TypeError key Answer Answer Spread syntax can be applied only to iterable objects By default Objects are not iterable but they become iterable when used in an Array or with iterating functions such as map reduce and assign If you still try to do it it still throws TypeError obj is not iterable Back to Top What is the output of below codejavascriptfunction myGenFunc yield yield yield var myGenObj new myGenFunc console log myGenObj next value undefined SyntaxError TypeErrorAnswer Answer Generators are not constructible type But if you still proceed to do there will be an error saying TypeError myGenFunc is not a constructor Back to Top What is the output of below codejavascriptfunction yieldAndReturn yield return yield var myGenObj yieldAndReturn console log myGenObj next console log myGenObj next console log myGenObj next value done false value done true value undefined done true value done false value done false value undefined done true value done false value done true value done true value done false value done false value done true Answer Answer A return statement in a generator function will make the generator finish If a value is returned it will be set as the value property of the object and done property to true When a generator is finished subsequent next calls return an object of this form value undefined done true Back to Top What is the output of below codejavascriptconst myGenerator function yield yield yield for const value of myGenerator console log value break for const value of myGenerator console log value and and and Answer Answer The generator should not be re used once the iterator is closed i e Upon exiting a loop on completion or using break amp return the generator is closed and trying to iterate over it again does not yield any more results Hence the second loop doesn t print any value Back to Top What is the output of below codejavascriptconst num o console log num SyntaxError Answer Answer If you use an invalid number outside of range in the octal literal JavaScript will throw a SyntaxError In ES it treats the octal literal as a decimal number Back to Top What is the output of below codejavascriptconst squareObj new Square console log squareObj area class Square constructor length this length length get area return this length this length set area value this area value ReferenceErrorAnswer Answer Unlike function declarations class declarations are not hoisted i e First You need to declare your class and then access it otherwise it will throw a ReferenceError Uncaught ReferenceError Square is not defined Note Class expressions also applies to the same hoisting restrictions of class declarations Back to Top What is the output of below codejavascriptfunction Person Person prototype walk function return this Person run function return this let user new Person let walk user walk console log walk let run Person run console log run undefined undefined Person Person SyntaxError Window WindowAnswer Answer When a regular or prototype method is called without a value for this the methods return an initial this value if the value is not undefined Otherwise global window object will be returned In our case the initial this value is undefined so both methods return window objects Back to Top What is the output of below codejavascriptclass Vehicle constructor name this name name start console log this name vehicle started class Car extends Vehicle start console log this name car started super start const car new Car BMW console log car start SyntaxError BMW vehicle started BMW car started BMW car started BMW vehicle started BMW car started BMW car startedAnswer Answer The super keyword is used to call methods of a superclass Unlike other languages the super invocation doesn t need to be a first statement i e The statements will be executed in the same order of code Back to Top What is the output of below codejavascriptconst USER age USER age console log USER age Uncaught TypeError SyntaxErrorAnswer Answer Even though we used constant variables the content of it is an object and the object s contents e g properties can be altered Hence the change is going to be valid in this case Back to Top What is the output of below codejavascriptconsole log false trueAnswer Answer Emojis are unicodes and the unicode for smile symbol is U F The unicode comparision of same emojies is equivalent to string comparison Hence the output is always true Back to Top What is the output of below code javascriptconsole log typeof typeof typeof true string boolean NaN numberAnswer Answer The typeof operator on any primitive returns a string value So even if you apply the chain of typeof operators on the return value it is always string Back to Top What is the output of below code javascriptlet zero new Number if zero console log If else console log Else If Else NaN SyntaxErrorAnswer Answer The type of operator on new Number always returns object i e typeof new Number gt object Objects are always truthy in if blockHence the above code block always goes to if section Back to Top What is the output of below code in non strict mode javascriptlet msg Good morning msg name John console log msg name Error John UndefinedAnswer Answer It returns undefined for non strict mode and returns Error for strict mode In non strict mode the wrapper object is going to be created and get the mentioned property But the object get disappeared after accessing the property in next line Back to Top What is the output of below code javascriptlet count function innerFunc if count let count console log count console log count Answer Answer and is logged to the console The innerFunc is a closure which captures the count variable from the outerscope i e But the conditional has another local variable count which overwrites the ourter count variable So the first console log displays value Whereas the second console log logs by capturing the count variable from outerscope Back to TopRead also Projects ideas to become a javascript master Resource compilation Giveaway DevLorenzo・Apr ・ min read javascript webdev programming beginners Finally How to understand math Awesome resource list DevLorenzo・Mar ・ min read productivity webdev beginners javascript Udemy Courses Worth Your Money amp Time Garvit Motwani・Apr ・ min read webdev beginners productivity javascript Thanks for reading and Happy coding Full Compilation of cheat sheets The ultimate Cheat sheets compilation Roadmap to dev DevLorenzo・Mar ・ min read productivity webdev beginners javascript Giveaway We are giving away any course you need on Udemy Any price any course Steps to enter the giveaway gt React to this post gt Subscribe to our Newsletter lt Very important gt Follow me on Twitter lt x Chances of winning 2021-04-27 12:28:24
海外TECH DEV Community Tratamento de Exceção com erros customizados em Swift https://dev.to/reisdev/tratamento-de-excecao-com-erros-customizados-em-swift-403b Tratamento de Exceção com erros customizados em SwiftCapa por Sigmund no UnsplashUtilizar erros customizados pode deixar seu código mais compreensível e organizado pois adiciona uma descrição para determinadas situações que podem ocorrer No artigo de hoje vamos ver como criar e tratar erros customizados na linguagem Swift SumárioCriaçãoTratamento de ExceçãoConsiderações CriaçãoPrimeiro precisamos pensar em um contexto para criar nossos erros Vamos supor que existe um serviço que consome uma API que fornece dados sobre filmes e iremos tratar os possíveis erros Os erros mais comuns são Recurso não encontrado Proibido Erro interno Serviço Indisponível Os números associados aos erros são conhecidos como Código de Status HTTP HTTP Status Code No trecho de código abaixo iremos criar nossos erros customizados enum APIError Error case NotFound Recurso não encontrado case Forbidden Proibido case InternalError Erro interno case ServiceUnavailable Indisponível Usamos uma estrutura do tipo enum para definir o conjunto de erros que temos Para dar continuidade iremos supor que nosso serviço dispara exceções com os tipos definidos acima quando os respectivos códigos de status HTTP são recebidos Tratamento de ExceçãoAgora que játemos um conjunto definido de erros vamos ver como tratar nossas exceções A linguagem Swift usa para tratamento de exceções uma estrutura conhecida como do try catch que éescrita da seguinte forma do try execute catch let exception Tratamento da exceção Adequando o código acima para nosso cenário do serviço de filmes e supondo que o serviço jáestáimplementado teríamos o seguinte do Tenta obter os dados do filme de id try MovieService getById catch let exception Trata os erros Podemos ir um pouco além do que jávimos A estrutura do try catch permite que tratemos diferentes tipos de exceções como se fosse um switch case da seguinte forma do Tenta obter os dados do filme de id try MovieService getById catch APIError NotFound Trata o erro de Recurso não encontrado catch APIError Forbidden Trata o erro de Proibido catch APIError InternalError Trata o erro de Erro interno catch APIError ServiceUnavailable Trata o erro de Serviço Indisponível Com a estrutura acima conseguimos tratar alguns dos erros mais comuns que podem ocorrer ao fazer uma requisição a um servidor Vale destacar que não necessariamente essa éa melhor abordagem mas ela éum bom exemplo de como tratar erros customizados usando a linguagem Swift ConsideraçõesCaso vocêtenha interesse em descobrir mais sobre tratamento de exceções em Swift vocêpode ler a documentação Espero que essa explicação tenha te ajudado Gostou deste artigo Me siga para mais conteúdos como esse Minhas redes sociais Twitter Instagram Youtube Atéa próxima 2021-04-27 12:20:29
海外TECH DEV Community Rest API Testing 🤖 with Postman: An Introduction https://dev.to/webdeasy/rest-api-testing-with-postman-approach-and-strategies-54e8 Rest API Testing with Postman An IntroductionOriginally published at webdeasy de Testing of Rest APIs is one of the most important tasks in application development A good strategy of approach can detect many errors before the release of the application There are now many tools on the Internet for testing Rest APIs All tools certainly have the most important functions I use Postman because I like it the most and it is very intuitive and completely free In addition I would like to show you how to select good test cases and what is important to keep in mind Table of contents Selection of the optimal test cases HTTP Request Methods HTTP Status Codes Assemble test cases Organize requests in Postman Pass body data Insert Authorization Keys Program test cases in Postman Execute tests automaticallySummaryYou can download Postman here available for Windows Mac amp Linux Rest APIs can be developed well with the help of Node js If you want to know more about it feel free to go through my Node js beginner s guide Just to reiterate what a Rest API actually is A Rest API is the interface between client and server which can request and send data via simple HTTP requests Every time you call a URL in the browser at least one HTTP request to the server happens in the background Selection of the optimal test cases Before we enter the requests into Postman and start testing the first step is to select the test cases This requires a bit of brain power and also a bit of practice but is extremely important so that we uncover all potential bugs We need to think particularly carefully about edge cases Edge cases are test inputs that are most likely to cause erroneous output or even a program error Before that however we need to clarify two basic concepts HTTP Request MethodsThe individual URLs of a Rest API routes in programming all have a specific HTTP request method There are quite a few of these These are the four most important of a Rest API GET To retrieve information from the server e g username of a specific ID POST To send information to the server which then creates a new user in the database for example PUT To create or update an entity on the serverDELETE To delete an entity on the serverA complete list of all HTTP request methods can be found here When developing the Rest API you should already make sure that you select the right method for each route I explain how this can look in my tutorial on creating a Rest API for a login system HTTP Status CodesFor each HTTP request the server responds with an HTTP response which always contains an HTTP status code This returns the status of the requested operation Mostly this is OK This is the server s way of saying that everything is OK You should already return these status codes in the correct use case when developing your Rest API which will also make testing easier Another example If a user requests a URL for which he has no permissions because he is not authorized not logged in your Rest API should also return the status code Unauthorized with a corresponding error message The most used status codes are OK Example Request was executed without problems Created Example New user was created in the database Bad Request Example Missing parameters when calling Unauthorized Example User has no permission for a URLA detailed list of important HTTP status codes can be found here Assemble test casesNow it gets a bit more exhausting You now have to select the appropriate test cases for your app As already mentioned we have to look especially at the edge cases To explain this better I have created the following requirements as an example We want to create a function to register a user sign up Username password and password repetition are to be queriedThe user name must not be assigned yetThe user should receive an email to complete the registration double opt in With a little logical thinking the following test cases come to mind first Were all parameters user name password password repetition passed Does the username already exist in the database Has the confirmation email been sent This is all correct however we have forgotten some And these are the so called edge cases Is the HTTP request method correct Do the password and password repetition match Could the database query be executed without errors Are the correct HTTP status codes returned in case of errors Is the username not too long for the database field e g if VARCHAR is limited to characters Was a valid token for the double opt in created and successfully stored in the database The aim is to look at the request from a different angle in order to cover all marginal cases as far as possible I hope that I can sensitize you a little with this example Take some time to select the test cases This is more important than running the tests Once you have done this properly you will save a lot of time in the future Organize requests in PostmanNow that we have selected the test cases we start entering the tests into Postman structuring them and of course testing them If you have installed Postman this interface awaits you You should create a separate collection for each project Rest API This is like a folder in which you can organize your individual requests Also you can then run the tests for all the requests in it with a single click img alt Postman Create Collection lt br gt src webdeasy de wp content uploads postman jpg We can then create any number of requests per collection I have marked the most important settings in red img alt Structure of an HTTP request lt br gt src webdeasy de wp content uploads request jpg First we should give our request a name to quickly recognize it “Login in this case This name also appears on the left side of the Collection menu Next we can set the appropriate HTTP request method for each request and specify the exact URL of the Rest API route to check On the far right you will find the “Send button to send a request directly Pass body dataIn many cases we want to send data to the Rest API We can either do this using the “Params tab These are then transmitted to the server according to the HTTP request method or we use the “Body tab to transmit data in other data formats On the web JSON is often used because it is very flexible and you can safely transfer complex data structures It is important that you select “raw above the text field and then select the format “JSON to the right Otherwise the data might not be transferred correctly img alt Pass body parameters in Postman lt br gt src webdeasy de wp content uploads body jpg In the large text field the data can now be passed in JSON format This can look like this Postman shows you errors in the JSON structure directly But you can test it more exactly with this JSON validator username webdeasy de password fbr password repeat foobr Whether you use URL parameters or body data depends entirely on the implementation of your RestAPI This is how you access it in Node js respectively router post sign up req res next gt body data console log req body YOURDATA url parameters console log req params YOURPARAM Insert Authorization KeysIf you have implemented a login with a Bearer Token you can transfer it in the “Authorization tab To do so select “Bearer Token and enter it under “Token on the right img alt Authorization Transmit Bearer Token lt br gt src webdeasy de wp content uploads authorization jpg For other authentication methods you can select the appropriate one under “Type Tip Under the menu item “History you can find your last queries Program test cases in PostmanWe have entered the individual routes and structured them neatly You can already execute and test them via the “Send button But you always have to check all results manually It is easier if a script takes over the task for us We can do that under the tab “Tests img alt Create test cases with Postman lt br gt src webdeasy de wp content uploads testing jpg Here you have the possibility to program your test cases which is also easier than it sounds at first moment We can realize the query of the correct status code via the following code pm test Status test function pm response to have status It can be as simple as that What you will also often need is to query a response header variable Here I check if the response is an image of type “jpeg pm test Content Type is image jpeg function pm response to have header Content Type pm response to be header Content Type image jpeg Tip In the right margin under “Snippets you can click to insert predefined tests A more detailed documentation on how to create test cases is available directly from learning postman com Execute tests automaticallyWe have created our test cases manually But to save us some time we can run all tests together in one collection To do this select the collection and click on “Run There you can set the number of iterations executions and other items img alt Run Collection Test lt br gt src webdeasy de wp content uploads run test jpg Afterwards you will receive an accurate test protocol and can directly fix errors in the code and run the test again img alt Test protocol of the two tests lt br gt src webdeasy de wp content uploads test passed jpg SummaryWhen testing a Rest API and in general the selection of test cases is an extremely important step Only if you choose everything correctly you can cover all edge cases and fix all potential bugs in your application Postman offers you a simple interface for testing and trial and error With a few simple steps you can customize Postman so that you only have to make a few adjustments to your next application and thus save a lot of time Note For large and very sensitive systems many more and more detailed tests have to be created and evaluated integration tests acceptance tests … In my experience the examples shown here are well suited for many web applications to detect many errors and log results especially after system adjustments Did you like the article There are more on webdeasy de I m waiting for you there 2021-04-27 12:11:40
海外TECH DEV Community Deque data structure simplified https://dev.to/narthcodes/deque-data-structure-simplified-g35 Deque data structure simplifiedHello friends in today s article I d be writing about my understanding of deque data structure which would be helpful to us in one way or the other Recently I have been reading and practising Data structure and algorithm in javascript and one of the data structure I came across that got me into making more research on it is the deque data structure So now let s get to know what this structure is Deque is a data structure that allows both insertion and deletion of an element from both ends of a list The diagram above shows us clearly what a deque structure looks like Deque can also be seen as the combination of Queues FIFO first in first out and Stack LIFO last in first out operations Stacks and Queues are one ended operations unlike the deque which is a double ended operation because of what it does In the Deque system we have the rear i e the end of a list and front which is the beginning Elements can either be added from the front or from the rear and also can be removed vice versa Now I d drop a code snippet to show you how the deque data structure can be implemented in Javascript function Deque this addFront addFront this removeFront removeFront this addBack addBack this removeBack removeBack this arr this size size function size return this arr length returns the length of the list function addFront el return this arr unshift el Adds an element to the beginning of the list function addBack el return this arr push el Adds an element to the rear end of the list function removeFront el return this arr shift el Removes element from the beginning of the list function removeBack el return this arr pop el Removes element from the end of the list The above code snippet creates a deque constructor and also chains different methods which we d use to execute our operations let test new Deque test addFront apple test addFront melon test addBack ragna test arr ragna apple melon test size test removeBack pops out ragna test arr apple melon Now we know how this operation work using Javascript Let s try to implement a palindrome checker using the deque systemfunction palindrome str let myQueue new Deque for let i i lt str length i myQueue addBack str i let isEqual true while myQueue size gt amp amp isEqual let front myQueue removeFront let back myQueue removeBack if front back isEqual false return isEqual console log palindrome racecar trueAnd this is how we implement a palindrome checker using a deque data structure in javascript I hope you were able to learn one or two from this article Kindly leave a reply or a like if you learnt something new thanks 2021-04-27 12:03:37
海外TECH Engadget ADT sues Amazon over Ring's blue octagon signs https://www.engadget.com/adt-sues-ring-blue-octagon-signs-121432354.html signs 2021-04-27 12:14:32
海外TECH Engadget Spotify counters Apple with its own podcast subscription plan https://www.engadget.com/spotify-podcast-subscription-platform-120040301.html platform 2021-04-27 12:00:40
ラズパイ Raspberry Pi How to add LoRaWAN to Raspberry Pi Pico https://www.raspberrypi.org/blog/how-to-add-lorawan-to-raspberry-pi-pico/ How to add LoRaWAN to Raspberry Pi PicoArguably the winner of the standards war around wide area networking protocols for the Internet of Things LoRaWAN is a low powered low bandwidth and long range protocol Intended to connect battery powered remote sensors back to the internet via a gateway on a good day with a reasonable antenna you might well get km of range from an The post How to add LoRaWAN to Raspberry Pi Pico appeared first on Raspberry Pi 2021-04-27 12:55:02
Cisco Cisco Blog Get Unique IT Insights That Help You Make The Right Decisions Fast https://blogs.cisco.com/perspectives/get-unique-it-insights-that-help-you-make-the-right-decisions-fast Get Unique IT Insights That Help You Make The Right Decisions FastDigital agility has become the most sought after capability for most organizations following the explosion of the pandemic…To deliver actionable insights about the exceptionally fast technology evolution we re seeing today Cisco has looked under the hood of our platforms which contain huge volumes of data generated by our customer base We extracted analyzed and correlated this anonymized data to produce insights about the changes that happened in Introducing Connected IT Insights 2021-04-27 12:41:14
Cisco Cisco Blog DNA Spaces Ecosystem Partner Spotlight: Infor https://blogs.cisco.com/networking/dna-spaces-ecosystem-partner-spotlight-infor DNA Spaces Ecosystem Partner Spotlight InforToday we re featuring our App Center partner Infor Location Based Intelligence a software provider who works with organizations in the healthcare industry to leverage real time location systems to track and manage people and equipment so they can improve operations and deliver better experiences for patients 2021-04-27 12:00:52
海外ニュース Japan Times latest articles Global travel sector prepares for vaccine-powered revival https://www.japantimes.co.jp/news/2021/04/27/business/global-travel-rebound/ Global travel sector prepares for vaccine powered revivalNew variants threaten to render today s vaccines ineffective and the U S has put of the world s countries on a no go list but travel firms 2021-04-27 22:04:13
海外ニュース Japan Times latest articles On Myanmar crisis, ASEAN pushes boundaries of ‘noninterference’ https://www.japantimes.co.jp/news/2021/04/27/asia-pacific/politics-diplomacy-asia-pacific/myanmar-asean-limits/ On Myanmar crisis ASEAN pushes boundaries of noninterference The summit s concluding consensus statement stretch the bounds of ASEAN s longstanding principle of noninterference in members internal affairs 2021-04-27 21:38:18
海外ニュース Japan Times latest articles Angels’ Shohei Ohtani gets first win since 2018 in two-way appearance https://www.japantimes.co.jp/sports/2021/04/27/baseball/mlb/ohtani-two-way-win/ Angels Shohei Ohtani gets first win since in two way appearanceThe year old who entered the day as co home run leader in the league threw five innings and hit a two run double for the victorious Halos 2021-04-27 22:19:41
海外ニュース Japan Times latest articles Amputee Blake Leeper won’t be allowed to race with running blades https://www.japantimes.co.jp/sports/2021/04/27/more-sports/track-field/blake-leeper-prosthetic-blades-rejected/ Amputee Blake Leeper won t be allowed to race with running bladesWorld Athletics has rejected an application from American double amputee Blake Leeper to run on particular running specific prostheses RSPs preventing him from competing in the 2021-04-27 21:26:31
海外ニュース Japan Times latest articles Italian clubs who break away to be banned from domestic competitions https://www.japantimes.co.jp/sports/2021/04/27/soccer/italy-breakaway-club-ban/ Italian clubs who break away to be banned from domestic competitionsThe Italian soccer federation FIGC said on Monday that clubs who join a breakaway league would be banned from all domestic competitions including the first division 2021-04-27 21:02:51
ニュース BBC News - Home Covid-19: Vaccine offered to 42-year-olds in England https://www.bbc.co.uk/news/uk-56899901 covid 2021-04-27 12:25:24
ニュース BBC News - Home India Covid: First UK aid arrives as coronavirus deaths mount https://www.bbc.co.uk/news/world-asia-india-56898654 covid 2021-04-27 12:23:19
ニュース BBC News - Home Meth lab found in raid near Redditch https://www.bbc.co.uk/news/uk-england-coventry-warwickshire-56901616 chemicals 2021-04-27 12:21:41
ニュース BBC News - Home French warn UK ahead of vote on Brexit trade deal https://www.bbc.co.uk/news/world-europe-56899831 brexit 2021-04-27 12:07:31
ニュース BBC News - Home Pink Supermoon seen around the world https://www.bbc.co.uk/news/in-pictures-56900164 supermoon 2021-04-27 12:03:27
ビジネス ダイヤモンド・オンライン - 新着記事 日経平均株価は、終値で2本の移動平均線(25日/75日) を上回ってくれば「3万500円」まで上昇の可能性も! 一方、バイデン氏の増税案の株価への影響は限定的! - 成り上がり投資術 https://diamond.jp/articles/-/269832 また、日経平均株価は月日以降、概ね万円万円のボックス相場を継続しています。 2021-04-27 21:45:00
北海道 北海道新聞 胆振管内 変異株新たに7人 新型コロナ https://www.hokkaido-np.co.jp/article/538191/ 新型コロナウイルス 2021-04-27 21:16:00
北海道 北海道新聞 「こいのぼり大火」100年 記憶つなぐ 体験談知る住民高齢化 市美術博物館は企画展 https://www.hokkaido-np.co.jp/article/538190/ 高齢化 2021-04-27 21:16:00
北海道 北海道新聞 23年度物価見通し1.0% 目標ますます遠く 日銀総裁「残念」 https://www.hokkaido-np.co.jp/article/538180/ 新型コロナウイルス 2021-04-27 21:04:04
北海道 北海道新聞 最高級の一戸建て住宅発売 大和ハウス、コロナで需要 https://www.hokkaido-np.co.jp/article/538186/ 組み合わせ 2021-04-27 21:02:00
ニュース Newsweek 大阪府、27日のコロナ感染1,230人 過去2番目の多さに https://www.newsweekjapan.jp/stories/world/2021/04/271230.php また、大阪府は新型コロナウイルスに感染して亡くなった人が新たに人確認されたと発表した。 2021-04-27 21:15:06
IT 気になる、記になる… Amazon、「Fire HD 10キッズモデル」を発表 https://taisy0.com/2021/04/27/139775.html amazon 2021-04-27 13:42:55
IT 気になる、記になる… Amazon、新型「Fire HD 10」を発表 − RAM 4GBでワイヤレス充電対応の「Fire HD 10 Plus」も https://taisy0.com/2021/04/27/139770.html amazon 2021-04-27 13:33:04
TECH Engadget Japanese Amazonが新Fire HD 10とFire HD 10 Plusを発表、純正キーボードカバーも投入 https://japanese.engadget.com/amazon-fire-hd-10-131446982.html amazon 2021-04-27 13:14:46
IT ITmedia 総合記事一覧 [ITmedia PC USER] Amazon、10.1型タブレット「Fire HD 10」を刷新 メモリ4GBで無線充電対応の「Plus」モデルも https://www.itmedia.co.jp/pcuser/articles/2104/27/news131.html ITmediaPCUSERAmazon、型タブレット「FireHD」を刷新メモリGBで無線充電対応の「Plus」モデルもAmazonは、同社製型タブレット「FireHD」をフルモデルチェンジし、新たに上位モデルの「FireHDPlus」を追加した。 2021-04-27 22:01:00
python Pythonタグが付けられた新着投稿 - Qiita DataFrameを数値型変数・カテゴリ変数で分ける方法 https://qiita.com/shoku-pan/items/a76bf996701aacb01aac 同様にして、カテゴリ変数は以下で取得できます。 2021-04-27 22:49:16
python Pythonタグが付けられた新着投稿 - Qiita Nmapについてまとめる THM[2] https://qiita.com/suk0/items/4afc2c95ca52c0b9df27 FirewallによりPingの問い合わせが破棄されるとnmapはコンピュータがダウンしていると判断し、ポートが起きているかを調べるportscanという次のステップに進めない。 2021-04-27 22:15:48
python Pythonタグが付けられた新着投稿 - Qiita PythonでSOAPサーバにzeepを使ってアクセスする https://qiita.com/ryan5500/items/0ce0f0992283105bb7a2 PythonでSOAPサーバにzeepを使ってアクセスするSOAPとはSOAPとは、サーバにある関数をコールするためのプロトコル。 2021-04-27 22:11:48
python Pythonタグが付けられた新着投稿 - Qiita RHEL8系ディストリビューションでPython 3を使う https://qiita.com/yamada-hakase/items/ed38a66ac10cf9cfe07e そのためインストール環境によってはpythonやpythonを実行してもPythonが起動しない可能性がある新しいバージョンのソフトウエアを提供する仕組みとして、これまでのSoftwareCollectionsに代わってAppStreamが導入されたユーザーが使うPythonはAppStreamからインストールするRHELやRHELにあったSoftwareColletionsは提供されないPythonがインストールされていないことがあるRHEL系ディストリビューションでは、Pythonがデフォルトだ。 2021-04-27 22:10:36
python Pythonタグが付けられた新着投稿 - Qiita 【Python】ブックの作成者の変更を行う。 https://qiita.com/rihu-do/items/2a064040f7971ef0b0ff 本日の気づき復習は、ブックの作成者最終更新者の変更に関してです。 2021-04-27 22:06:06
js JavaScriptタグが付けられた新着投稿 - Qiita ~ChildプロパティをquerySelector/querySelectorAllで取得した値に使えるか https://qiita.com/prog_jincho/items/8ff9dd8559080b02906a ChildプロパティをquerySelectorquerySelectorAllで取得した値に使えるかはじめにJavaScriptのDOMの勉強をし始めて、Elementと名の付くプロパティが使えたり使えなかったり大変だなあと感じています。 2021-04-27 22:19:13
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Laravelを使用してて、use App\Http\Requests;だけ薄くなります。 https://teratail.com/questions/335479?rss=all laravel 2021-04-27 22:57:00
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 二次元リストのそれぞれの要素の組み合わせを抽出 https://teratail.com/questions/335478?rss=all 二次元リストのそれぞれの要素の組み合わせを抽出二次元リストのそれぞれの要素数が異なり、その要素を組み合わせた新たなリストを作りたいです。 2021-04-27 22:56:22
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Exclusive locks are not supported for this streamの対応 https://teratail.com/questions/335477?rss=all Exclusivelocksarenotsupportedforthisstreamの対応質問諸事情で、LaravelのFileCacheにAWSnbspEFSを利用しています。 2021-04-27 22:43:57
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) PHPとMySQLの接続 https://teratail.com/questions/335476?rss=all PHPとMySQLの接続PHPでユーザーログイン機能を作っているのですが、まずログイン画面が表示されて、アカウントがなかったら、新規登録画面URLで新規登録画面に遷移して、そこでユーザー名、パスワードを入力してMySQLデータベースに登録すると言った処理なのですが、新規登録画面を押すと、ブラウザ上で、SQLSTATEHYnbspnbspNonbspsuchnbspfilenbspornbspdirectorynbspや、SQLSTATEHYnbspnbspCannotnbspassignnbsprequestednbspaddressnbspと表示されてしまいます。 2021-04-27 22:34:16
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) GASでスプレッドシートをメールに添付した際に更新箇所が反映されていない https://teratail.com/questions/335475?rss=all GASでスプレッドシートをメールに添付した際に更新箇所が反映されていない前提・実現したいことWebフォームで入力した内容をスプレッドシートに反映し、そのシートをExcelに変換してメールに添付して送信するスクリプトを作成しています。 2021-04-27 22:20:27
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) editorconfig https://teratail.com/questions/335474?rss=all editorconfig 2021-04-27 22:11:09
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) SVG画像、画面幅によって画像の縦横比が崩れる。 https://teratail.com/questions/335473?rss=all SVG画像、画面幅によって画像の縦横比が崩れる。 2021-04-27 22:02:49
Ruby Rubyタグが付けられた新着投稿 - Qiita 【Ruby】メソッド【備忘録】 https://qiita.com/guminatto/items/405b60eaecef03018e60 カンマとコロンの両方に一致する部分で分割したい場合irbmaingtsplitgtバイトの空白文字で区切る場合irbmaingtabcdefsplitgtabcdefsplitで対象となる文字列中の空白文字は、半角スペース、改行、タブのつある区切り文字に一致する部分すべてを分割する必要がない場合irbmaingtabcdefsplitfirstgtabcfirstメソッドを使うと、区切り文字の分割された最初だけ取得できるmapメソッド配列の要素の数だけブロック内で処理を繰り返して、新しい配列を返すメソッド。 2021-04-27 22:24:33
AWS AWSタグが付けられた新着投稿 - Qiita VPC Peeringを使用してVPC間を接続する https://qiita.com/mkuser9/items/591f9a779fd9e11a01b8 ECインスタンスを払い出してdigコマンドで名前解決各VPCにECインスタンスを払い出す。 2021-04-27 22:24:43
Docker dockerタグが付けられた新着投稿 - Qiita dockerとkubectl をWSL2で用意 https://qiita.com/XPT60/items/ef9fbe82127b5b559b44 Dockerここに書いてあることをそのまま実行しただけ。 2021-04-27 22:51:22
Ruby Railsタグが付けられた新着投稿 - Qiita Rails APIモード + devise_token_auth + Vue.js 3 で認証機能付きのSPAを作る(ファイル投稿編) https://qiita.com/kk-icare/items/50d440b3994234cb76db 前回RailsAPIモードdevisetokenauthVuejsで認証機能付きのSPAを作るNavigationGuard編ActiveStorageの導入今回はファイルの保存をRails系以降から使えるようになったActiveStorageを用いて実現してみようと思います。 2021-04-27 22:56:03
技術ブログ Developers.IO カメラの外部パラメータを推定する(2Dカメラ) https://dev.classmethod.jp/articles/estimate-camera-external-parameter-matrix-2d-camera/ depth 2021-04-27 13:28:51
海外TECH Ars Technica Archaeologists found the site of Harriet Tubman’s family home https://arstechnica.com/?p=1760318 conservation 2021-04-27 13:49:58
海外TECH Ars Technica A freshly flush Lotus Cars readies four new vehicle architectures https://arstechnica.com/?p=1760341 combustion 2021-04-27 13:06:13
海外TECH DEV Community From JavaScript to Rust : Data Types https://dev.to/laurieontech/from-javascript-to-rust-data-types-13ff From JavaScript to Rust Data TypesYou may have been following my journey to learn Rust as I covered topics like mutable variables ownership and references and crates These learnings fell into two distinct categories Stuff that has a clear parallel in JavaScript landStuff that s brand new and I have no existing mental model forYet as I started to read and write more Rust code I realized I was missing one big piece of the puzzle when it comes to learning a new language I didn t have a strong understanding of data types in Rust I quickly discovered that this information fell into a third learning category Stuff that overlaps with my JavaScript mental model in a way that s contradictory Given that reality I figured a post was in order So without further ado let s talk data types PrimitivesA JavaScript primitive is similar to what Rust calls a scalar type Rust has four scalar types booleans integers floating point numbers and characters Additionally The Rust Reference mentions primitive types which includes str and Never on top of the four scalar types BooleanLet s start with something familiar booleans Booleans or bool in Rust are a type with two possible values true or false This matches up with our JavaScript understanding so no changes here NumberThe same can t be said of numbers In Rust you need to care about what type of number you re storing Is it an integer or a floating point number What amount of space in bits does storing it take Is it signed or unsigned In Rust you can initialize integers of five different sizes from bit to bit either signed or unsigned For floating point numbers you have either f or f the first is single precision and the second double precision StringYou may have noticed that I didn t mention strings as Rust scalar types I mentioned char This is accurate However Rust does have a primitive type str The strange thing is you likely won t use it other than as a reference to a specific string stored in memory amp str If you want to create or manipulate strings you want the growable type String But be careful The methods you re used to like len aka length won t return what you expect Structural typesIn JavaScript most structural types are specific implementations of the JavaScript object type But we ll break them out individually for the sake of this post ArraysNow we get to the part where you ll need to rewire your internal JavaScript dictionary An array is a valid Rust type Unfortunately that s not entirely helpful An array in Rust is of fixed size If you expect to create static data that won t change but you want to reference look it up in an array structure then this may be what you want More likely though you want a Vector vec is similar to String It s an array type that you can own and grow dynamically ObjectsSearch Rust object type and you re bound to be confused You ll end up reading up on Trait object types which is a bit more advanced than what you re after What you re really looking for is struct In Rust a struct is defined as a type composed of other types Sounds like a JavaScript object to me It s worth reading about structs further because they do some unique things when it comes to mutability Sets and MapsThese are relative newcomers in the land of JavaScript but they re great tools to have at your disposal When developing in Rust you ll get similar functionality from HashSets and HashMaps Note that there are also BTree based implementations of these structures FunctionAs with JavaScript Rust has first class functions In addition to functions defined using the fn keyword Rust also has closures Closures are anonymous functions with syntax that looks similar to JavaScript arrow functions Is that it JavaScript is pretty minimal when it comes to types Especially when compared to more verbose languages like Java or C Rust s offerings are more similar to the latter so things like Linked Lists are available as a type in Rust If you can t find what you re looking for the docs are great And so is the community With a little bit of trial and error you ll get what you need 2021-04-27 13:44:08
海外TECH DEV Community 5 blogs you shouldn't have missed last week, but did! 📣 https://dev.to/technoglot/5-blogs-you-shouldn-t-have-missed-last-week-but-did-1cbl blogs you shouldn x t have missed last week but did Photo by Oleg Laptev on UnsplashWhat s up devs How are you doing Last week I did a post highlighting underrated blogs that I thought could use more attention I enjoyed that so I thought I d do it again this week Let s take a look at this week s picks Disclaimer I m doing this out of my personal motivation None of these great authors bloggers asked me for any promo I still think they deserve a shout out so here it goes Oh and the order I listed the posts in is totally random by the way Pick ️⃣Here s a friendly yet much needed reminder from malteriechmann Learn the basics I highly recommend all code newbies to take a look at this one It s a short blog yet oh so powerful But first learn the basics Malte Riechmann・Apr ・ min read beginners webdev career Pick ️⃣ kaspermroz did an awesome job documenting his learnings on this Einstellung effect Einstel whut Yeah das ist ein deutsches wort I m not fluent in German whatsoever yet Take a look at it I m sure you won t be disappointed Tell Kasper I said Hi The Einstellung Effect Kasper Mróz・Apr ・ min read productivity watercooler todayilearned programming Pick ️⃣Guess what I ve found another blog covering TDD this week Yep that s right This time theowlsden gives us a pretty neat non technical intro to the subject Go read it what are you waiting for TDD a non technical intro Shaquil Maria・Apr ・ min read devops beginners testing todayilearned Pick ️⃣ lukaszreszke begs us to please stop talking SQL Huh If you like me are wondering what he means go take a look for yourself Ah and be mindful of your soft i e non technical skills Let s stop talking SQL Łukasz Reszke・Apr ・ min read watercooler devjournal architecture agile Pick ️⃣And last but certainly not least smeetsmeister dropped yes FOUR lessons learned as a starting Scrum Master This blog right here is a pot of gold on its own lessons I learned as a starting Scrum master Jelle Smeets・Apr ・ min read career agile productivity beginners It s a wrap That s all folks Let me know how you liked these posts if you check them out Should I rollout another blog like this next week Insert thoughts below See you soon ‍ 2021-04-27 13:25:43
海外TECH DEV Community Batch with Node.js https://dev.to/alligatore3/batch-with-node-js-3nlk Batch with Node js PremiseLet s say that your aunt comes to you asking a favor She has this pen drive with A LOT of folders containing mps and by what she believes her car cannot read recursively all the folders so she needs one root folder containing all the mps The USB drive is structured as below songs folder foo mp another foo mp folder bar mp another bar mp And we need to reach this result output foo mp another foo mp bar mp another bar mp Given this overview you have two option to do this Do it manually Leave a like ️to this post To start we re gonna create a folder let s call it batch node Inside that folder I ve copied the songs folder above and I ve created an index js file So this is now my batch node structure batch node index js songs For this purpose we ll use fs extra since copy paste seems like not supported by fs API Just add it yarn add fs extra Let s starting coding index js fs extra adds file system methods that aren t included in the native fs module and adds promise support to the fs methods const fs require fs extra const MP DIRECTORY songs const OUTPUT output Be carefull do not create output folder since fs extra will handle this for us otherwise it won t work The script is composed by main functions a readDirectory to of course read a folder and its content and a copyToDestination function to copy our song to the folder destination Let s add these functions to our index js const copyToDestination path file gt try const fileFormat path split pop const isMP fileFormat mp if isMP return see fs copySync path OUTPUT file console log file has been copied to OUTPUT catch error console error error const readDirectory dir name gt fs readdir dir name withFileTypes false error files gt try files forEach file gt const path dir name file see fs stats isdirectory const isDir fs lstatSync path isDirectory const config file path return isDir readDirectory path copyToDestination config catch error console error error Pay attention to these lines const fileFormat path split pop const isMP fileFormat mp if isMP returnSince we have different types of files inside folders like covers album ini files and many more we re returning the function to totally ignore these kinds of file Finally we just have to lunch our function at the end of our index js readDirectory MP DIRECTORY This should avoid you some boring manual stuff 2021-04-27 13:08:56
Apple AppleInsider - Frontpage News Spotify launches paid podcast subscriptions via Anchor https://appleinsider.com/articles/21/04/27/spotify-launches-paid-podcast-subscriptions-via-anchor?utm_medium=rss Spotify launches paid podcast subscriptions via AnchorPodcast creators who use Anchor can now submit paid only podcast episodes to Spotify initially for no additional cost but with a fee starting in Premium podcasts on SpotifyAs previously predicted Spotify has launched paid podcasts on its platform and is rolling out the service to creators and users It hopes to achieve a competitive advantage over Apple s new podcast offering with zero fees and non exclusive requirements Read more 2021-04-27 13:42:17
Apple AppleInsider - Frontpage News Hands on: Twelve South Forte is a MagSafe charging stand for iPhone & AirPods https://appleinsider.com/articles/21/04/27/hands-on-twelve-south-forte-is-a-magsafe-charging-stand-for-iphone-airpods?utm_medium=rss Hands on Twelve South Forte is a MagSafe charging stand for iPhone amp AirPodsTwelve South gave us an early hands on of its first MagSafe charging stand Forte that is well suited for not only your iPhone but your AirPods as well Forte MagSafe chargerForte a product name once bestowed on its previous high end Apple exclusive charger is now being used for a new MagSafe charging stand Read more 2021-04-27 13:11:12
Apple AppleInsider - Frontpage News Hands on with Nomad's new Base Station Mini wireless charger https://appleinsider.com/articles/21/04/27/hands-on-with-nomads-new-base-station-mini-wireless-charger?utm_medium=rss Hands on with Nomad x s new Base Station Mini wireless chargerNomad has released a new model of its popular Base Station lineup this time a solo wireless charging pad We go hands on for the device s launch Base Station MiniBase Station Mini is very similar to Nomad s Base Station Base Station Hub as well as its Base Station Pro They all have a very similar design aesthetic and not dissimilar matterials Read more 2021-04-27 13:07:39
Apple AppleInsider - Frontpage News Leaked Apple schematics and extortion threats removed from dark web https://appleinsider.com/articles/21/04/27/leaked-apple-schematics-and-extortion-threats-removed-from-dark-web?utm_medium=rss Leaked Apple schematics and extortion threats removed from dark webThe ransomware group attempting to extort million from Apple has pulled down previously leaked schematics and removed all references to the previous demands On April ransomware REvil posted on the dark web that it had obtained stolen Quanta documents revealing details of upcoming Apple Watch MacBook Air and MacBook Pro models The group threatened to leak the documents if Apple did not pay a million ransom The group had initially attempted to get money from Apple supplier Quanta though the effort fell flat Read more 2021-04-27 13:06:23
Apple AppleInsider - Frontpage News Apple will ban apps offering rewards to users that enable tracking https://appleinsider.com/articles/21/04/27/apple-will-ban-apps-offering-rewards-to-users-that-enable-tracking?utm_medium=rss Apple will ban apps offering rewards to users that enable trackingApp developers cannot bribe users into allowing tracking within an app Apple has warned with apps prevented from performing a number of actions to try and influence what a user selects in the App Tracking Transparency notification As part of the introduction of App Tracking Transparency Apple s feature to give users the chance to prevent specific apps from tracking their online activities for advertising purposes Apple has written guidelines for developers to follow As part of these guidelines Apple lists things apps cannot do to convince users into enabling tracking in the ATT notification Within the Human Interface Guidelines of Apple s Developer site specifically under Accessing User Data Apple has included a section explaining elements that developers cannot do in tandem with tracking requests As reported by MacRumors this includes outright bribery of a user Read more 2021-04-27 13:05:27
Apple AppleInsider - Frontpage News Updated Eve Energy now available with Thread support https://appleinsider.com/articles/21/04/27/updated-eve-energy-now-available-with-thread-support?utm_medium=rss Updated Eve Energy now available with Thread supportOn Tuesday Eve officially launched the latest fourth generation model of the Eve Energy HomeKit smart plug ーcomplete with Thread support Eve Energy fourth genThe smart home purveyor kept the design of the same as the last generation device with the only notable change the addition of Thread Read more 2021-04-27 13:04:35
Apple AppleInsider - Frontpage News Apple's 'M2' processor enters mass production for MacBook Pro https://appleinsider.com/articles/21/04/27/apples-m2-processor-enters-mass-production-for-macbook-pro?utm_medium=rss Apple x s x M x processor enters mass production for MacBook ProThe second Apple Silicon processor has reportedly entered volume production and will first appear in MacBook Pro models from the second half of Apple s MacBook Pro is expected to be the first Mac to use the forthcoming M processorA new supply chain report is backing up previous claims that Apple has rescheduled new MacBook Pro manufacturing to the second half of Read more 2021-04-27 13:57:39
海外TECH Engadget ‘The Falcon and Winter Soldier’ fails to pay off on its initial promise https://www.engadget.com/falcon-and-winter-soldier-episode-six-captain-america-disney-plus-133033258.html The Falcon and Winter Soldier fails to pay off on its initial promiseDisney promised us Marvel shows that would tie into the movies but the finale of The Falcon and Winter Soldier just sent us back to the beginning 2021-04-27 13:30:33
海外TECH Engadget Samsung Galaxy S21 smartphones are up to $200 off at Amazon https://www.engadget.com/samsung-galaxy-s21-5g-smartphone-sale-up-to-200-off-amazon-131515976.html ultra 2021-04-27 13:19:15
海外TECH Engadget 'Super Mario Party' update adds proper online multiplayer https://www.engadget.com/super-mario-party-online-nultiplayer-update-131057030.html x Super Mario Party x update adds proper online multiplayerNintendo has added a full online multiplayer mode to Super Mario Party making it much more viable when you can t join friends in person 2021-04-27 13:10:57
海外科学 NYT > Science Why Aren’t More Moon Craters Named for Women? https://www.nytimes.com/2021/04/27/science/moon-craters-women.html contributions 2021-04-27 13:46:28
海外科学 NYT > Science These Materials Could Make Science Fiction a Reality https://www.nytimes.com/2021/04/27/science/metamaterials-technology.html fiction 2021-04-27 13:09:49
海外科学 NYT > Science Lockdowns Cut South Asia Smog. They Could Fill Reservoirs, Too. https://www.nytimes.com/2021/04/26/climate/air-pollution-coronavirus-snowmelt.html Lockdowns Cut South Asia Smog They Could Fill Reservoirs Too Coronavirus restrictions reduced pollution that makes snow melt faster which could help water supplies for million last longer this year 2021-04-27 13:06:19
金融 RSS FILE - 日本証券業協会 新型コロナウイルス感染症への証券関係機関等・各証券会社の対応について(リンク集) https://www.jsda.or.jp/shinchaku/coronavirus/link.html 新型コロナウイルス 2021-04-27 14:30:00
海外ニュース Japan Times latest articles Global travel sector prepares for vaccine-powered revival https://www.japantimes.co.jp/news/2021/04/27/business/global-travel-rebound/ Global travel sector prepares for vaccine powered revivalNew variants threaten to render today s vaccines ineffective and the U S has put of the world s countries on a no go list but travel firms 2021-04-27 22:04:13
海外ニュース Japan Times latest articles Angels’ Shohei Ohtani gets first win since 2018 in two-way appearance https://www.japantimes.co.jp/sports/2021/04/27/baseball/mlb/ohtani-two-way-win/ Angels Shohei Ohtani gets first win since in two way appearanceThe year old who entered the day as co home run leader in the league threw five innings and hit a two run double for the victorious Halos 2021-04-27 22:19:41
ニュース BBC News - Home Labour accuses Boris Johnson of lying over flat renovation costs https://www.bbc.co.uk/news/uk-politics-56903838 downing 2021-04-27 13:24:38
ニュース BBC News - Home Tate Modern: Jonty Bravery had history of 'malicious and violent' behaviour https://www.bbc.co.uk/news/uk-england-london-56881724 behaviourjonty 2021-04-27 13:03:00
ニュース BBC News - Home Queen pictured resuming public duties after duke's death https://www.bbc.co.uk/news/uk-56903877 death 2021-04-27 13:38:48
ニュース BBC News - Home High Court to look at PM's Patel 'bullying' decision https://www.bbc.co.uk/news/uk-politics-56901333 rules 2021-04-27 13:41:07
ニュース BBC News - Home Crocs sales soar in fashion comeback https://www.bbc.co.uk/news/business-56901386 record 2021-04-27 13:35:05
ニュース BBC News - Home Covid: What is the rule of six and what are the social distancing rules? https://www.bbc.co.uk/news/uk-51506729 covid 2021-04-27 13:27:59
ビジネス ダイヤモンド・オンライン - 新着記事 東京エレクトロン デバイス、2期連続「増配」を発表、 配当利回り3.5%に! 年間配当は2年で1.9倍に急増、 2022年3月期は前期比50円増の「1株あたり125円」に - 配当【増配・減配】最新ニュース! https://diamond.jp/articles/-/269897 東京エレクトロンデバイス、期連続「増配」を発表、配当利回りに年間配当は年で倍に急増、年月期は前期比円増の「株あたり円」に配当【増配・減配】最新ニュース東京エレクトロンデバイスが期連続の「増配」を発表し、配当利回りがに東京エレクトロンデバイスは年月期の配当予想を「株あたり円」と発表し、前期比「円」の増配で「期連続増配」の見通しとなった。 2021-04-27 22:15:00
ビジネス ダイヤモンド・オンライン - 新着記事 ツカダ・グローバルホールディング、株主優待の一部 変更で利便性アップ! 100株でもらえる「株主優待券」 がスパやフィットネスの施設でも利用できるように! - 株主優待【新設・変更・廃止】最新ニュース https://diamond.jp/articles/-/269722 ツカダ・グローバルホールディング、株主優待の一部変更で利便性アップ株でもらえる「株主優待券」がスパやフィットネスの施設でも利用できるように株主優待【新設・変更・廃止】最新ニュースツカダ・グローバルホールディングが、株主優待を一部変更することを、年月日に発表した。 2021-04-27 22:10:00
LifeHuck ライフハッカー[日本版] iOS 14.5が公式リリース。iPhoneの新機能を早速チェックしよう https://www.lifehacker.jp/2021/04/how-to-get-early-access-to-ios-14-5-before-next-weeks.html airtag 2021-04-27 22:05:00
北海道 北海道新聞 投資名目で30代女性1千万円、別の女性は550万円だまし取られる 札幌 https://www.hokkaido-np.co.jp/article/538221/ 仮想通貨 2021-04-27 22:15:00
北海道 北海道新聞 英大時計の改修、来年終了 新型コロナで作業遅れ https://www.hokkaido-np.co.jp/article/538219/ 遅れ 2021-04-27 22:10:00
北海道 北海道新聞 巨14―11ヤ(27日) 巨人が乱打戦制す https://www.hokkaido-np.co.jp/article/538218/ 最多 2021-04-27 22:08:00
北海道 北海道新聞 江差高等看護 パワハラ調査早急に 父母ら再度訴え https://www.hokkaido-np.co.jp/article/538217/ 高等看護学院 2021-04-27 22:02:00
ビジネス 東洋経済オンライン 液晶パネルで世界出荷が1位、中国「BOE」の凄み 2020年の通期業績は大幅増収増益を記録した | 「財新」中国Biz&Tech | 東洋経済オンライン https://toyokeizai.net/articles/-/424097?utm_source=rss&utm_medium=http&utm_campaign=link_back biztech 2021-04-27 22:30:00
仮想通貨 BITPRESS(ビットプレス) [BUSINESS INSIDER] ビットコインはバブルか?コインチェック共同創業者が語る「仮想通貨ブームのこれから」 https://bitpress.jp/count2/3_9_12460 businessinsider 2021-04-27 22:32:51
IT 週刊アスキー 『リゼロス』で「第3章前編 ミミIFストーリー」を公開!そのほか「GW記念キャンペーン」など多彩なイベントやキャンペーンも開催中 https://weekly.ascii.jp/elem/000/004/053/4053164/ lostinmemories 2021-04-27 22:20:00
IT ITmedia 総合記事一覧 [ITmedia News] 「kintoneの脆弱性ではない」 東京都医療者向けワクチン予約サイトの個人情報問題でサイボウズが見解 https://www.itmedia.co.jp/news/articles/2104/27/news162.html itmedia 2021-04-27 23:43:00
AWS AWS Management Tools Blog Using AWS CodePipeline to deploy AWS Config conformance packs created with the Rule Development Kit https://aws.amazon.com/blogs/mt/using-aws-codepipeline-to-deploy-aws-config-conformance-packs-created-with-rule-development-kit/ Using AWS CodePipeline to deploy AWS Config conformance packs created with the Rule Development KitAs consultants we often help customers manage AWS services using infrastructure as code IaC We follow DevOps practices for building versioning testing and deploying services We also use AWS Config custom and managed rules to evaluate the configuration settings of AWS resources AWS Config continuously tracks the configuration changes that occur among AWS resources and … 2021-04-27 14:27:25
AWS AWS Open Source Blog Using Streamlit to build an interactive dashboard for data analysis on AWS https://aws.amazon.com/blogs/opensource/using-streamlit-to-build-an-interactive-dashboard-for-data-analysis-on-aws/ Using Streamlit to build an interactive dashboard for data analysis on AWSIn this article we ll show how to stand up an Exploratory Data Analysis EDA dashboard for business users using Amazon Web Services AWS with Streamlit Streamlit is an open source framework for data scientists to efficiently create interactive web based data applications in pure Python In this tutorial the EDA dashboard allows for quick end to end deployment … 2021-04-27 14:07:49
python Pythonタグが付けられた新着投稿 - Qiita 謎謎 https://qiita.com/NIT/items/6f863eb228987512d7cb 謎謎 2021-04-27 23:25:55
js JavaScriptタグが付けられた新着投稿 - Qiita querySelectorAllとgetElementByClassNameの違い https://qiita.com/prog_jincho/items/a9c3a398ce9c23124958 getelementbyclassname 2021-04-27 23:17:17
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) C言語のforの問題の質問 https://teratail.com/questions/335490?rss=all C言語のforの問題の質問前提・実現したいことと入力するととなるコードが書きたいここに質問の内容を詳しく書いてください。 2021-04-27 23:57:15
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 時系列データのタイムゾーン処理をしたい https://teratail.com/questions/335489?rss=all 時系列データのタイムゾーン処理をしたい前提・実現したいこと以下の時系列データに対して、タイムゾーンをquotUTCquotからquotEuropeLondonquotに切り替えたいが、思うような結果が得られません。 2021-04-27 23:53:28
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) PHPでSQLに接続する処理を書くと真っ白な画面が出てしまいます。原因と解決策をご教示頂きたく存じます。 https://teratail.com/questions/335488?rss=all 現在、phpでsqlにデータを記述する処理を書こうとしているのですが、参考書の通りに記述しているにも関わらず、サーバーにアップして見てみても、真っ白な画面が出るだけで、何も表示されません。 2021-04-27 23:34:18
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) NUCLEO-F446REで入力ピンの状態をレジスタから知りたい。 https://teratail.com/questions/335487?rss=all NUCLEOFREで入力ピンの状態をレジスタから知りたい。 2021-04-27 23:26:41
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) WordPressの外部リンクが上手くいかない https://teratail.com/questions/335486?rss=all wonbsp 2021-04-27 23:24:21
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 正規表現 3文字連続する文字を、2文字にしたい https://teratail.com/questions/335485?rss=all resubraaabbcああcあああcあああああccdddddcccあああああああabbcああcあcあccdcあ見ていただいたら分かるように、文字以上の文字を取るところまでは出来ているのですが、それらを文字にしたいのです。 2021-04-27 23:21:05
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) FlutterのDropDownButton(DropdownMenuItem)の選択した値の画面遷移の値渡しについて教えてください https://teratail.com/questions/335484?rss=all FlutterのDropDownButtonDropdownMenuItemの選択した値の画面遷移の値渡しについて教えてください前提・実現したいことFlutterどころかプログラミングについてかなりの初心者です。 2021-04-27 23:20:41
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) formオブジェクトで投稿が表示されない https://teratail.com/questions/335483?rss=all formオブジェクトで投稿が表示されない現状現在、オリジナルアプリ作成中で、投稿機能と多対多の関係でタグ機能を実装中です。 2021-04-27 23:20:38
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) forループについて https://teratail.com/questions/335482?rss=all forループについてPythonのforループについてコンソールからの文字列をforループで文字ずつ確認し、aposaposの文字数をprintできるようにしたい。 2021-04-27 23:11:42
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 数字がいくつ一致するかで条件分岐 https://teratail.com/questions/335481?rss=all 数字がいくつ一致するかで条件分岐前提・実現したいこと数字当てをするゲームを作成しています。 2021-04-27 23:06:42
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) pytorchのtensorについて質問です。 https://teratail.com/questions/335480?rss=all pytorch 2021-04-27 23:05:03
Linux Ubuntuタグが付けられた新着投稿 - Qiita Asterisk18 + Ubuntu で内線電話網を構築 https://qiita.com/YuuT_38/items/5a418a60f2d08d8bc3cf Asteriskで過去に内線環境自体は構築したことがあるのですが、そのときは声が届かず検証の時間も準備していなかったため、断念しました。 2021-04-27 23:45:07
AWS AWSタグが付けられた新着投稿 - Qiita AmazonLinux上でNode.jsとYarnをインストールする https://qiita.com/Jackson123/items/97621cfef83c53bfbb5b AmazonLinux上でNodejsとYarnをインストールする下記を参考にさせていただきました。 2021-04-27 23:18:22
Docker dockerタグが付けられた新着投稿 - Qiita 【メモ】Kubernetesのよく使うリソースまとめ【初心者】 https://qiita.com/tetsuro731/items/b2e978e5a11de7551a48 これに一致するappreleaseを指定したPodと疎通できるreleasesummerportsnamehttpport番ポートを公開こんな感じで書く。 2021-04-27 23:30:34
Azure Azureタグが付けられた新着投稿 - Qiita 【2021令和最新版】Azure Cognitive Search を使って簡単ナレッジマイニングハンズオン(日本語対応) https://qiita.com/nohanaga/items/a8a70bb19cdb2710eb72 デプロイが完了し、作成された検索サービスをクリックすると、以下のようなポータル画面が表示されます。 2021-04-27 23:55:57
Azure Azureタグが付けられた新着投稿 - Qiita Azure Functions x Twitter4Jで乃木坂46への愛を叫ぶ https://qiita.com/kikutaro/items/2910927288cef773491d mvnazurefunctionsdeployAzureFunctionsといっても中身は普通のJavaプログラムなので、TwitterJのようなライブラリを利用できるのが嬉しいです。 2021-04-27 23:05:41
Git Gitタグが付けられた新着投稿 - Qiita Railsチュートリアル(第1章)でHerokuへのデプロイに躓いた https://qiita.com/it1221/items/85d1eb1f0b5f086020dc 解決編・エラー文での指示通りにコマンドを実行bundlelockaddplatformxlinuxGemfilelockを覗いてみるとnokogirixdarwin↲raccgt↲nokogirixlinux↲raccgt↲元から記述されてたであろうdarwinの下に先ほど追加したlinuxがちゃんと記述されてる・Gemfileを書き換えたのでRailsチュートリアルでの教えに倣って再度以下のコマンドを実行bundleinstallwithoutproduction・Gitの練習も兼ねているのでコミットしてから、再度デプロイにチャレンジgitpushherokumasterremoteVerifyingdeploydone解決編失礼、そのはありません。 2021-04-27 23:48:58
Ruby Railsタグが付けられた新着投稿 - Qiita Railsチュートリアル(第1章)でHerokuへのデプロイに躓いた https://qiita.com/it1221/items/85d1eb1f0b5f086020dc 解決編・エラー文での指示通りにコマンドを実行bundlelockaddplatformxlinuxGemfilelockを覗いてみるとnokogirixdarwin↲raccgt↲nokogirixlinux↲raccgt↲元から記述されてたであろうdarwinの下に先ほど追加したlinuxがちゃんと記述されてる・Gemfileを書き換えたのでRailsチュートリアルでの教えに倣って再度以下のコマンドを実行bundleinstallwithoutproduction・Gitの練習も兼ねているのでコミットしてから、再度デプロイにチャレンジgitpushherokumasterremoteVerifyingdeploydone解決編失礼、そのはありません。 2021-04-27 23:48:58
Ruby Railsタグが付けられた新着投稿 - Qiita ActiveAdmin で日付カラムのデフォルトを datepicker にする方法 https://qiita.com/Yuki-Inoue/items/308e7e4d47037f484254 ActiveAdminで日付カラムのデフォルトをdatepickerにする方法問題ActiveAdminでは、日付カラムはデフォルトではdateselectが利用され、結果として年月日のフィールドが別々になってしまう。 2021-04-27 23:36:34
技術ブログ Developers.IO GlacierおよびGlacier Deep Archiveに対するAthenaの実行結果 https://dev.classmethod.jp/articles/athena-glacier-deep-archive-error/ archive 2021-04-27 14:37:00
海外TECH Ars Technica EU to charge Apple with anticompetitive behavior this week https://arstechnica.com/?p=1760377 iphone 2021-04-27 14:25:41
海外TECH DEV Community Mendekatkan Diri Kepada Functional Programming di Javascript 🚶 https://dev.to/fauzan121002/mendekatkan-diri-kepada-functional-programming-di-javascript-3opk Mendekatkan Diri Kepada Functional Programming di Javascript Bagaimana kalian menulis blok program dan menggunakan paradigma apa adalah hal yang sangat penting dan vital bagi pemrogram karena hal tersebut juga dapat menentukan bagaimana sebuah program berjalan dan berkembang selanjutnya Kali ini saya akan membahas Functional Programming karena terlalu banyak sudah yang membahas OOP dan procedural programming akhirnya saya berinisiatif menyebarkan faham tentang paradigma pemrograman yang satu ini Functional Programming Functional Programming adalah ketika kita menulis kumpulan blok program menggunakan functions dan menghindari state dan data yang mutable mutable berarti kita dapat dengan mudah membuat struktur data daripada memodifikasi yang sudah ada bukan OOP objects classes bottom up approach maupun procedural programming every program start with function top down approach Basic Terminology and Concepts Referential transparencyDalam matematika Referential transparency adalah properti yang memungkinkan kita mengganti ekspresi dengan nilainya dan tidak mengubah hasil dari apa pun yang kita lakukan Sebagai contoh menggunakan Javascript let x menjadilet x atau lebih baik menjadilet x untuk menghemat waktu eksekusi ini memanfaatkan fakta bahwa semua ekspresi dan fungsi matematika menurut definisinya adalah transparan secara referensial Modular approachModular approach adalah proses pengelompokan program komputer menjadi sub program terpisah menggunakan functions dimana functions ini bisa digunakan di aplikasi lain atau functions lainnya Desain modular dapat meningkatkan produktivitas Modul kecil dapat dikodekan dengan lebih cepat dan memiliki peluang lebih besar untuk digunakan kembali DRY Don T RepeaT YourselF yang tentunya mengarah pada pengembangan program yang lebih cepat Selain itu modul dapat diuji secara terpisah unit testing yang membantu kita mengurangi waktu yang dihabiskan untuk pengujian unit dan debugging MaintainabilityMaintainability adalah istilah sederhana yang berarti pemrograman FP lebih mudah dipelihara karena kita tidak perlu khawatir secara tidak sengaja mengubah apa pun di luar fungsi yang diberikan First class FunctionFirst class Function adalah definisi yang dikaitkan dengan entitas bahasa pemrograman yang tidak memiliki batasan dalam penggunaannya Oleh karena itu first class function dapat muncul di mana saja dalam program di JavaScript first class function adalah function yang berarti kita dapat menyimpannya dalam variabel objek dan array Sebagai contoh menggunakan Javascript let isOdd n gt return n dengan higher order functionlet isOdd n gt return n let arr let oddArray arr gt let proxyArr imperative approach arr forEach el gt isOdd el proxyArr push el return proxyArr console log oddArray arr dengan filter no imperative approach let isOdd n gt return n let numbers let oddNumbers numbers filter isOdd console log oddNumbers ClosureClosures adalah fungsi dalam yang dapat mengakses variabel dari fungsi induk bahkan setelah fungsi induk dijalankan Contoh closure ada pada bagian higher order function diatas Pure Function Accessor Method Pure Function adalah fungsi yang masukannya dideklarasikan sebagai masukan dan tidak ada satupun yang harus disembunyikan outputnya juga dideklarasikan sebagai output Pure Function bekerja berdasarkan parameternya Tidak efisien jika tidak me return apapun Selain itu ia menawarkan return yang sama untuk parameter yang diberikan Contoh pure function pada Javascript function pure a b return a b Impure Function Mutator Method Impure Function adalah kebalikan dari pure function Fungsi ini memiliki input atau output tersembunyi itu disebut impure Impure Function tidak dapat digunakan atau diuji secara terpisah karena memiliki ketergantungan Contoh impure function pada Javascript let z function impure z z Function CompositionFunction Composition adalah proses menggabungkan fungsi atau lebih untuk membuat yang baru Shared StateShared State adalah state bisa berupa variabel ataupun objek yang dibagikan Side EffectsSide Effects adalah efek samping setiap perubahan keadaan yang terjadi di luar function yang dipanggil Tujuan terbesar dari setiap functional programming language adalah meminimalkan efek samping dengan memisahkannya dari kode perangkat lunak lainnya Dalam functional programming sangat penting untuk menghilangkan efek samping dari sisa logika pemrograman Kenapa Functional Programming Secara general alasan kenapa kita harus memilih functional programming karena paradigma ini powerful expressive dan fun contohnya menggunakan fungsi filter dari javascript sebelumnya itu fun dan expressive loh kenapa expressive karena kita sudah tau bagaimana mengoperasikan fungsinya Benefit lainnya Memungkinkan kita menghindari masalah dan kesalahan yang membingungkan dalam kode expressive fun Lebih mudah menguji dan menjalankan unit testing dan debugging powerfull fun Pemrosesan Paralel dan Concurrency powerfull Hot code deployment and fault tolerance powerfull Menawarkan modularitas yang lebih baik dengan kode yang lebih pendek powerfull fun expressive Meningkatkan produktivitas fun Mendukung Nested Functions powerfull Functional construction seperti Map Filter Reduce dll fun expressive Memungkinkan penggunaan Lambda Calculus secara efektif powerfull TamatSekian yang bisa saya sampaikan mengenai Functional Programming Divide and Conquer Terima kasih buat yang sudah baca ️️️Untuk penjelasan mengenai functional programming lainnya saya sangat merekomendasikan slide di url berikut ini Functional Programming Forever 2021-04-27 14:14:13
海外TECH DEV Community How FirstPort manage GitHub, using code stored in GitHub https://dev.to/ghostinthewire5/how-firstport-manage-github-using-code-stored-in-github-41f6 How FirstPort manage GitHub using code stored in GitHub IntroductionAs many of you will already know I recently started an exciting new role as Head of Technology at FirstPort having previously been at a great consultancy called DevOpsGroup A key part of my role is delivering FirstPort s vision of People First technology To do this it is imperative that I select the right technology to underpin the delivery of services that help make customers lives easier Today I want to talk about my selection of GitHub Enterprise GitHub is a best in breed secure collaborative code hosting platform with built in CI CD capabilities with over million users Many organisations use it and all of them have to manage users repositories branch rules and much more Standardising all of this is quite challenging and involves creating things like CLI tools scripts and other ways to try to automate how people deal with GitHub Here at FirstPort I decided to use Terraform to manage and standardise all of the repository and user management and today I want to share with you how we are doing this Team and user managementIf you are using GitHub enterprise you will probably use Single Sign on SSO This does the job but isn t great especially when having to manage collaborators outside of your Identity Provider However you can use Terraform to manage sync groups This still leaves you to manage repositories labels pull requests all manually In our case I decided to use Terraform s GitHub provider to automate most of this work Firstly I created the teams Creates a parent teamresource github team engineering name engineering description This is a parent team privacy closed Creates a sub team of front end developersresource github team frontend name frontend description This is a sub team parent team id github team engineering id privacy closed Every time we have someone new join anyone at FirstPort can open a PR and invite them to the team Invites a user to the organizationresource github membership anewstarter username firstportuser role member Adds the user to a teamresource github team membership frontend firstportuser username github membership firstportuser username team id github team frontend id role maintainer This will run in a GitHub Actions workflow and the user will receive an invite to join our organisation Repository creationThis is probably the main reason why I decided to use Terraform for managing GitHub If repositories aren t standardised this can create a chaotic situation if the way engineers open issues raise PRs etc is different in every repository To avoid this I decided to create most of our repositories in the same way A few things were very important to us that every repository had to have Let s go through the mains ones Release notesI wanted to provide a way to be able to easily create release notes to enhance transparency on what we are delivering I chose to use a tool called Release Drafter in our workflow I wanted to configure how labels would be used in every repository and for that we standardised all labels across all repositories I use docs dependencies bug feature and maintenance Every time someone opens a PR they need to select at least one of these labels to define how this PR is categorised This is enforced using the Enforce Label Action When a PR is merged I use the GitHub Action release drafter which creates a draft release with the commits from the PR into one of those categories This helps us to create release notes for all of our services This is how the release notes would look like Every time someone creates a new repo the release drafter comes pre configured and you can start enjoying good release notes without any effort Branch protectionSetting up rules for when you can merge a branch is very important for code quality and in our case for legal reasons at FirstPort we deal with personal user data so all changes must go through strict code quality checks GitHub gives the possibility for you to configure branch protection rules to solve that I wanted to define the same set of basic branch protection for all repositories This was easily solved with our Terraform module Terraform moduleTo achieve all of this I created a Terraform module that manages users teams and repositories Here is an example on how we use the module module my firstport repo source modules repo version gt name my firstport repo description A firstport repository description visibility private delete branch on merge true vulnerability alerts true teams data github team engineering id push collaborators data github user external username push labels type bug daa type docs ff type feature aeeef type maintenance afda type dependencies d branch protection master enforce admins true push restrictions required status checks strict true contexts required pull request reviews dismiss stale reviews true require code owner reviews true dismissal restrictions GitHub ActionsGitHub Actions is our CI tool of choice GitHub Actions is a hosted runner service provided by GitHub Any user can write individual tasks called actions and put them together into a workflow These workflows can trigger off numerous events such as pull requests comments labels releases and so forth I think of it as having a box of LEGO bricks that can be put together as needed I can build a space ship or a pirate ship as my heart desires Users are free to write their own actions or consume them from the GitHub Marketplace For example the action that performs code checkout is written by GitHub and is on the Marketplace For a more in depth introduction to GitHub Actions I suggest reading the Getting started with GitHub Actions documentation For the purpose of this article I am using GitHub Actions to construct a workflow to provide CI functionality There is one workflow that runs on every PR name Terraform Planon pull requestjobs terraform name Terraform runs on ubuntu latest env ARM CLIENT ID secrets CLIENT ID ARM CLIENT SECRET secrets GH TERRAFORM PRD ARM SUBSCRIPTION ID secrets SUB ID ARM TENANT ID secrets TENANT ID ARM ACCESS KEY secrets GH TERRAFORM PRD STATE BLOB KEY steps name Checkout uses actions checkout master name Security Scan uses triat terraform security scan master env GITHUB TOKEN secrets GITHUB TOKEN name Lint Code Base uses github super linter master env GITHUB TOKEN secrets GH TOKEN VALIDATE ALL CODEBASE true VALIDATE MD true VALIDATE TERRAFORM true uses hashicorp setup terraform master with terraform version latest name Terraform Format id fmt run terraform fmt check name Terraform Init id init run terraform init name Terraform Validate id validate run terraform validate no color env TF VAR github token secrets GH TOKEN name Terraform Plan id plan run terraform plan no color continue on error true env TF VAR github token secrets GH TOKEN uses actions github script master env PLAN terraform n steps plan outputs stdout with github token secrets GH TOKEN script const output Terraform Security Scan Success The configuration is secure Terraform Format and Style steps fmt outcome Terraform Initialization ️ steps init outcome Terraform Validation steps validate outputs stdout Terraform Plan steps plan outcome lt details gt lt summary gt Show Plan lt summary gt process env PLAN lt details gt Pusher github actor Action github event name Working Directory env tf actions working dir Workflow github workflow github issues createComment issue number context issue number owner context repo owner repo context repo repo body output name Terraform Plan Status if steps plan outcome failure run exit On a merge we run the following workflow name Terraform Applyon push branches mainjobs terraform name Apply runs on ubuntu latest env ARM CLIENT ID secrets CLIENT ID ARM CLIENT SECRET secrets GH TERRAFORM PRD ARM SUBSCRIPTION ID secrets SUB ID ARM TENANT ID secrets TENANT ID ARM ACCESS KEY secrets GH TERRAFORM PRD STATE BLOB KEY steps name Checkout uses actions checkout master uses hashicorp setup terraform master with terraform version name Terraform Init id init run terraform init name Terraform Apply id apply run terraform apply auto approve input false env TF VAR github token secrets GH TOKEN Release Drafter is set up as follows name Release Drafteron push branches mainjobs update release draft runs on ubuntu latest steps uses release drafter release drafter master env GITHUB TOKEN secrets GH TOKEN with the following YAML for config categories title Features labels feature title Bug Fixes labels bug title Maintenance label maintenance title Docs label docs title ️Dependencies label dependencies change template TITLE AUTHOR NUMBER change title escapes lt amp You can add and to disable mentions and add to disable code blocks template Changes CHANGESTo ensure everything is captured in the release notes we also use the Enforce Label Action name Enforce PR labelson pull request types labeled unlabeled opened edited synchronize jobs enforce label runs on ubuntu latest steps uses yogevbd enforce label action master with REQUIRED LABELS ANY bug docs feature maintenance dependencies REQUIRED LABELS ANY DESCRIPTION Select at least one label bug docs feature maintenance dependencies This is what you see in the Pull Request Tab each time the PR workflow runs Allowing you to quickly see if a PR can be merged We also push this information into Microsoft Teams using the GitHub Integration App DevSecOpsAn additional benefit of using a CI workflow is adding automated tests In this scenario I ve added a step leveraging tfsec to scan for static code vulnerabilities In the example below tfsec warns against creating an Azure network security rule which is fully open This will halt and fail the workflow unless I provide an ignore comment to accept the warning SummaryIn this post I explored using GitHub Actions as a CI workflow that could build and maintain a GitHub organization including users teams permissions security etc I started by generating a new GitHub repository then wrote the GitHub Workflow files and finally started testing the CI workflow and introducing small incremental changes Using Terraform to manage GitHub organisations can really help your developer teams to onboard quickly and securely I hope I could help you learn something new today and share how we do things here at FirstPort Any questions get in touch on Twitter Andrew MVP ghostinthewire Azure Readiness ChecklistAre you ready to go to prod on Azure Use this checklist to find out azurechecklist comCall for contributors Help make this THE go to list for Azure AzureDevOps OpenSource PLS RT ️ AM Nov 2021-04-27 14:08:07
海外TECH DEV Community 5 Array Methods You Should Know 🚀 https://dev.to/garvitmotwani/5-array-methods-you-should-know-22ff Array Methods You Should Know Array methods are used in almost every JavaScript project nowadays which also means that everybody should know the important ones So I will give you array methods that you should know So let s get started forEachThis is a common one and a vital one The forEach method executes a given function on every element from an array So I would try to explain it through some code const nums nums forEach arrFunc function arrFunc item index arr console log item Output So as you can see I created an array nums and then called the forEach method and then declared a callback function called arrFunc so this is where it all happens you see the forEach needs parameters first one is item which are the elements which in our case are and then the second parameter is index which is the index of the item in the array and second is the arr which is the array itself although you don t use this parameter often So in the callback function you can just type the things you want with every single element on the array It is like a for loop on the base but not much like it Keep in mind that you can use the forEach method with arrow functions which is always the recommended way const nums nums forEach item index arr gt console log item concatThe concat method allows you to merge or more arrays together without modifying the arrays but instead creating a new one It is a bit easy and useful and it is as simple as it sounds in code too So let s say we have two arrays const x const y So if you want to merge them you can do that easily with this method like this const z x concat y Now If you console log the z arrayconsole log z You will receive If you want to concat more than arrays you can just add it as the second parameter and if more you can add more parameters like this const z x concat y q v You can also use concat method like the push method like this const x const z x concat console log z Output includesThe includes method allows you to find if an element is included inside an array Let s try understand it with code const names Garvit Lorenzo Adam const outputRes names includes Adam console log outputRes Output trueSo here as you can see we have declared an array called names and we have the names Garvit Lorenzo and Adam stored in them now in the next line we declared a variable called outputRes in which we typed if the array names includes Adam then the output will be true prooving that the array includes that and if we wrote something like John the output will be false prooving that John is not in that array spliceThe splice method allows you to remove or replace an existing element of an array simple right Let s try to learn more about this in code const numbers numbers splice console log numbers Output So as you can see I have created an array called numbers and entered some numbers in it and then I typed numbers splice so here the first parameter is the starting index from where we want to start removing elements which in our case was and then the second parameter that we passed was that how many elements we want to remove which in our case was Now take a look at this const numbers const modifiedArr numbers splice console log modifiedArr Output Not much of a difference right but still the output has changed that is because we have stored the splice array in a variable so It is like putting all the deleted element in the modifiedArr If you want to replace the existing elements you can just add the elements as another parameter const numbers numbers splice console log numbers Output reverseThe reverse method allows you to reverse an array this is an easy one lets see how that works in code const numbers numbers reverse console log numbers Output References Florin Pop s Array Methods PlaylistMDN Web Docs ️Giveaway ️We are giving away any course you need on Udemy Any price any course Steps to enter the giveaway gt React to this post gt Subscribe to our Newsletter lt Very important gt Follow me on Twitter lt x Chances of winningThe winner will be announced on May Via TwitterThank you very much for reading this article PLEASE LIKE SHARE AND COMMENTFollow me on Dev and TwitterYou Should also check JavaScript Interview Questions With Answers DevLorenzo・Apr ・ min read javascript webdev career productivity by my friend devlorenzo Subscribe to our newsletter to receive our weekly recap directly on your email Join us on Discord to participate in hackathons with us participate in our giveaways Happy Coding 2021-04-27 14:04:51
海外TECH DEV Community Intro to Amazon S3 https://dev.to/mtliendo/intro-to-amazon-s3-1il1 Intro to Amazon S Simple Storage Service or SWhether it s Dropbox Google Drive iCloud or that folder on your Desktop that has way too much stuff in it you know the one the idea of storing data somewhere and being able to access it later on isn t anything new S on its surface can be seem like the services above However going deeper it is much more versatileーbut more on that in a later post To get started you ll need an AWS account If you don t have one I created a video showing how you can sign up With that out of the way let s define some terms Need to know termsBucket This is a grouping of all the “stuff you d like to store There s no limit to the amount of stuff you can put in a bucket Also even though buckets are created in a specific region of your choosing the name you decide to give them has to be globally unique Object Notice above how I said a bucket contains “stuff Well S calls it an object This an item you d like to put in a bucket This can be any type of data text JSON a picture or video A single object s size can be as large as terabytes ️Creating Your First BucketCreating an S bucket is fairly straightforward with one small gotcha that we ll address as we go To get started search for S once you re logged into your AWS account or click this link From here we can follow these steps to create our first bucket Click the orange Create Bucket button on the right side of the pageGive our bucket a name remember it has to be globally unique Ensure the region is a location generally close to youUncheck Block all public access Of the nested checkboxes check the first and leave the last uncheckedIn the ️warning area click the box to acknowledge the bucket being publicAt the bottom of the page select Create bucketIf all went well you should be looking at a screen with your bucket listed in it“What did we do in step Great question glad you asked AWS has a concept known as Least Privilege This means services should only be able to do exactly what we need them to do and nothing more So when we tell AWS we want a bucket that can contain anything in it to be publicly available on the internet they want to ensure we know what we re doing to avoid any security issues In addition when it comes to making items public there are a few ways to do it Leaving those two boxes unchecked says “we re going to write a policy a snippet of JSON that tells you exactly how I want to make this bucket public If you haven t already go ahead and click on your bucket and select the Permissions tab Down a bit we ll come across a section that says Bucket policy Click the Edit button then click Policy examples On the new tab that opened up select the Granting read only permissions to an anonymous user link as shown in the screenshot belowNow copy the JSON snippet and head back to the tab with your S bucket Paste in the JSON and click “Save changes at the bottom Make sure to replace DOC EXAMPLE BUCKET with your bucket nameMake sure there is a at the end of your bucket name ️Yes I could ve just given you a link or the snippet to paste but knowing where to click in AWS is a skill in itself “What does this policy aka snippet of JSON do Excellent question Here s a breakdown of what each part is doing️Remember when I mentioned Least Privilege The Action part in our policy should only list what we want our resource to allow Back at the top of the page select the Objects tab and select Upload On the next page feel free to drag in a photo remember this is public and click Upload at the bottom when you re done Once you get an “Upload Succeeded message click the Close button on the right side of the page Congratulations You ve just created a bucket and uploaded an item to it To verify click the photo link and on the next page note the Object URL This is the public link to view your image Want to try it out on a webpage Feel free to head to this Codesandbox and update the link on line PricingIn S you pay based on factors The amount of data in a bucketThe requests made to query get or change copy delete update a bucket ️The pricing is also specific to whatever region the bucket is in but is similar across most regions For example in the region us east for an S bucket with GB of data in it being fetched times month you would spend month RecapToday we explored Simple Storage Service We created a bucket of images and displayed them on a webpage This is only scratching the surface of what S can do In many tutorials and blogs this is usually where they tell you how to host a static website on S However I m not going to do that The process of hosting static webpages used to be really involved and error prone due to the number of services needed With that said I hope you still use S to host your static assets photos movies etc AWS released the Amplify Console which greatly simplifies the process of hosting static sites So I ll leave you with a video on how to use the Amplify Console to deploy a react application to AWS spoiler alert it s really easy Thanks for following along and I look forward to seeing you next time when I talk about one of the most buzzword cloud services out there AWS Lambda 2021-04-27 14:02:23
Apple AppleInsider - Frontpage News Apple highlights three financial wellness apps that help marginalized communities https://appleinsider.com/articles/21/04/27/apple-highlights-three-financial-wellness-apps-that-help-marginalized-communities?utm_medium=rss Apple highlights three financial wellness apps that help marginalized communitiesIn what Apple calls a WWDC Spotlight it has selected three apps that are targeted at financial wellness and education Financial wellness apps help marginalized communitiesApple s Worldwide Developer s Conference or WWDC is in June and Apple usually takes some time to discuss some of the innovations being shared by developers Tuesday s spotlight focuses on financial apps specifically ones that help the people who need it most Read more 2021-04-27 14:49:35
Apple AppleInsider - Frontpage News Hands on: Twelve South Forte is a MagSafe charging stand for iPhone & AirPods https://appleinsider.com/articles/21/04/27/hands-on-twelve-south-forte-is-a-magsafe-charging-stand-for-iphone-airpods?utm_medium=rss Hands on Twelve South Forte is a MagSafe charging stand for iPhone amp AirPodsTwelve South gave us an early hands on of its first MagSafe charging stand Forte that is well suited for not only your iPhone but your AirPods as well Forte MagSafe chargerForte a product name once bestowed on its previous high end Apple exclusive charger is now being used for a new MagSafe charging stand Read more 2021-04-27 14:09:41
Apple AppleInsider - Frontpage News Hands on with Nomad's new Base Station Mini wireless charger https://appleinsider.com/articles/21/04/27/hands-on-with-nomads-new-base-station-mini-wireless-charger?utm_medium=rss Hands on with Nomad x s new Base Station Mini wireless chargerNomad has released a new model of its popular Base Station lineup this time a solo wireless charging pad We go hands on for the device s launch Base Station MiniBase Station Mini is very similar to Nomad s Base Station Base Station Hub as well as its Base Station Pro They all have a very similar design aesthetic and not dissimilar materials Read more 2021-04-27 14:52:34
Apple AppleInsider - Frontpage News Updated Eve Energy now available with Thread support https://appleinsider.com/articles/21/04/27/updated-eve-energy-now-available-with-thread-support?utm_medium=rss Updated Eve Energy now available with Thread supportOn Tuesday Eve officially launched the latest fourth generation model of the Eve Energy HomeKit smart plug ーcomplete with Thread support Eve Energy fourth genThe smart home purveyor kept the design of the same as the last generation device with the only notable change the addition of Thread Read more 2021-04-27 14:23:26
Apple AppleInsider - Frontpage News Want to protect your new AirTag? Here are the accessories you need https://appleinsider.com/articles/21/04/26/want-to-protect-your-new-airtag-heres-the-accessories-you-need?utm_medium=rss Want to protect your new AirTag Here are the accessories you needIf you re buying an AirTag at launch you ll probably want to acquire a holder for the small tracker Here s a compilation of accessories for AirTag that you can buy to carry around and attach it to the things you don t want to lose AirTag s design is striking yet simple consisting of a round tag with a rim While the coin like device is beautifully crafted by Apple it differs from other trackers on the market as it doesn t include any built in attachment points Other tags from firms like Tile and Chipolo include holes and spaces to hook or tie the tags onto an item or keychain however AirTag doesn t offer this capability out of the box Naturally for an Apple device there s a large number of accessories already produced for the AirTag which can help you attach it to practically anything you want within reason Read more 2021-04-27 14:34:57
海外TECH Engadget Master Microsoft Azure, Ansible and Git for $30 with four prep courses https://www.engadget.com/microsoft-azure-training-bundle-145534086.html content 2021-04-27 14:55:34
海外TECH Engadget Deepfake satellite images pose serious military and political challenges https://www.engadget.com/deepfake-satellite-imagery-144145142.html military 2021-04-27 14:41:45
海外TECH Network World Weekly internet health check, US and worldwide https://www.networkworld.com/article/3534130/covid-19-weekly-health-check-of-isps-cloud-providers-and-conferencing-services.html#tk.rss_all Weekly internet health check US and worldwide The reliability of services delivered by ISPs cloud providers and conferencing services a k a unified communications as a service UCaaS is an indication of how well served businesses are via the internet ThousandEyes is monitoring how these providers are handling the performance challenges they face It will provide Network World a roundup of interesting events of the week in the delivery of these services and Network World will provide a summary here Stop back next week for another update and see more details here Get regularly scheduled insights by signing up for Network World newsletters To read this article in full please click here 2021-04-27 14:47:00
海外科学 NYT > Science ‘This Is a Catastrophe.’ In India, Illness Is Everywhere. https://www.nytimes.com/2021/04/27/world/asia/India-delhi-covid-cases.html This Is a Catastrophe In India Illness Is Everywhere As India suffers the world s worst coronavirus crisis our New Delhi bureau chief describes the fear of living amid a disease spreading at such scale and speed 2021-04-27 14:42:43
海外科学 NYT > Science These Materials Could Make Science Fiction a Reality https://www.nytimes.com/2021/04/27/science/metamaterials-technology.html fiction 2021-04-27 14:56:08
金融 RSS FILE - 日本証券業協会 新型コロナウイルス感染症への証券関係機関等・各証券会社の対応について(リンク集) https://www.jsda.or.jp/shinchaku/coronavirus/link.html 新型コロナウイルス 2021-04-27 14:30:00
海外ニュース Japan Times latest articles Medical supplies pour into India as COVID-19 deaths approach 200,000 https://www.japantimes.co.jp/news/2021/04/27/asia-pacific/india-coronavirus-supplies/ worldwide 2021-04-28 00:54:50
海外ニュース Japan Times latest articles Fighting erupts in Myanmar as junta says it will ‘consider’ ASEAN plan https://www.japantimes.co.jp/news/2021/04/27/asia-pacific/myanmar-violent-clashes/ Fighting erupts in Myanmar as junta says it will consider ASEAN planSoutheast Asian leaders had said over the weekend they had reached a consensus with the junta on steps to end violence and promote dialogue between 2021-04-28 00:48:45
海外ニュース Japan Times latest articles Japan to miss key 2% inflation target again as policy coordination loosened https://www.japantimes.co.jp/news/2021/04/27/business/economy-business/boj-haruhiko-kuroda-japan-economy-abenomics/ Japan to miss key inflation target again as policy coordination loosened It s hugely symbolic that even Kuroda can t hit the target after a decade said a chief economist and former Bank of Japan official 2021-04-28 00:20:10
海外ニュース Japan Times latest articles When the CEO’s son makes $3 million, I worry https://www.japantimes.co.jp/opinion/2021/04/27/commentary/world-commentary/sec-corruption-enron-skechers-stocks/ company 2021-04-28 00:11:49
海外ニュース Japan Times latest articles Economic issues, once divisive, now bind Japan and the U.S. https://www.japantimes.co.jp/opinion/2021/04/27/commentary/japan-commentary/japan-u-s-climate-change-covid-19-global-economy/ economic 2021-04-28 00:09:25
海外ニュース Japan Times latest articles America’s undimmed global cultural reach continues https://www.japantimes.co.jp/opinion/2021/04/27/commentary/world-commentary/u-s-qanon-donald-trump-history-culture/ clearest 2021-04-28 00:08:22
ニュース BBC News - Home Labour accuses Boris Johnson of lying over flat renovation costs https://www.bbc.co.uk/news/uk-politics-56903838 downing 2021-04-27 14:46:12
ニュース BBC News - Home Crawley College: 'Heroic' staff tackled armed suspect https://www.bbc.co.uk/news/uk-england-sussex-56898742 police 2021-04-27 14:57:50
ニュース BBC News - Home Teams to be allowed 26-man Euro 2020 squads https://www.bbc.co.uk/sport/football/56905822 championship 2021-04-27 14:32:49
北海道 北海道新聞 中国空母、東シナ海へ北上 防衛省、沖縄通過で警戒 https://www.hokkaido-np.co.jp/article/538237/ 中国海軍 2021-04-27 23:16:00
IT 気になる、記になる… Apple、「macOS 10.14 Mojave」向けに「セキュリティアップデート 2021-003」をリリース https://taisy0.com/2021/04/28/139784.html apple 2021-04-27 15:55:17
IT 気になる、記になる… Apple、「macOS 10.15 Catalina」向けに「セキュリティアップデート 2021-002」をリリース https://taisy0.com/2021/04/28/139781.html apple 2021-04-27 15:16:46
IT 気になる、記になる… Fitbit、ファッション性を重視した新型アクティビティトラッカー「Fitbit Luxe」の予約受付を開始 https://taisy0.com/2021/04/28/139776.html fitbit 2021-04-27 15:02:13
AWS AWS DevOps Blog CDK Corner – April 2021 https://aws.amazon.com/blogs/devops/cdk-corner-april-2021/ CDK Corner April Social Community Engagement We re getting closer and closer to CDK Day with the event receiving CFP submissions The cdkday schedule is now available to plan out your conference day Updates to the CDK Constructs promoted to General Availability Promoting a module to stable General Availability is always a cause for celebration Great job to … 2021-04-27 15:28:20
js JavaScriptタグが付けられた新着投稿 - Qiita PAYJP 設定引き数一覧 リファレンスより https://qiita.com/takuo_maeda/items/9ffda3c806e8344611ff 2021-04-28 00:09:08
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) pythonライブラリnltkをgaeで使いたい https://teratail.com/questions/335498?rss=all pythonライブラリnltkをgaeで使いたい前提・実現したいことGAEGoogleAppEngineでnltkを使用したpythonのスクリプトを実行したいと思っています。 2021-04-28 00:41:26
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) サクラエデイタとvscode はセキュリティ面の安全性はどちらも変わらないでしょうか。 https://teratail.com/questions/335497?rss=all 会社で推奨されているのは、サクラエデイタなのですが、vscodenbspを使いたいと考えてます。 2021-04-28 00:37:40
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) JavaScriptをdiscordPythonに変える https://teratail.com/questions/335496?rss=all 2021-04-28 00:27:46
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) kotlinでオセロを作っています https://teratail.com/questions/335495?rss=all kotlinでオセロを作っています下記のエラーメッセージがでてしまいます。 2021-04-28 00:27:32
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) [AOJ]ITP1_6_A Presentation Error(空白エラー)で行き詰まりました https://teratail.com/questions/335494?rss=all 数列の要素の間につの空白を入れて下さい最後の数の後に空白は入らないことに注意して下さい。 2021-04-28 00:18:19
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 画像選択せずに「id」設定のみでImageViewを配置する方法を知りたい https://teratail.com/questions/335493?rss=all その書籍の中で具体的には章「じゃんけん」のp、画像を選択せずに「id」と「配置する位置」のみを設定して「アクティビティ」に「ImageView」を貼り付けています。 2021-04-28 00:18:17
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) ExtendScript DebuggerにおけるVScodeの設定 https://teratail.com/questions/335492?rss=all 2021-04-28 00:17:54
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) railsでcouldn't find ~ without an IDのエラーを解消したい。 https://teratail.com/questions/335491?rss=all railsでcouldnxtfindwithoutanIDのエラーを解消したい。 2021-04-28 00:17:49
Ruby Rubyタグが付けられた新着投稿 - Qiita アプリの一括削除 https://qiita.com/konchim/items/15257b22eec81e41d5d1 cdrmrf 2021-04-28 00:10:24
AWS AWSタグが付けられた新着投稿 - Qiita linuxのiptablesでproxyサーバーを簡単に実現する方法 https://qiita.com/awszhoubo/items/cdcda56baa22151352a4 ローカルネットワーク内のpcは、proxyサーバーを経由して、外部インターネットにアクセスします。 2021-04-28 00:24:50
Ruby Railsタグが付けられた新着投稿 - Qiita アプリの一括削除 https://qiita.com/konchim/items/15257b22eec81e41d5d1 cdrmrf 2021-04-28 00:10:24
海外TECH DEV Community Why Community is Important for Developers https://dev.to/ceeoreo/why-community-is-important-for-developers-25g8 Why Community is Important for DevelopersThere are a plethora of developer communities out there Countless times I ve been encouraged to join some online or in person community for developers and I m sure you have too After listening to the episode of the Version One podcast I was reminded of the value of community The second episode of the Version One podcast features guest Guillermo Rauch CEO and Co founder of Vercel When discussing how he started coding Guillermo mentioned an online forum which played a huge part in his growth as a developer As Guillermo s experience demonstrates community can be a huge catalyst for growth as a developer By why is that the case And where can you find said communities Why you need to invest in communityCoding isn t always an easy task There are multiple hurdles that many people confront along their developer journey Running into difficult errors dealing with difficult coding concepts job searching career growth the list could go on forever It becomes so much easier to deal with these things when you have a helpful community to lean on I started finding different communities that were helping me figure things out And that also whenever I would figure something out I would contribute back too When you find a community that fits your interests and career goals you ll have a place where you can turn to ask questions and get advice from developers all over the world You can also share your own insights and help others along the way As time goes on your developer network will continue to grow and you ll become a better developer This is why it s so important to invest in community no matter what skill level you re at Where to find the right community for youNow that you know community is so valuable it s time to actually find one for yourself You don t need to be part of every single one you come across That can easily become overwhelming Focus on actively participating in just a few If it s safe to do so in the area where you live you can look around for local meetups and communities Check websites like Meetup and search for groups using keywords that are related to whatever language or technology you would like to be more involved with Thankfully we have social media and platforms like Discord and Slack which enable remote community building Twitter is a developer hot spot It s a great place to go to share what you re working on and learning and to ask and answer questions It s good to know though that Twitter isn t always a safe space But it still holds a ton of value To find Discord and Slack communities search insert language or tech stack of interest communities on Discord Slack on Google It also helps to ask developers you already know for recommendations When you find a community that matches your interests keep an eye out for active moderators and a Code of Conduct Both of these things ensure the safety of community members Of course this isn t absolute and people with bad intentions may still slip in But having moderators and a Code of Conduct that is heavily promoted means that your online safety is being prioritized and that s very important ConclusionIt s clear that being part of a community can do wonders for your growth as a developer Searching for joining and participating in developer communities online or in person if it s safe will be well worth the effort and time you invest Guillermo s podcast episode reminded me of this There s much more to learn from his journey to becoming a startup founder So make sure to give his Version One interview a listen 2021-04-27 15:54:36
海外TECH DEV Community Introduction To JavaScript Promises https://dev.to/boiliev/introduction-to-javascript-promises-2oed Introduction To JavaScript Promises IntroductionA Promise is an object representing the eventual completion or failure of an async operation A promise is a returned object to which you attach callbacks instead of passing callback into a function new PromiseIn order to make a new Promise you need to write new Promise and then it will expect you to pass in a function with two arguments which are functions The first one represents the resolution of this promise and the second one the rejection of this promise const requestPromise url gt return new Promise resolve rejects gt const delay Math floor Math random setTimeout gt if delay gt reject Connection Timeout else resolve Here is your fake data from url delay Now in order to call the function multiple times with different URLs we need to use the then method The then method returns data if the async request is returned But if the operation is failed we must use the catch method This is how it should look like requestPromise reddit com api chicken page then gt console log PAGE WORKED requestPromise reddit com api chicken page then gt console log PAGE WORKED requestPromise reddit com api chicken page then gt console log PAGE WORKED catch gt console log PAGE ERROR catch gt console log PAGE ERROR catch gt console log PAGE ERROR As you can notice this is very long and repetitive We can make it shorter and cleaner by using only one catch In order for this to work we need to return a promise from within our callback requestPromise reddit com api chicken page then gt console log PAGE WORKED return requestPromise reddit com api chicken page then gt console log PAGE WORKED return requestPromise reddit com api chicken page then gt console log PAGE WORKED catch gt console log REQUEST FAILED Promises are resolved and rejected with values requestPromise reddit com api chicken page then data gt console log PAGE WORKED console log data return requestPromise reddit com api chicken page catch err gt console log REQUEST FAILED console log err IF IT WORKS IT WILL PRINT PAGE WORKED Here is your fake data from reddit com api chicken page IF IT DOESN T WORK REQUEST FAILED Connection Timeout This is coming from a function async FunctionsA newer and cleaner syntax for working with async code It s still the same thing as a promise but it s prettier There are two keywords that you need to know async keyword Async functions always return a promise If the function returns a value the promise will be resolved with that value If the function throws an exception the promise will be rejected async function hello gt returns a promise even if emptyconst sing async gt gt we can use async arrow functionsHere are some examples const login async username password gt if username password throw Missing Credentials if password password return Welcome throw Invalid Password login demonslayer then msg gt console log LOGGED IN console log msg catch err gt console log ERROR console log err Returns ERROR Missing Credentialslogin demonslayer slayerdemon then msg gt console log LOGGED IN console log msg catch err gt console log ERROR console log err Returns ERROR Invalid Passwordlogin demonslayer password then msg gt console log LOGGED IN console log msg catch err gt console log ERROR console log err Returns LOGGED IN WELCOME await keyword The await keyword is used inside of functions declared with async await will pause the execution of the function waiting for a promise to be resolved Here is an example with our function from earlier async function makeTwoRequests let data await requestPromise page console log data Returns lt gt Promise lt pending gt Here is your fake data from page ConclusionThis is pretty much the basics of JavaScript promises Let me know if this has helped you at all Any feedback will be greatly appreciated 2021-04-27 15:23:09
海外TECH DEV Community Amazing Image Hover Effect Using HTML & CSS https://dev.to/nikhil27b/amazing-image-hover-effect-using-html-css-4m76 Amazing Image Hover Effect Using HTML amp CSSHello Today I created an Amazing Image Hover Effect Using HTML amp CSS when you hover on the image it s changing blur amp grayscale also have some cubic bezier animation in this post I hope you like this also comments about your thoughts For more content follow me on Instagram developer nikhil If you want to more support me then buy me a coffee Thank you 2021-04-27 15:03:04
Apple AppleInsider - Frontpage News Mac developer poll illustrates demographics, favorite tools, and more https://appleinsider.com/articles/21/04/27/mac-developer-poll-illustrates-demographics-favorite-tools-and-more?utm_medium=rss Mac developer poll illustrates demographics favorite tools and moreA survey of Mac developers using popular commercial software breaks down info on demographics ways of working and other tidbits to paint a clearer picture of Mac developers While it isn t a scientific survey of Mac developers one company s poll could perhaps hint at the community s breakdownThe team behind Mac development software Git Tower surveyed users in March and April It included participants Read more 2021-04-27 15:54:34
Apple AppleInsider - Frontpage News Cellebrite removes iPhone data extraction from most capable product https://appleinsider.com/articles/21/04/27/cellebrite-removes-iphone-data-extraction-from-most-capable-product?utm_medium=rss Cellebrite removes iPhone data extraction from most capable productBecause of a crippling vulnerability Cellebrite disabled the iPhone data extraction feature on its Physical Analyzer tool Cellebrite Physical Analyzer no longer works with iPhoneCellebrite is a company that builds forensic devices used by law enforcement and governments These devices have been deployed around the world to gain access to data stored on iPhones and other smartphones Read more 2021-04-27 15:41:58
Apple AppleInsider - Frontpage News Time names Apple a 'Leader' in its 100 Most Influential Companies list https://appleinsider.com/articles/21/04/27/time-names-apple-a-leader-in-its-100-most-influential-companies-list?utm_medium=rss Time names Apple a x Leader x in its Most Influential Companies listTime magazine has curated a list of the most influential companies with Apple sharing a Leaders category alongside Nike Walgreens and the NBA Tim Cook is praised by Time magazineTime magazine has famously chosen a person of the year since and its Most Influential People list has previously included Apple CEO Tim Cook Now for its first ever curated list of most influential companies it has included Apple as a whole Read more 2021-04-27 15:10:40
Apple AppleInsider - Frontpage News Apple debuts teaser for upcoming dark comedy 'Physical' https://appleinsider.com/articles/21/04/27/apple-debuts-teaser-for-upcoming-dark-comedy-physical?utm_medium=rss Apple debuts teaser for upcoming dark comedy x Physical x Apple TV has released a trailer for Physical a series that follows a determined housewife in s Southern California as she begins to build an aerobics empire Rose Byrne in PhysicalFollowing an initial announcement in February the new minute long trailer serves as a quick teaser to get viewers acquainted with the show It begins by showing the main character Sheila daydreaming about being a backup dancer to cope with her role as a dutiful housewife Read more 2021-04-27 15:01:33
海外TECH CodeProject Latest Articles Java on Azure: Adding Containers https://www.codeproject.com/Articles/5299822/Java-on-Azure-Adding-Containers storage 2021-04-27 15:11:00
海外科学 NYT > Science Blue Origin Challenges NASA Over SpaceX Moon Lander Deal https://www.nytimes.com/2021/04/26/science/spacex-moon-blue-origin.html lunar 2021-04-27 15:11:23
海外科学 NYT > Science ‘This Is a Catastrophe.’ In India, Illness Is Everywhere. https://www.nytimes.com/2021/04/27/world/asia/India-delhi-covid-cases.html This Is a Catastrophe In India Illness Is Everywhere As India suffers the world s worst coronavirus crisis our New Delhi bureau chief describes the fear of living amid a disease spreading at such scale and speed 2021-04-27 15:00:59
海外ニュース Japan Times latest articles Local governments scrap plans to host Tokyo Games training camps https://www.japantimes.co.jp/news/2021/04/27/national/olympics-camps-scrapped/ reactions 2021-04-28 02:00:48
海外ニュース Japan Times latest articles Billionaire founder of Nidec hands reins to ex-Nissan star https://www.japantimes.co.jp/news/2021/04/27/business/nidec-ceo-jun-seki/ family 2021-04-28 01:56:17
海外ニュース Japan Times latest articles A look at the COVID age’s wannabe platinum cards (and apps) https://www.japantimes.co.jp/news/2021/04/27/world/science-health-world/vaccination-passports/ A look at the COVID age s wannabe platinum cards and apps It is the latest status symbol Flash it at the people and you can get access to concerts sports arenas or long forbidden restaurant tables Some 2021-04-28 01:36:37
海外ニュース Japan Times latest articles Annual Japan diplomacy report targets Chinese military concerns but omits Taiwan https://www.japantimes.co.jp/news/2021/04/27/national/japan-china-bluebook/ Annual Japan diplomacy report targets Chinese military concerns but omits TaiwanThe report explained the outcome of the recent Suga Biden summit but made no reference to their joint statement which explicitly mentioned Taiwan 2021-04-28 01:35:27
海外ニュース Japan Times latest articles Medical supplies pour into India as COVID-19 deaths approach 200,000 https://www.japantimes.co.jp/news/2021/04/27/asia-pacific/india-coronavirus-supplies/ worldwide 2021-04-28 00:54:50
海外ニュース Japan Times latest articles Fighting erupts in Myanmar as junta says it will ‘consider’ ASEAN plan https://www.japantimes.co.jp/news/2021/04/27/asia-pacific/myanmar-violent-clashes/ Fighting erupts in Myanmar as junta says it will consider ASEAN planSoutheast Asian leaders had said over the weekend they had reached a consensus with the junta on steps to end violence and promote dialogue between 2021-04-28 00:48:45
海外ニュース Japan Times latest articles Japan to miss key 2% inflation target again as policy coordination loosened https://www.japantimes.co.jp/news/2021/04/27/business/economy-business/boj-haruhiko-kuroda-japan-economy-abenomics/ Japan to miss key inflation target again as policy coordination loosened It s hugely symbolic that even Kuroda can t hit the target after a decade said a chief economist and former Bank of Japan official 2021-04-28 00:20:10
海外ニュース Japan Times latest articles Masters winner Hideki Matsuyama to receive Prime Minister’s Award https://www.japantimes.co.jp/sports/2021/04/27/more-sports/golf/hideki-matsuyama-prime-ministers-award/ Masters winner Hideki Matsuyama to receive Prime Minister s AwardThe year old will become the th individual recipient of the honor after becoming the first Japanese man to win one of golf s four major tournaments 2021-04-28 01:10:25
海外ニュース Japan Times latest articles Japanese brewery re-creates feudal-era sake https://www.japantimes.co.jp/life/2021/04/27/food/feudal-era-sake/ sweet 2021-04-28 02:00:09
海外ニュース Japan Times latest articles When the CEO’s son makes $3 million, I worry https://www.japantimes.co.jp/opinion/2021/04/27/commentary/world-commentary/sec-corruption-enron-skechers-stocks/ company 2021-04-28 00:11:49
海外ニュース Japan Times latest articles Economic issues, once divisive, now bind Japan and the U.S. https://www.japantimes.co.jp/opinion/2021/04/27/commentary/japan-commentary/japan-u-s-climate-change-covid-19-global-economy/ economic 2021-04-28 00:09:25
海外ニュース Japan Times latest articles America’s undimmed global cultural reach continues https://www.japantimes.co.jp/opinion/2021/04/27/commentary/world-commentary/u-s-qanon-donald-trump-history-culture/ clearest 2021-04-28 00:08:22
ニュース BBC News - Home India Covid: Delhi builds makeshift funeral pyres as deaths climb https://www.bbc.co.uk/news/world-asia-india-56897970 capital 2021-04-27 15:17:56
ニュース BBC News - Home Arlene Foster: Letter of no confidence sent to DUP MLAs https://www.bbc.co.uk/news/uk-northern-ireland-56902771 arlene 2021-04-27 15:43:35
ニュース BBC News - Home Brexit: Tensions overshadow EU vote on UK trade deal https://www.bbc.co.uk/news/world-europe-56899831 ireland 2021-04-27 15:52:02
ニュース BBC News - Home Covid: When, where and how can I go on holiday? https://www.bbc.co.uk/news/explainers-52646738 covid 2021-04-27 15:18:02
AWS AWS Architecture Blog Journey to Adopt Cloud-Native Architecture Series: #3 – Improved Resilience and Standardized Observability https://aws.amazon.com/blogs/architecture/journey-to-adopt-cloud-native-architecture-series-3-improved-resilience-and-standardized-observability/ Journey to Adopt Cloud Native Architecture Series Improved Resilience and Standardized ObservabilityIn the last blog Maximizing System Throughput we talked about design patterns you can adopt to address immediate scaling challenges to provide a better customer experience In this blog we talk about architecture patterns to improve system resiliency why observability matters and how to build a holistic observability solution As a refresher from previous blogs … 2021-04-27 16:32:38
AWS AWS Partner Network (APN) Blog How to Strengthen Your Own AWS Practice with Help from an Experienced AWS Partner https://aws.amazon.com/blogs/apn/how-to-strengthen-your-own-aws-practice-with-help-from-an-experienced-aws-partner/ How to Strengthen Your Own AWS Practice with Help from an Experienced AWS PartnerWith more and more businesses investing in cloud products and solutions the time to power a sustainable cloud practice is now For technology solution providers it can be time consuming and costly to figure out how to build a cloud business that offers customers the best value and stands out from the rest Tech Data created a clearly defined path through its Cloud Practice Builder framework meant to streamline this journey for fellow AWS Partners 2021-04-27 16:06:18
AWS AWS Machine Learning Blog AWS DeepRacer device software now open source https://aws.amazon.com/blogs/machine-learning/aws-deepracer-device-software-now-open-source/ AWS DeepRacer device software now open sourceAWS DeepRacer is the fastest way to get started with machine learning ML You can train reinforcement learning RL models by using a th scale autonomous vehicle in a cloud based virtual simulator and compete for prizes and glory in the global AWS DeepRacer League Today we re expanding AWS DeepRacer s ability to provide fun hands on learning … 2021-04-27 16:39:39
AWS AWS How to Incorporate graph databases in .NET Applications with Amazon Neptune https://www.youtube.com/watch?v=YdHbIhvZLH0 How to Incorporate graph databases in NET Applications with Amazon NeptuneIn this video we will learn how to use Amazon Neptune in NET applications Amazon Neptune is a fast reliable fully managed graph database service that makes it easy to build and run applications that work with highly connected datasets The core of Amazon Neptune is a purpose built high performance graph database engine optimized for storing billions of relationships and querying the graph with milliseconds latency Learn more about Amazon Neptune Subscribe More AWS videos More AWS events videos AWS AmazonNeptune AWSDemo 2021-04-27 16:46:02
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) cloud9上でのsqlite3インストール https://teratail.com/questions/335501?rss=all cloud上でのsqliteインストール前提・実現したいことAWSでCloudを使用してローカルサーバーを起動させようとしたのですが、できません。 2021-04-28 01:28:59
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) [Unity]RigidBodyの"力"を取得したい https://teratail.com/questions/335500?rss=all UnityRigidBodyのquot力quotを取得したい前提・実現したいこと現在、物理パズルのようなゲームを作っているのですが、そこでrigidbodyの力を取得したい場面があり、力を取得する方法が分からず困っています。 2021-04-28 01:13:09
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Googleスプレッドシートの上から順番にSlackへ投稿 https://teratail.com/questions/335499?rss=all Googleスプレッドシートの上から順番にSlackへ投稿前提・実現したいこと・Googleスプレッドシートのシートの内容を上から順番にSlackに投稿したい分毎にテストまで順番に投稿したい。 2021-04-28 01:03:14
海外TECH Ars Technica Tesla posts another record quarterly profit—and Wall Street shrugs https://arstechnica.com/?p=1760378 shrugstesla 2021-04-27 16:37:39
海外TECH Ars Technica Cable-chewing beavers take out town’s Internet in “uniquely Canadian” outage https://arstechnica.com/?p=1760440 conduit 2021-04-27 16:27:11
海外TECH DEV Community What is fundamentally wrong about the modern Web? https://dev.to/chronograph/what-is-fundamentally-wrong-about-the-modern-web-2j04 What is fundamentally wrong about the modern Web If you are in the web development business you might thought this post is about Webpack and friends Nope its even more fundamental TLDRWeb as a platform is trying to solve an application containerization problem but the way of solving it rewriting every piece of code in the world using the Web API is extremely dated Instead Web should rely on OS level containerization and create a common standard of interoperable native calls between different languages something like IDL The problemBeing a programmer I ll use a rd party library blog post to describe the problem I mention in the title Please return after reading it TLDR the key citation The number of WC specifications grows at an average rate of new specs per year or about million words or about one POSIX every to months How can a new team possibly keep up with this on top of implementing the outrageous scope web browsers already have now Lets try to analyze this problem The essentials of webWeb has started as a media for distribution of static content like plain html pages without JavaScript That s HTML epoch Then people realized that content can be dynamic interactive The border between the content and the application started to fade out That s the beginning of the modern web back in the days called HTML HTML started as a list of improvements to HTML And the more people were able to do with the modern Web the more things they wanted to do The improvements list became endless and this is where we are currently But why has the Web become so popular as a media for distributing interactive content aka applications There are regular desktop applications you can download and run on your computer Multiple good reasons I ll mention just few Security Obviously running some untrusted code on your machine you can easily find yourself sending bitcoins to someone to decrypt your HDD with you work files Or discover your business critical files published on every torrent tracker Web acts here as a virtual machine Web VM which sandbox the application and limit the potential harm In practice this point does not hold web browsers are still the most common vector of malicious software infection Interoperability Instead of writing your application for all possible CPU architectures you write it for Web VM I ll focus on the security problem below as most important one after all even C programs can be cross platform nowadays Web as a virtual machineThe main purpose of the Web VM is provide a secure sandbox to be able to run the arbitrary untrusted code When you open a page with the weather forecast nowadays it might be showing some D scenes of Earth Moon orbits and whatnot You do want those D scenes they are very informative The real trouble might begin when you ll decide to check that link your colleague send to you with a note like check out this awesome video You are curious about the video but you don t want your machine to be polluted with viruses So you want a combination of security and versatility in the same time Why an endless list of extensions and new specs is needed for the Web VM to provide both Because its a closed environment every new use case or feature requires a new specification even that already established solutions libraries exists for it in the native code Internal demonsLooking from the other viewpoint the so called modern Web API is just a normal wish of every programmer to rewrite every piece of software in the world in their favorite language framework instead of solving the business requirements It is an intrinsic desire of every developer I ll rewrite that neat library doing feature X but I ll do it in the right way using tabs instead of spaces or may be spaces instead of or may be I ll properly insert semi colons after every statement or I ll remove those noisy semi colons after every statement or I ll use an awesome Web API instead of that C lib please insert your favorite preference here In case of Web VM this desire is also supported by the rational explanation I can t use a library for this purpose it might be not secure What is forgotten I can t use that native library for this purpose because WebVM does not support native code Providing a secure application sandbox is a real world need Rewriting everything from scratch internal demon Security done rightAgain being a developer I ll use a rd party content to demonstrate why the current Web VM approach to security is not correct Check out this thread in Node js mailing listSomeone is submitting a PR for the node safe mode hardened node that should allow running third party written code The list of improvements includes Each node processes will be given a file system directory which will contain the JavaScript it runs other than that the process will have no access to any other part of the file system Each node process creates a socket that it uses to receive requests from the server To prevent different node processes from communicating with each other directly the ability of node processes to connect to sockets will be restricted On general principles Node processes will not be allowed to kill other processes change their default directory change their effective user or group idetc Wow this looks pretty much like the security guarantees of the regular web page Must be an excellent addition to the Node js Ok what are the answers to this generous contributor No I appreciate the effort but it sounds too much like PHP s safe mode and everyone knows how broken that is Containerization should be done at the OS level not the application level The problem with continually restricting things like child processes and native addons is that these are popular features and you still face problems like port fd hijacking In order to prevent fd attacks and port hijacking you would want to completely restrict the C level access instead of Javascript as well I recommend VM level separation if you are serious about security combined with OS level protection True security containment is not trivial It s not a feature you add onto a platform later It s something that you really have to bake into the architecture from the very start and evaluate all your trade offs in that light Furthermore doing multi tenancy in this way is extremely dated and unnecessary There s better technology now Wait what A non trivial PR which adds a security model to Node that is similar to a web page security model is rejected because doing multi tenancy in this way is extremely dated and there s better technology Pretty much all those who replied to the PR said that doing security at the application level is old unreliable way which also restricts the native addons Then why Web is still using such old fashioned approach If we combine the citation from one of the replies from the Node js thread with the citation from the blog post I mentioned in the beginning we ll receive exactly the problem the modern Web is experiencing The problem with continually restricting things like child processes and native addons is that these are popular features and your specification starts to grow at the speed of one POSIX every to months SolutionThe solution is dumb simple As suggested by Node js engineers Web should provide native OS level containerization for the pages Yes every tab in your browser should run in container If you recall when Chrome started running every tab in a separate process that seemed like something inconceivably new and even frightening Well that has proven itself as a reliable solution The next step is to put every of those processes into separate OS level container That s just it you have the proper real security for the untrusted code and that code can use popular native addons There s no need to write a spec for every library in the world Especially if those specs are just descriptions of the imperative interfaces not the mathematically verified code Need to mention that web page as a container is not a new concept There were already similar attempts like Java Web Start They were however application containers similar to the safer node The missing piece was OS level containerization VisionLets imagine we have this OS level containerization for web pages and page can be running native code easily How the Web will look like in this brave new world The role of the JavScript and HTML CSS will probably reduce somewhat The WebAssembly hype wave will not be that big or not happen at all However WebAssembly is moving in the right direction for example with InterfaceTypes proposal The notion of desktop application may start disappearing why would anyone write a program limited to only one CPU architecture For example I imagine all kinds of various editors which are currently desktop applications like PhotoShop DMax etc will have web equivalents It should be possible to run a whole OS desktop in the web page I imagine if I had to open some really untrusted page I d be using a browser running inside of such Web OS page to provide an extra level of containerization Containers may have different virtualization mechanisms from being a container as we know now to being a VM emulator supposedly more secure The border between the web page and mobile application will disappear completely This is probably not what the owners of the mobile app stores want The key piece of the puzzle for this paradigm shift to happen is providing the really secure containerization solution The only way of doing it is writing as mathematically proven statically verified code The IOT can benefit from the secure execution sandbox container a lot Imagine various devices too dumb to visualize their interface but smart enough to upload it to your computer smartphone for execution No need for cloud every internet thing can carry all needed software onboard The need for formal spec for every use case will reduce a lot Instead the need for the robust mathematically sound native code interoperability will appear A web page and a desktop application window these are the equal concepts ConclusionIf we look at the Web from a bit more general perspective we can replace the web page concept with the web node A universal execution node combined with other nodes in a distributed network and able to the run untrusted code this is what probably Ryan Dahl had in mind back in the days calling his project Node Hopefully the argumentation in this post is straightforward enough I believe OS level containerization is a next logical step in the Web evolution 2021-04-27 16:25:42
海外TECH DEV Community Guide to Callbacks & Higher-Order Functions in JavaScript. https://dev.to/blessingartcreator/guide-to-callbacks-higher-order-functions-in-javascript-g98 Guide to Callbacks amp Higher Order Functions in JavaScript Callbacks and Higher Order functions are some of the most misunderstood concepts in JavaScript During this post we will become familiar with them to write pro level code as JavaScript engineers Before continuing let s ask ourselves a question Why do we even have functionsLet s see why…Create a function squaredTakes no inputReturns tenSquaredfunction tenSquared return tenSquared What about a squared function nineSquaredfunction nineSquared return nineSquared And an squared function squared What principle are we breaking DRY Don t Repeat Yourself We can generalize the function to make it reusable function squareNum num return num num squareNum squareNum squareNum Generalizing functionsParameters placeholders mean we don t need to decide what data to run our functionality on until we run the function Then provide an actual value argument when we run the function Higher order functions follow this same principle we may not want to decide exactly what some of our functionality is until we run our function Now suppose we have a function copyArrayAndMultiplyBy function copyArrayAndMultiplyBy array const output for let i i lt array length i output push array i return output const myArray const result copyArrayAndMultiplyBy myArray What if want to copy the array and divide it by function copyArrayAndDivideBy array const output for let i i lt array length i output push array i return output const myArray const result copyArrayAndDivideBy myArray Or add function copyArrayAndAdd array const output for let i i lt array length i output push array i return output const myArray const result copyArrayAndAdd myArray What principle are we breaking DRY Don t Repeat Yourself We could generalize our function so we pass in our specific instruction only when we run copyArrayAndManipulate function copyArrayAndManipulate array instructions const output for let i i lt array length i output push instructions array i return output function multiplyBy input return input const result copyArrayAndManipulate multiplyBy How was this possible Functions in javascript first class objects In addition to this let s highlight some of the other features of functions They can co exist with and can be treated like any other javascript objectAssigned to variables and properties of other objectsPassed as arguments into functionsReturned as values from functionsConsider this piece of codefunction copyArrayAndManipulate array instructions const output for let i i lt array length i output push instructions array i return output function multiplyBy input return input const result copyArrayAndManipulate multiplyBy Which is our Higher Order Function The outer function that takes in a function is our higher order Which is our Callback FunctionThe function we insert is our callback function Higher order functionsTakes in a function or passes out a function Just a term to describe these functions any function that does it we call that but there s nothing different about them inherently Why do we need to master these two conceptsCallbacks and Higher Order Functions simplify our code and keep it DRY Declarative readable code Map filter reduce the most readable way to write code to work with data Codesmith amp pro interview prep One of the most popular topics to test in an interview both for Codesmith and other mid senior level job interviews Asynchronous JavaScript Callbacks are a core aspect of async JavaScript and are under the hood of promises async await ConclusionWhat s more there we have it If you made it here thank you for reading I hope this post will help you get started with writing pro level JavaScript codes Let s be friends Follow me on Twitter and instagram for more related content Don t forget to follow me also here on Dev as well to get updated for new content Cheers 2021-04-27 16:09:45
Apple AppleInsider - Frontpage News Price wars heat up as Apple's M1 MacBook Air drops to $899 [u] https://appleinsider.com/articles/21/04/22/price-wars-heat-up-as-apples-m1-macbook-air-drops-to-899?utm_medium=rss Price wars heat up as Apple x s M MacBook Air drops to u As month end price wars heat up B amp H Photo has issued a standout deal on the standard M MacBook Air dropping the price to a record low And Amazon has followed suit M MacBook AirUpdate on April After selling out at Amazon is stating units will be back in stock soon at the discounted price Shoppers can order now to secure the best spot in line Read more 2021-04-27 16:14:24
Apple AppleInsider - Frontpage News Mac developer poll illustrates demographics, favorite tools, and more https://appleinsider.com/articles/21/04/27/mac-developer-poll-illustrates-demographics-favorite-tools-and-more?utm_medium=rss Mac developer poll illustrates demographics favorite tools and moreA survey of Mac developers using popular commercial software breaks down info on demographics ways of working and other tidbits to paint a clearer picture of Mac developers While it isn t a scientific survey of Mac developers one company s poll could perhaps hint at the community s breakdownThe team behind Mac development software Git Tower a popular app with over customers surveyed users in March and April It included participants Read more 2021-04-27 16:22:29
海外TECH Engadget DoorDash offers restaurants more flexible commission rates https://www.engadget.com/doordash-commission-rate-flexibility-restaurants-food-delivery-161807416.html customer 2021-04-27 16:18:07
海外TECH Engadget Ford announces plans for two EV battery facilities https://www.engadget.com/ford-ion-park-160053425.html technologies 2021-04-27 16:00:53
Cisco Cisco Blog Cisco Intersight – a Capabilities-as-a-Service platform, for an agile, API-driven world https://blogs.cisco.com/cloud/cisco-intersight-a-capabilities-as-a-service-platform-for-an-agile-api-driven-world Cisco Intersight a Capabilities as a Service platform for an agile API driven worldBhaskar Jayakrishnan the visionary behind Intersight unveils the origin story behind this the world s simplest hybrid cloud platform Specifically Bhaskar discusses how Intersight delivers tremendous value to customers by simplifying the management of APIs that customers have to deal with in a cloud delivered app centric world 2021-04-27 16:16:34
海外科学 NYT > Science ‘This Is a Catastrophe.’ In India, Illness Is Everywhere. https://www.nytimes.com/2021/04/27/world/asia/India-delhi-covid-cases.html This Is a Catastrophe In India Illness Is Everywhere As India suffers the world s worst coronavirus crisis our New Delhi bureau chief describes the fear of living amid a disease spreading at such scale and speed 2021-04-27 16:15:35
ニュース ジェトロ ビジネスニュース(通商弘報) モルドバ政府が国内のワクチン接種状況を発表、医療従事者の接種進む https://www.jetro.go.jp/biznews/2021/04/19a3c4df13ca17b3.html 医療従事者 2021-04-27 16:20:00
ニュース ジェトロ ビジネスニュース(通商弘報) 任期満了前の前倒し議会選実施に向けパシニャン首相が辞任 https://www.jetro.go.jp/biznews/2021/04/aebe05db64cd2725.html 任期満了 2021-04-27 16:10:00
海外ニュース Japan Times latest articles Tokyo to get SDF-staffed, large-scale vaccination site amid slow rollout https://www.japantimes.co.jp/news/2021/04/27/national/tokyo-large-vaccination-site/ Tokyo to get SDF staffed large scale vaccination site amid slow rolloutMedically licensed SDF personnel are expected to administer Moderna and AstraZeneca vaccines to about people age or older living in the capital and 2021-04-28 02:54:27
海外ニュース Japan Times latest articles Tokyo reports highest new COVID-19 cases on a Tuesday since Jan. 26 https://www.japantimes.co.jp/news/2021/04/27/national/coronavirus-japan-april-27/ Tokyo reports highest new COVID cases on a Tuesday since Jan Osaka Prefecture reported new cases of the deadly virus the second highest figure on record as it continues to fight a fourth wave of 2021-04-28 02:31:54
海外ニュース Japan Times latest articles Local governments scrap plans to host Tokyo Games training camps https://www.japantimes.co.jp/news/2021/04/27/national/olympics-camps-scrapped/ reactions 2021-04-28 02:00:48
海外ニュース Japan Times latest articles Billionaire founder of Nidec hands reins to ex-Nissan star https://www.japantimes.co.jp/news/2021/04/27/business/nidec-ceo-jun-seki/ family 2021-04-28 01:56:17
海外ニュース Japan Times latest articles A look at the COVID age’s wannabe platinum cards (and apps) https://www.japantimes.co.jp/news/2021/04/27/world/science-health-world/vaccination-passports/ A look at the COVID age s wannabe platinum cards and apps It is the latest status symbol Flash it at the people and you can get access to concerts sports arenas or long forbidden restaurant tables Some 2021-04-28 01:36:37
海外ニュース Japan Times latest articles Annual Japan diplomacy report targets Chinese military concerns but omits Taiwan https://www.japantimes.co.jp/news/2021/04/27/national/japan-china-bluebook/ Annual Japan diplomacy report targets Chinese military concerns but omits TaiwanThe report explained the outcome of the recent Suga Biden summit but made no reference to their joint statement which explicitly mentioned Taiwan 2021-04-28 01:35:27
海外ニュース Japan Times latest articles Rui Hachimura returns from injury in loss for Wizards https://www.japantimes.co.jp/sports/2021/04/27/basketball/nba/hachimura-wizards-return-loss/ Rui Hachimura returns from injury in loss for WizardsRui Hachimura returned for the Washington Wizards on Monday after missing four games with a sore left knee contributing points and six rebounds in 2021-04-28 02:51:41
海外ニュース Japan Times latest articles Yuki Kawamura hopes to emulate idol Isiah Thomas with Asics deal https://www.japantimes.co.jp/sports/2021/04/27/basketball/yuki-kawamura-asics/ Yuki Kawamura hopes to emulate idol Isiah Thomas with Asics dealThe year old Tokai University point guard is the latest to join Asic s roster of advisors which includes Japan stars Ryusei Shinoyama and Ramu Tokashiki 2021-04-28 02:26:47
海外ニュース Japan Times latest articles Masters winner Hideki Matsuyama to receive Prime Minister’s Award https://www.japantimes.co.jp/sports/2021/04/27/more-sports/golf/hideki-matsuyama-prime-ministers-award/ Masters winner Hideki Matsuyama to receive Prime Minister s AwardThe year old will become the th individual recipient of the honor after becoming the first Japanese man to win one of golf s four major tournaments 2021-04-28 01:10:25
海外ニュース Japan Times latest articles Japanese brewery re-creates feudal-era sake https://www.japantimes.co.jp/life/2021/04/27/food/feudal-era-sake/ sweet 2021-04-28 02:00:09
ニュース BBC News - Home Labour accuses Boris Johnson of lying over flat renovation costs https://www.bbc.co.uk/news/uk-politics-56903838 downing 2021-04-27 16:13:57
ニュース BBC News - Home Arlene Foster: Letter of no confidence sent to DUP politicians https://www.bbc.co.uk/news/uk-northern-ireland-56902771 arlene 2021-04-27 16:46:52
ニュース BBC News - Home India Covid: Delhi builds makeshift funeral pyres as deaths climb https://www.bbc.co.uk/news/world-asia-india-56897970 capital 2021-04-27 16:13:40
ニュース BBC News - Home Autistic teens face 'barbaric' treatment, parents tell MPs https://www.bbc.co.uk/news/uk-56905842 autistic 2021-04-27 16:30:57
ニュース BBC News - Home Covid-19 in the UK: How many coronavirus cases are there in your area? https://www.bbc.co.uk/news/uk-51768274 cases 2021-04-27 16:12:20

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)