Posts tagged "javascript"

Nombas ScriptEase

$9Bn James Webb Telescope Relying on Outdated Nombas JavaScript Engine

April 24, 2019 Posted by Programming 0 thoughts on “$9Bn James Webb Telescope Relying on Outdated Nombas JavaScript Engine”

According to a paper written in anticipation of  the 2006 SpaceOps Conference, the decades in the making James Webb Telescope is supposed to be an event-driven telescope. Dr. Vicki Balzano and John C. Isaacs gave this for their reasoning behind employing event-driven scripts: “To take advantage of the opportunity offered by the JWST environment to increase science efficiency and to decrease the ground system development cost…”

In the end, the language of choice was JavaScript. NASA planned  on using an on-board commercial JavaScript engine called ScriptEase from Nombas, a company that now no longer exists. According to Brent Noorda, co-founder of Nombas, “Nombas was the leading developer, innovator, licensor, and evangelist of script language tools, licensing their JavaScript engines and tools to C, C++, and Java developers for everything from embedded devices to massively parallel servers.”

Perhaps, in choosing JavaScript, NASA has found out how quickly a language and its dependencies can change over the years. The JavaScript of 2006 looks very different from the JavaScript of today, which makes one wonder why a more embeddable event-driven language like Lua wasn’t considered. For those like NASA stuck with a technology that will be difficult to maintain, Brent gave modern alternatives to ScriptEase:

  • List of ECMAScript engines – Look to this Wikipedia page for other javascript engines, although only a couple have good embeddable libraries. ScriptEase isn’t there anymore–which makes me sad–althought it still gets lots of legacy use.
  • Rhino – Javascript engine written in Java. I don’t know why it’s not in the List of ECMAScript engines.
  • lua.org – Not ecmascript, but is guided by a small/fast/embeddable/minimalist philosopy similar to the original Cmm.
  • node.js – Server-side javascript. It’s coming back, baby! I’ve been playing with node.js lately, and quite enjoy it. Imagine the fun of turning adding a couple of the old CEnvi features, and turning into a cross-platform desktop environment for automation, thin servers, and so on, then CEnvi/SE:Desk would be back……
  • dnode “freestyle rpc” – I really nice-looking implementation of what we used to call “distributed scripting”. Perhaps nowjs is on the right track, too. Or maybe meteorjs. Or maybe Yahoo’s Cocktails & Mojito.

 

So many of these new JavaScript technologies have come on very recently, and one can only wonder if NASA’s additional delay has something to do with refactoring JavaScript code that has quickly become legacy since they started development before 2010. Though, this recent  quote from Brent says otherwise:

“I led the team that created the JavaScript interpreter JWST is using, and I still occasionally work with them on it. 16 (or so) years ago I was blown away at the amount of research NASA did covering all of the control language options, and of course glad that they selected ours. The language itself wasn’t so important as having adequate performance, robustness, memory use, reproducibility and extreme QC.. the way I remember thinking about it was that when your system is running a million miles away, you can’t send an IT tech to press ctl-alt-del when something goes wrong. IMHO they made a well-researched choice that continues to hold up.”

So, perhaps NASA has nothing to worry about.

Please follow and like us:
0
time travel debugger

Mozilla is Working on a Time Travel Debugger for JavaScript

April 8, 2019 Posted by Programming 0 thoughts on “Mozilla is Working on a Time Travel Debugger for JavaScript”

Normally, when you want to debug software, you use a tool to pause execution in order to step through the code line by line. That’s after you’ve been able to isolate the bug. The problem is that for bugs that exist in complex systems, isolating the bug can be tricky. Some bugs are difficult to reproduce, because they don’t produce substantial effects, making them hard to pin down. For example,  logic errors can produce slightly unexpected results that add up over time. Tracking the source of the error by logging input and outputs can be painstaking.

If a developer could only look back in time to see the events that led up to the failure, they might be able to save time, thereby saving a company money. That’s the hypothetical that time travel debuggers put out. According to UndoDB, reverse debugging or time travel debuggers “can deliver significant savings. Mentor Graphics has reduced debugging time by 66% (two thirds) after implementing Undo’s reverse debugger for Linux, UndoDB. Take an average software developer earning $90,000. Currently they spend a quarter of their time debugging, costing $22,500 in wages. Reducing that by two thirds, creates a saving of $15,000 and increasing available developer time.”

Time travel debuggers have been available for GDB compatible programming languages like C/C++, Go, Fortran, Pascal, etc.

Then, you have projects like…

  • Chronon for Java
  • RevDeBug for .Net and C#
  • RevPDB for Python
  • Elm TTD for, as you can guess, Elm

 

What’s been missing from this list is a reverse debugging tool for the web’s favorite scripting language–JavaScript. Mozilla’s developers have been hard at work to come up with a time travel debugger for the browser. The technology is called Web Replay and is only available for macOS nightly builds.

Here are some of the features that are currently stable:

  • Ability to step back in code
  • Rewind to a set breakpoint
  • A timeline with record and replay markers, current position in time indicator, errors/messages
  • Retroactive console logging

 

Of all the stable features, retroactive console logging is the most interesting in that a large portion of front end debugging is looking at output logged to a browser’s console. How many times have you had to dig back into the source files to move console logs around to further isolate a bug? Countless times most likely. According to Mozilla, this headache is alleviated with Web Replay.

“The bug only needs to be reproduced in a recording tab once, and then console logs can be added which apply throughout the entire recording.  This is based on the log points feature in the debugger, which can be enabled with the devtools.debugger.features.log-points preference.  Set a breakpoint and right click on it to change it to a log point.

In a non-recording tab this will update the console whenever the log point’s location executes in the future.  In a recording tab, however, this will update the console with messages for every time the location has ever been hit.  This requires scanning the recording and the console will not update immediately.  These messages will show up on the timeline and can be sought in the same way as other console messages.”

 

There are several features that are still being worked on. Some of them are:

  • DOM/CSS integration
  • Object watching(logging changes to object over time)
  • Bookmarking points in recording
  • code path highlighting
  • Comparing executions(buggy vs clean code)

 

Web Replay may change the way front end developers code, but the complexity of time travel debuggers may limit its scope. Will developers accustomed to Chrome migrate to Firefox to take advantage of the new technology? If so, Google may also create a time travel debugger of their own. On the other hand, if the demand for time travel debuggers is minimal, the cost of developing such a complex tool may not be worth it to Google. Only time will tell whether Mozilla’s project will bear fruit.

 

 

 

Please follow and like us:
0

TC39 Creates A Website For JavaScript Specification News and Documents

March 19, 2019 Posted by News 0 thoughts on “TC39 Creates A Website For JavaScript Specification News and Documents”

JavaScript is a language that has exploded over the last few years.  The most notable starting point for the explosion was TC39’s introduction of ES6, the JavaScript community was graced with the notorious fat arrow operator whose purpose wasn’t simply to obfuscate anonymous functions, but to also apply auto binding. ES7 and ES8 quickly followed ES6. To put that into context the gap from ES5 to ES6 was about 7 years.  Now, we almost expect to hear rumblings of new features at the turn of every year.

To respond to this anticipation, TC39 is developing a website that will publish its JavaScript specifications and alert news-hungry devs about what’s coming up in their latest releases. TC39 sets out to provide a platform that allows developers easy access to the most important documents pertaining to specification. To accomplish the task of accessibility, the team interviewed individual members of the JavaScript community in-person and provided surveys to the community as a whole.

The insights gained UX research should enable them to build a site that will provide useful information. An actionable piece of information they received from a survey was that respondents wanted more learning resources when it came to features added to JavaScript. Rather than fish around for blog posts, a knowledge base created by TC39 would make it easier to integrate some of JavaScript’s new features. This is important considering that new features are being added almost every year. It would be nice to have a well-organized repository full of clear documentation.

 

Currently TC39 admits that though a website is up, it is far from complete:

“While the website is currently an MVP and very simple, we have plans to expand it. These plans include a set of documentation about how we work. We will experiment with other features as the need arise.”

 

The website, according to TC39, targets:

“Learners who are discovering the specification for the first time, Observers of the specification who are watching proposal advancement, and Reference Users who need a central location where all of the significant documents can be found. The website was designed around these users. In order to not overwhelm people with information, the MVP is specifically focused on the most pertinent information, namely proposals in Stage 3 of our process. Links are contextualized in order to help people understand what documents they are looking at.”

 

If you have any questions about the site or you want to drop feedback, you can add an issue on their GitHub page.

Please follow and like us:
0

V8 Now Supports JIT-less JavaScript Execution

March 14, 2019 Posted by Programming 0 thoughts on “V8 Now Supports JIT-less JavaScript Execution”

The V8 team announced yesterday that JavaScript developers now have the ability to go JIT-less when developing apps. In an article we published, we detailed exactly what JIT is in the context of JavaScript’s engine:

” JavaScript’s compilers are forced to compile the code at the last second — literallyThe technology used to compile JavaScript is aptly named Just-In-Time(JIT). This “compilation on the fly” has appeared in modern JavaScript engines to speed up the browsers that implement them.”

In the words of the engineers who built the TurboFan optimizing compiler,

“the TurboFan optimizing compiler creates native code for hot JavaScript (JS) functions just-in-time, and most JS regular expressions are compiled down to native code by the irregexp engine. Creating executable memory at runtime is part of what makes V8 fast.”

The problem that the engineers and developers are aware of is the fact that some platforms like the iOS, smart TVs, and game consoles don’t allow write access to memory for third party developers, so JIT becomes a moot feature.  In that case, having an option to switch JIT off can allow for better accessibility when developing for platforms that don’t support JIT.

This prompted V8’s engineers to finally develop a –jitless flag which essentially turns JavaScript into what it’s usually advertised as being: an interpreted language. All of the code is funneled into V8’s Ignition interpreter. Unfortunately, V8 doesn’t support Web Assembly, which might have been able to counteract the inevitable penalty for removing JIT.

“WebAssembly is currently unsupported, but interpretation is also in the realm of possibility. V8’s builtins are still compiled to native code, but are no longer part of the managed JS heap, thanks to our recent efforts to embed them into the V8 binary.”

 

After testing JIT-less mode versus JIT mode on  Youtube TV, the engineers found that JIT-less mode showed a 6% performance hit as compared to the standard configuration.  The V8 team acknowledged that the performance regression was small relative to the  40% performance hit on Speedometer 2.0, leading them to conclude that testing environments don’t always translate to real world results.

image source: V8

 

Though one can also argue that Youtube TV is just one example and that further testing may reveal larger performance hits depending on the structure of the app. In any case, V8 has provided an alternative for those willing to work on restricted platforms. The performance hit might be negligible enough to try out JIT-less V8.

 

 

Please follow and like us:
0

What Do You Think About JavaScript’s Tooling Landscape?

March 8, 2019 Posted by Programming 0 thoughts on “What Do You Think About JavaScript’s Tooling Landscape?”

Every year, it seems that JavaScript developers get a new tool or framework to play with. In one sense, it’s exciting to see fresh updates arrive that make developing with JavaScript a more efficient and intuitive process. Web Assembly, for instance, is a standard that allows JavaScript code to be broken down into fast machine code without the need of  optimizers like asm.js. The new tech also means that developers have to change some of their habits when it comes to optimizing apps. The same goes for build tools. The thriving dev community is always coming up with something that will make builds “blazing fast.”

The question is, at what point do you get tooling fatigue? Some developers discuss how they feel about JavaScript’s tooling landscape, specifically as it pertains to bundlers like Parcel, on Dev.to.

 

James Hickey

I was thinking about trying out parcel… but for most of the stuff I just need webpack for vuejs + sass. I already have a working webpack config that I can just copy from project to project that works great.

I am tired of learning about more bundlers. I just want to build my apps.

 

Mark Erikson

What’s the concern? Just because a specific tool exists doesn’t mean you have to use it, or even have to learn how to use it.

It can be helpful to know that various tools exist, so that you can evaluate them later on if and when there’s a need to make a decision, but otherwise it’s totally fine to stick with your current toolset.

In this specific case, Parcel looks like it’s got some interesting ideas, and it might be worth looking at if you’re starting a new project from scratch, but there’s no need to go throw out an existing project’s build config just because Parcel exists.

 

Thomas Junk

Javascript tooling is really evolving in a fast pace. Which is in itself a good thing. People are working on improvements everywhere. For many different problems there are a variety of solutions to pick from. So in terms of supply and demand, it is a nice market.

The only thing which in my eyes causes problems is the overoptimistic attitude of people, trying to learn the latest and greatest in order to feel their skillset staying sharp.

It’s a bit like developers became some kind of fashion victim: »Oh, what you are still using $blerg when everybody else is using $blarg. This is so 2017«.

Another problem I see is big insecurty: Becuase of having (too) many choices people are afraid of making the wrong choices (which is not even limited to the javascript ecosystem).
»What framework should I use to accomplish X

My standard answer to this:
»Pick the one you are understanding fast and feel the most productive with«

Most of the time, projects or companies die before they feel any serious pain because of wrong technological choices. And if they survived up to that point, they have enough money to pay people making the right decisions for them.

My approach to this in general, or parcel in special is purely hedonistic:
If I find a minute, I have a look at it and play with it. If not, it’s okay – I know, it’s there; and when webpack at some point in the future should make me cry (again), I’ll give it a try. If it’s fun, I’ll use it. If I am bored. I leave it.

OTOH, I’ve been long enough in the industry to have learned, that all tools/languages are in one way or the other “crap”. And sometimes it is better to stay with “crap you know”. There are less bad surprises waiting.

Avalander

I usually don’t look much into new stuff until I’ve heard about it for a while and it looks like it’s getting widely adopted, or I have a specific interest in it.

I didn’t move into Webpack until I felt it was becoming the most commonly used bundler and I had some issues with Gulp.

So far I’m happy with Webpack and I haven’t looked into Parcel or Rollup at all. Webpack solves my problems and it’s still actively developed and getting good updates, so I don’t see any reason to change.

 

Graeme Worthy

I’ve experienced tooling fatigue as well, and it can be refreshing to realize that you can just keep using the tool you used yesterday, it still works.

You can get your focus and your energy back by stepping off the hamster-wheel, and focusing on building what you came here to build rather than re-writing every time a new library is announced.

Kasey Speakman

My disappointment with front end processes is very influenced by using Visual Studio all these years. It has templates which automatically setup the build processes. Then the IDE does a decent job of keeping the build process up to date as you use it. Example, when you Add New File from the UI, it also adds that file to the build template.

If you add a source file, it will be added to the compile list. If you add a content file, it will be copied to the output as-is. And you can adjust the behavior on the file’s properties. In effect, file organization is a separate concern from file build settings… you don’t have to put certain files in static and other files in src to get it to build correctly. Nor maintain build configurations for each file by hand.

The IDE cannot do everything you might ever need — in which case you can use the command-line build tools and scripts — but it does a great job of covering standard cases. I’ve never really needed to write command-line build scripts until recently with .NET Core. And that is mostly to build docker images. VS added Docker image build support in 15.7, but I had major issues with it for multi-container projects. So I’m building the images with scripts.

But front end basically has very limited coverage of even common cases. You are expected to write custom builds from the get-go. It is such a large barrier to entry that many setup tools have sprung up such as Create React App to start you off right. If I take a lesson from VS, what we really need is some build template support integrated into editors so they can manage common cases and just let me worry about coding my features. Maybe “IDEs” are not so bad after all.

 

JR

I went thru tooling fatigue for a while and finally decided to stay with the most stable, long-term supported projects as my go-tos (like webpack). I did that, not because I reject new, exciting stuff; but because I have to limit the amount of time I spend getting a project from dev to prod. Its that simple. I can’t learn everything; but I can pick and choose what my toolbox is made of and know how to use what I have.

That being said, there are pros and cons to being strictly frontend and not writing in a compiled language like C++. @kspeakman makes a good point about using Visual Studio and not having to worry about browser options for compiling.

What I really think is that over the last five years js has mutated in an “out-of-control way” and frontend devs have had to suffer through its gigantic growing pains. I really love js but sometimes its just easier build those features on to a .net base. That’s why I think .net core is a good fit for some of my projects.

 

jrop

The best thing about JavaScript is also the worst: everything is in userland, which can tend to anarchy at times. However, it does yield (multiple) killer tools that everybody chooses from regarding which to use.

“Your greatest strength is also your greatest weakness.”

 

Conclusion

The last quote describes JavaScript beautifully. JavaScript’s ecosystem is a thriving one that produces modern frameworks like React, but then also gives you 10 other frameworks just in case you’re looking for something else. A lot of the push back come when there’s this peer pressure to have to learn the ins and outs of yet another tool when the tool you’ve grown accustomed to works just fine. Not being on the bleeding edge, in the web development world becomes akin to being the old man in the outfield still trying to make plays.

But new doesn’t always mean better. There are tools out there that have their pros and cons. Webpack is a mature bundler whose configuration may be perfect for devs working on large projects. Parcel, on the other hand, seems to be a nice tool for someone starting a project from the ground up. The low barrier makes that tool attractive to some. At the end of the day, some tools are easier to use than other. Still, as long as these tools are reliable and function the way developers expect them to function, there should be nothing wrong with creating your own island of acceptable tools. If you liken JavaScript’s tooling landscape to a market, then you’ll realize that you only need to grab what will help you within your current context.

 

 

Please follow and like us:
0

#OPJerusalem Tries To Hack Israel and Fails Because of Hilariously Bad Code

March 6, 2019 Posted by Programming 0 thoughts on “#OPJerusalem Tries To Hack Israel and Fails Because of Hilariously Bad Code”

A recent hacking campaign led by #OpJerusalem aimed at targeting Israeli websites with JCry ransomware failed spectacularly over the weekend. The ransomware was supposed to lock out hundreds of Israeli Windows users by exploiting Nagish’s DNS records. In so doing, the hackers were able to spread the malware across all of the sub-domains belonging to nagish.com.

 

So if a users visited a site that enabled Nagish’s tool, they would’ve automatically gotten a script downloaded onto their browser. Afterwards, the script would’ve checked if the user was a Windows user.

Theoretically, if it was true that the user’s OS was Windows, the script would’ve presented a message alerting the user to a supposedly outdated Flash player(which should be deleted and left to die anyway).

If for some reason, the user clicked the update button, JCry would’ve been downloaded onto their PC. It would’ve then executed an Enc.exe file that would’ve encrypted the user’s files, appending .jcry to each and every file. $500 dollars in Bitcoin would then have had to have been payed in order to  decrypt the files.

The geniuses went the extra mile to right a condition, in the case that the OS wasn’t Windows, that presented an overlay that read:

The problem is that everyone received that message. Apparently, there was a bug in the code. Here’s a snippet of the code that Yuval Adam released. You can see the full source on his gist.

[ It’s a good idea to use the  !== operator when comparing two strings just to eliminate any other potential bugs.]

In this case, the logic is so simple it’s almost unbelievable that this particular bug wasn’t spotted, which raises the possibility that the condition was just a last minute tack on, as well as the function that the condition relied on. If the hackers(or single hacker) had tested their code, they would’ve noticed that the condition is always true. The os that gets returned is a Windows version.

“Windows 10/8.1/8/7…” != “Windows” // hacker’s sentient computer shrugs and says, true

Conclusion

 The hacker group’s simple oversight saved thousands of users from a nasty ransomware. If you were their peer and you had to perform a code review, what would you have said in regard to their code? How would you have refactored it?

By the way, here’s a video demonstrating the exploit:

 

Resources:

 

https://www.bleepingcomputer.com/news/security/opjerusalem-targeted-israeli-windows-users-with-jcry-ransomware/

https://www.zdnet.com/article/ransomware-attack-on-israeli-users-fails-miserably-due-to-coding-error/

https://brica.de/alerts/alert/public/1249713/jcry-ransomware-utilized-in-opjerusalem-campaign-against-israeli-sites/

 

Please follow and like us:
0

Google Domains’ First Page is Slow on First Load Because of Google Web Toolkit

February 28, 2019 Posted by Programming 0 thoughts on “Google Domains’ First Page is Slow on First Load Because of Google Web Toolkit”

Google Domains, if you haven’t heard of it, is Google’s attempt at joining Namecheap and GoDaddy in the domain selling business. The program is currently in beta and Jane Machun Wong has discovered why the first page doesn’t load quickly. Besides the 230k lines of code, the developers have rolled in arguably the heaviest object known to mankind–the node module.  Machun Wong explains the cascade of nightmares that end in Java in her tweet below.

 

Java and JavaScript are two completely different languages, but Java’s portability allows it to find its way into web development projects. Especially when that project calls for using a tool like Google Web Toolkit. That’s really the main cause of the slow page load. And that’s due to all of the factors associated with using GWT. One of them includes the need to generate a ton of JavaScript for what is primarily a single page web app. Ironically, all of this JavaScript is compiled from Java when you’re using GWT. If you want to check out a full list of the downsides of using GWT, check out this stackoverflow page. Developers who’ve had extensive experience using GWT give an unbiased account of what makes the toolkit flawed.

 

So, technically, Java is acting like high level JavaScript. Hence, if someone asks you if JavaScript is anything like Java, you can say:

 

 

In the end, I’ll just quote Joseph Gentle who said in reference to web developers building CPU-guzzling apps, “Also all you web devs: Go learn C or Rust or something. Your program runs on a computer. Until you know how that computer works, you’re doomed. And until then get off my lawn shakes fist.”

 

 

 

Please follow and like us:
0

Developer Handbook: JavaScript Control Flow

January 31, 2019 Posted by Programming 0 thoughts on “Developer Handbook: JavaScript Control Flow”

There comes a point in time when you need to rely on automated tasks to run code. Think of the traffic lights that control traffic, saving cities from the hassle of appointing a traffic cop on every crossroad. Or the assembly line which performs mundane tasks at incredible speeds.

Similarly, conditionals and loops allow us to write effective and efficient code. The reason why the term control flow is used is because the interpreter reads code from top to bottom. Step by step.

When you write a bunch of statements like,

 let firstVar = 'dummy';
 let secondVar = 'bozo';
 let thirdVar = 'stoog';

 console.log(firstVar);
 console.log(secondVar);
 console.log(thirdVar);

The interpreter reads the code from top to bottom and executes them in that order. This would be fine if we didn’t have to account for the fact that users will interact with our app. Humans, unlike robots, can be don’t interact with our app they way we want them to, so we have to plan for this by setting up conditions.

Think of conditionals as forks in a road. One conditional you may be familiar with by now is the if statement. Let’s try to use it in a scenario where a user would interact with our app.

If/else

Suppose we’ve been tasked with building a submission form for a pet daycare called Pet Nirvana. One of the questions that CEO Larry Davis wants to ask his potential costumer is, ‘how many pets do you have?’.

var answer = prompt("how many pets do you have?");
alert(answer);

Pro tip: The prompt method takes in a response from a user and returns the user’s input. We can use it to test user input. Once upon a time, the alert method used to be used to test output, but console.log() took over that role.

We’d assume that the user would enter a number, but what if someone wanted to enter a long string just to mess with us.

Without control flow, this is what we might get from a malicious user: DROP/*you got jacked!*/users

That little line of SQL code can drop all of the users in a database. That’s just one example. Really, all it takes is a simple string to break our app.

Imagine if we wanted to calculate the average pets per owner so that Mr. Davis can know how much he should be spending on supplies.

Don’t worry about the functions. Copy the code below into the editor and try entering a number.

var pets = 35;
var owners = 15;
var petsPerOwner = average(pets, owners);
//======Pet Info Form
var answer = prompt("how many pets do you have?");
//============
updateAvg(answer) // update based on answer, add new owner

console.log(`There are now ${petsPerOwner} pets per owner at Pet Nirvana `)

//============
//Functions are hoisted up in JavaScript.
//We'll deal with 'em later

function average(total, number){
    return total / number;
}
function updateAvg(newNum){
  pets += Number(newNum); // register new pet(s)
  owners += 1 // register new owner
  petsPerOwner = Math.ceil(average(pets, owners)); // find new average, round up
}

You should’ve received a nicely rounded average. Now, try to insert a random string into the prompt.

You should get “There are now NaN pets per owner at Pet Nirvana”

Pro tip: The specific error originates at the Number() function. The function forces a number that’s type string ('3') into type number
(3). Whenever we receive user input, it’ll most likely be in the form of a string. So Number() comes in handy when we’re expecting a number. If an input is a normal string of words, and we try to coerce it into a number, we get NaN.

This might not appear to be a big deal, but in the real world this would be a disaster. We’ve lost access to important information just because we couldn’t filter data.

There has to be control over the data we’d like to work with.

if/ else

Thankfully, we have if/else statements.

var answer = prompt("how many pets do you have?");
if(isNaN(answer)){
    alert("Error: input a number");
}else{
  updateAvg(answer) // update based on answer, add new owner
  console.log(`There are now ${petsPerOwner} pets per owner at Pet Nirvana `)
}

Instead of taking in any ol’ response, we’re able to control the flow of data by checking if the answer is a number. Remember our NaN error? It’s the error you get when you try to perform incompatible arithmetic operators on strings. Any block of code within the if statement will automatically execute if the condition is true.

Note: There’s no need to write isNaN(answer) == true because the if statement can evaluate the truthiness of a value.

"hello" / 4; //> NaN

Well, there’s a built-in function called isNaN() that checks whether or not a data type is a number. If the data type is not a number, it returns true. Otherwise, it returns false.

Let’s translate the code we just wrote into pseudo code for better understanding.

/*
If the answer is not a number
     output an error
Else(otherwise)
    update the average
*/

Short Circuiting

There’s an alternative way to control the flow of data. We can short circuit the OR operator.

 isNaN(answer) || (petsPerOwner = updateAvg(answer));
console.log(`There are now ${petsPerOwner} pets per owner at Pet Nirvana `);

The OR operator looks for the first truthy value. When it finds it, it breaks out of the condition. So, if there’s ever the case that the answer is not a number, we wont have to update the average.

The problem here is that answer still holds the unwanted value, limiting what we can do with that variable down the line. You’ll also notice that there was no way of giving the user any feedback. Short circuiting the OR operator is a nifty trick, but it’s not the best at controlling data flow.

else if

What if we want to check for more than two possible conditions? What if the CEO of Pet Nirvana also wants to warn pet owners that the company can only accommodate 3 pets per owner, for now. We would now not only need to check for the type of data the users are entering, we would also have to warn owners who have over four pets about the limit.

An else if statement will be useful. You can chain as many of them together as you want.

if(/*first condition*/){

}else if(/*second condition*/){

}else if(/*third condition*/){

}

Why don’t we try pseudo coding our solution first before we begin coding?

/*
If the answer is not a number
     output an error
Else if the answer is greater than three     
    warn the user that they have too many pets
Else(otherwise)
    update the average
*/

Let’s try it out on our code. When you input a number greater than 3, you should get a warning.

var answer = prompt("how many pets do you have?");
if(isNaN(answer)){
    alert("Error: input a number");
}else if(Number(answer) > 3){
  alert("Sorry, we currently only accept 3 pets");
}
else{
  updateAvg(answer) // update based on answer, add new owner
  console.log(`There are now ${petsPerOwner} pets per owner at Pet Nirvana `)
}

Task

Oh, oh. There was a breakdown in communication between you and your client. Apparantly, he wants the average to be updated even if an owner’s total number of pets exceeds the limit, but he want’s to ask the user if they’re okay with the limit before doing so.

Pseudocode has been provided for you.

/*
Else if the answer is greater than three   
  Prompt the user and ask if they're ok with the limit
  If the prompt equals yes
     update the average

*/

Switch Statements

As you continue to work with if statements, you might come across this type of code:

if (x == "case 1") runThis();
else if (x == "case 2") runThat();
else if (x == "case 3") runThis();
else if (x == "case 4") runThat();

If you’re dealing with so many cases, it may be better to use a control flow construct called switch.

A basic switch statement begins with the initial value, then offers up case blocks with an optional default.

A case statement is just a reader-friendly if statement.

let greeting = 'hello'
switch(greeting){
  case 'hello': // is the same as if(greeting === 'hello')
    //code goes here
    //break

  default: // is the same as else
}

Here’s a more fleshed out example for you to munch on.

let number = 2;

switch(number) {
  case 1:
    console.log("this is one");
    break;
  case 2:
    console.log("this is two");
    break;
  case 3:
    console.log("this is three");
    break;
  default:
    console.log("I can't count past three.");
}

//can you guess what the result will be?

The break keywords are crucial. If you leave them out and the condition is met, the switch statement will continue, automatically executing the next case block until it hits a break or runs out of cases.

So, if we had omitted the break in case 2:, we would have gotten:

"this is two"
"this is three"

Think of the switch statement as a pipe. The break statements serve as dams that prevent leakage to other sections of the pipe.

One other thing to note about switch statements is the ability to group cases. Let’s expand our greeting example to showcase our chain of cases.


switch(prompt('greet me!')){
  case 'hello':
  case 'hi':
  case 'yo':
    console.log("Hey? What's up?");
    break;
  default:
    console.log("I don't speak your lingo.");
}

Loops

So now we know how to control the data that comes in, but how about the data that goes out to the user?

Mr. Davis now wants to add a rating system to his handlers. He’d like stars to show up under their profile name.

We could render all of the stars manually…

//you can see that Becky has accumulated a rounded average of four stars
var becky = {name:'Becky Star', stars: 4}

//====Profile
//Mock profile name
console.log(becky.name)
//we can render our stars four times
render() + render() + render() + render();
//====
//Dummy render function
function render(){
  return '*';
}

while loop

Or we can use a while loop. A while loop checks if the condition is true and will continue running the block of code until it is false. Make sure your loop can eventually produce a false value. Otherwise, you’ll have an infinite loop on your hands.

// you usually have to set a counter and either decrement or increment it till it satisfies the condition.
counter = 4;

while(counter != 0){
  console.log(counter);
  --counter //we decrease the counter by 1
}

Try igniting your creativity. render a row four stars using a while loop. The output should look like this: '****'

Hint: the counter number and the number of stars are significant.

Hint: the plus equals operator will be useful

do while

A do while loop is similar to a while loop except for the fact that you are guaranteed the execution of the block on the first go round.

It’s like saying, “definitely do this first(this being the block of code). Now, while my condition is true, continue to do what’s in that block.

Let’s revisit that pet number prompt and rewrite it using a do while loop.

let answer;
do {
  answer = prompt("how many pets do you have?");

}while(isNaN(answer))

This code will keep badgering a user to enter information if they don’t enter a number.

Let’s add a condition within the loop to beef up our control of information.

let answer;
do {
  answer = prompt("how many pets do you have?");
  if(isNaN(answer)){
     alert("error: enter a number");
  }
}while(isNaN(answer))

Now we’ve created a feedback loop that alerts the user of their error and allows them to immediately correct it.

for loop

Simply put, a for loop is a while loop with batteries included. You know how you have to set up a counter outside of the loop and then make sure you decrement or increment it?

With a for loop, you set everything within a single parameter().

/* first you set the counter*/
//var x = 4;
/* then you set the condition*/
//x != 0;
/*finally, you decrement or increment
depending on your condition
*/
//--x
//Now let's install the batteries
for(var x = 4; x!= 0; --x){
  //we're ready to loop
}

Remember that rendering task you had to do earlier? Here’s the solution using a for loop.

//we can see here that Becky has accumulated a rounded total of four stars
var becky = {name:'Becky Star', stars: 4}
var starRow = '';
//====Profile
//Mock profile name
console.log(becky.name)
//rendering with the for loop
for(cnt = becky.stars; cnt != 0; --cnt){
  starRow += render();
}
starRow; // > '****'

//Dummy render function
function render(){
  return '*'
}

Breaking loops

A loop continues to run until the condition is false. Sometimes we might want to break out of the loop–Inception-style–with the keyword break.

//this is a potential infinite loop
while(true){
  console.log("I'm free!");
  break; // phew
}

You might encounter a problem that requires a nested for loop.

var matrix = [[1,2,3],[4,5,6],[7,8,9]];
//prints 1,2,3,4...
for(var outer=0;outer < matrix.length; ++outer){
   for(var inner=0;inner < matrix.length; ++inner){
    console.log(matrix[outer][inner])   
   }
}

Writing a break statement in the inner for loop will break the inner loop, but the outer loop will keep running.

var matrix = [[1,2,3],[4,5,6],[7,8,9]];
//prints 1,2,3,4...
for(var outer=0;outer < matrix.length; ++outer){
   for(var inner=0;inner < matrix.length; ++inner){
      if(matrix[outer][inner] === 2){
        break;
      }   
   }
}

If you want to break completely free of every loop, you need to label your loops. You prepend your for loop with any name you want followed by a colon. Then, when you’re ready to break the loop, you append your label name after the break keyword.

labelName: for(){
  for(){
    break labelName;
  }  
}

Here’s our modified nested loop.

var matrix = [[1,2,3],[4,5,6],[7,8,9]];
//the for loop can start on a newline
outer:
for(var outer=0;outer < matrix.length; ++outer){
   for(var inner=0;inner < matrix.length; ++inner){
      if(matrix[outer][inner] === 2){
        break outer;
      }   
   }
}

Continuing loops

The continue directive allows us to skip steps in a loop. Perhaps the directive should’ve been called skip, but, alas, we’ll make do with continue.

for (let i = 0; i < 10; i++) {
// if i is even, skip the rest of the code.
  if (i % 2 == 0) continue;

  console.log(i); // 1, 3, 5, 7, 9
}

Pro tip: Curly braces are not required if the block of code can be written in one line.

Summary

We conquered if/else if/else statements, tackled switch statements, and untangled whiledo while, and for loops. We also learned how to break loops and continue them. Next, we’ll learn how a JavaScript program flows around functions.

Please follow and like us:
0

Learn JavaScript by Building a Game(Part 2)

January 31, 2019 Posted by Programming 0 thoughts on “Learn JavaScript by Building a Game(Part 2)”

In the first part of this series, we went through some of the basics of JavaScript. By the end, we were creating events to ensure that the score would change once you hit a frump. Now that we’ve got a handle on some of our problems, we’re ready to piece together our game. In this part, we’ll start by getting a handle on our animation.

Animation

var el = document.getElementsByClassName(“frmp-hd”)[0];
anime({
targets: el,
left: “-40px”,
direction: “reverse”
});

This is a really simple animation. All I did here was shift the position of the first frump head to the left. Then, I allowed the animation to play in the opposite direction to hide the frump head. All of these options are baked into the animejs library. Check out the amazing documentation right here.

Now that we’ve animated our frump, we need to randomize its appearance. 

Randomization

Wrapping Math.random() in Math.floor() will allow us to randomize our array of frumps. Below, I’ve created a function that will return a random number.

function rand() {
return Math.floor(Math.random() * 7);
}

Because we have 6 frumps, we need to multiply Math.random() by 7. That gives us a range of random numbers from 0 to 6. You can practise generating your own range of random numbers at W3schools.

Now we can plug our rand() function into the bracket notation. Remember, all our function does is output a random number. Every time we reload the browser, we should see a random frump appearing. 

var el = document.getElementsByClassName(“frmp-hd”)[rand()];

Animation Loop

setInterval() will be a suitable tool for our simple game. It takes a callback function and an integer. The integer that we’ll put in the parameter is in the form of milliseconds. 5000 milliseconds equals 5 seconds.

Warning: Due to JavaScript’s event loop, setInterval() may not work as you expect. You might find that instead of 2 seconds, it may take 4 seconds for your code to execute. 

Want to learn a bit about the event loop? Read our article about that topic.

setInterval(function() {
// We can plug our animation in setInterval() to loop the animation
},5000);

Now frump heads will appear every five seconds. Play around with the intervals of this extremely basic animation setup to get familiar with setInterval. If you want a more in depth explanation, check out JavaScript.info’s animation article

Conclusion

That’s it for this part of the tutorial. Animations are a crucial part of gaming. Without them, games are drained of what makes them so fun. Hopefully this section has taught you a bit about how JavaScript can be used beyond websites. Until next time, keep coding.

Please follow and like us:
0

Ultimate List Of JavaScript Functions

January 15, 2019 Posted by Programming 0 thoughts on “Ultimate List Of JavaScript Functions”

You’re an aspiring web developer who after breezing through HTML and CSS, are now embarking on the stormy sea of JavaScript. In order to realize your dream you must learn the most essential aspects of this scripting language. You’ve gotten through some basics of JavaScript but you can’t seem to make sense of JavaScript functions. There are so many of them and they’re rarely organized in a format that progresses through each and every one of them.

Let this article be your reference to all of the important functions you need to know to build a modern website. But first, let’s look at what JavaScript code looks like without functions.

Life without Functions

let pets = 35;
let owners = 15;
let petsPerOwner = pets / owners;
//======Pet Info Formlet answer = prompt("how many pets do you have?");
//============ 
// update based on answer, add new owner
pets += answer / 1; 
//  coerce string into number
owners += 1; 
// register new ownerp
etsPerOwner = pets / owners;
//test`There are now ${petsPerOwner} pets per owner at Pet Nirvana `;

Is that easier to read than this?

Life with functions

let pets = 35;
let owners = 15;
let petsPerOwner = average(pets, owners);
let answer = prompt("how many pets do you have?");
registerPets(answer);
registerOwner();
updateAvg(); 
// update based on answer, add new owner
console.log(`There are now ${petsPerOwner} pets per owner at Pet Nirvana `);
function average(total, number){  
return total / number;
}
function registerPets(newNum){  
pets += Number(newNum); // register new pet(s)
}
function registerOwner(){  
++owners;
}
function updateAvg(){
// find new average, round up  
petsPerOwner = Math.ceil(average(pets, owners)); 
}

Besides legibility, you can also see how much easier it is to do our job when we have all these built-in functions provided for us. Math.ceil rounds up and log() helps us debug code. Also, notice how the first example still uses a function for pure necessity.

Without functions, there is no JavaScript, at least all the good parts of JavaScript .

Anatomy of a Function

function multiply(x, y){  return x * y;}
function // keyword for decleration
multiply // function 
name(x,y)   // parameters
return x * y; // a return statement allows 
              //the function to produce value

A function has a parameter or parameters. We can name them whatever we like, just like variables. Though, we should think of parameters more like references rather than storage. We’re telling the function that we’re expecting some variable or data type to be plugged into this space by the user. We then operate on the parameter names within the body of the function.

More times than not, you’ll want to make sure you return your expected result. Not doing so will produce undefined when you invoke the function. If you intend to use your function to set value, include the return keyword.

Return

The return statement can return any data type.

Numbers:

return 2;

Strings:

return "hello";

Null:

return null;

Undefined:

return undefined;

Arrays:

return [1,2,3];

Objects:

return {one: 1, two: 2, three: 3};

Functions:

return function(){return "I'm in a function";}

Invoking a function

You invoke a function by adding () to its name. If the function requires parameters, you must enter them or you’ll get an error.

function multiply(x, y){  
  return x * y;
}
multiply(2,2); // 4

You can invoke a function before its declaration and it’ll still work. This is called hoisting.

multiply(2,2); // 4
function multiply(x, y){  
  return x * y;
}

Function notations

When a landmark or a thing is significant in any human language, there’s often more than one way to declare its name.

Fun fact: In Classical Arabic, there are hundreds of ways to name a camel.

Similarly, functions are so important to JavaScript that there are numerous names for them depending on the context in which they’re used.

Function Declaration

You have the tried and true function declaration:

function greet(){  return 'hello';}
// we can the call or invoke this functions
greet(); // 'hello'

Function Expression

You also have a function expression. It’s called a function expression because you’re assigning a function to a variable:

let greet = function(){  
  return 'hello';
}
// we can still call or invoke this functions
greet(); // 'hello'

One important thing to note is that hoisting does not work with function expressions.

greet(); // undefined
let greet = function(){  
  return 'hello';
}

Anonymous Functions

The function keyword(function()) without a name after it is called an anonymous function. Es6 introduced a new way to write an anonymous function. Instead of using the function keyword, you can delete it and add the arrow operator => to the parenthesis.

let greet = ()=>{  
  return 'hello';
}

For the most part, the difference in syntax was introduced to satisfy purists who are fond of writing minimal code. Though, the arrow function does introduce auto binding. Instead of getting overly technical, we’ll show you what auto binding is later.

Anonymous functions are versatile. You can set them as a value to a key in an object literal:

let person = {  
  name: "Mark",  
  greet: function(){    
    return 'hello' + ' ' +  this.name;    
   }
 }; // end of object literal
person.greet();

Note: this refers to person within our anonymous function. We could have just as easily wrote person.name.

Callback Functions

Anonymous functions can also go in a parameter. Doing so turns the anonymous function into what’s called a callback.

//here's a function expression
let greet = (callback, times)=>{  
  for(let cnt=0; cnt < times; cnt ++){      
    console.log(callback()); //it doesn't return.                              //This will cause a side effect  
   }
}
//here's our anonymous func AKA callback
greet(()=>{return 'hello'}, 3);
//we could have written it like this:
greet(function(){return 'hello'}, 3);

Note: Remember when we talked about the anatomy of a function? When you define a function, you create a mock up. The callback just takes advantage of that because we can wait for the function to arrive. We’re telling the interpreter that we want to invoke the function when it arrives by attaching () to our parameter name.

Closures

A function within a function is called a closure:

// We have two functions. One is named outie and the other is named closure
function outie(){  
// this is closure's first and only outer scope  
  function closure(){   
    // this is closure's local scope  
  }
}

Context:

Now is a good time to address context. Functions create their own context, which effects the this keyword, but if we wrote a closure within an anonymous function, this would refer to our function. Thus, we’d get undefined.

Here’s an example:

let person = {  
  name: "Mark",  
  greet: function(){        
    return function(){ 
      return 'hello' + ' ' +  this.name;      
     }        
   }
}
// double invoke ()() can invoke a returned closure
person.greet()();// >'hello undefined'

To fix the problem, developers just set this to a variable to preserve the context. In other words, we’re binding this. Starting to see what auto binding may entail?:


greet: function(){  
  let self = this;     
  return function(){ 
    return 'hello' + ' ' +  self.name;    
   }     
 }

An alternate solution is to explicitly call bind(this) on the closing bracket of a function.

greet: function(){     
  return function(){        
    return 'hello' + ' ' +  this.name;    
  }.bind(this)      
 }//end of excerpt

It looks ugly, but it works.

Pro Tip: Remember the new ()=> sytax? The example above gives a good example of why we need auto binding. Before, you had to remember to bind this in a variable like we had to do earlier. Now, you just use the new syntax and, wala!, you have a functioning this keyword. Try it out by rewriting the closure.

The final solution is to use the ES6 arrow function.

greet: function(){    
  return ()=>{        
    return 'hello' + ' ' +  this.name;    
  }      
}//end of excerpt

Note: Using the arrow function on the outer anonymous function destroys context. Because the arrow function binds automatically, you will be binding this to a context outside of the person object. So, this.person would no longer work.

IIFE

A function that calls itself is called an Immediately Invoked Function Expression(IIFE).

(function(){  return 'hello'; //'hello'}());

You can still do anything that you can do with other functions. You can set parameters and use the “invoker” () to feed in data.

(function(name){  return name;   // 'hi'}("hi"));

You can set an IIFE to a variable, but you have to declare the name. You don’t have to invoke it though.

var greet =(function(name){  return name;   }("hi"));
greet // 'hi'

Function Mania

We can use IFFE’s and closures, combined with anonymous functions, to create an android.

//function expression
let android = (function(){    
  //==private    
  this.name = "Mark VI";    
  //declaration    
  function addStrings(){       
    return "hello" + " " + this.name;    
  }    
  function setName(name){      
    this.name = name;    
  }    
  //==public: we're just returning an object.    
  return {  
  //anonymous functions       
    setName:(name)=>{          
      return setName(name);        
      },            
    greet: ()=>{
      return addStrings();        
     }   
  }
}());//IIFE
android.setName("Raj");android.greet(); //'Hello, I'm Raj'

The code above takes advantage of all that functions give us to produce a functioning object. It manages its own state, meaning that any changes we make will be saved. So, if we set a new name, and tell the android to greet us, it will greet us with that new name. That’s some powerful stuff! We will learn more about object oriented programming in another chapter.

Note: Oftentimes, developers wrap JavaScript code with an IFFE if they want their code to run without having to be triggered by an event.

Summary

It may be hard to keep track of all of these different type of functions, so let’s list the different function types.

  • Declared functions
  • Anonymous functions
  • Callbacks
  • Closures
  • Immediately Invoked Function Expressions
Please follow and like us:
0