fbpx

Posts in Programming

Understanding JavaScript Data Types and Variables

October 17, 2018 Posted by News, Programming 0 thoughts on “Understanding JavaScript Data Types and Variables”

Welcome, Fresh Coders!

If you’ve ever had the pleasure(or displeasure)of sitting through an Algebra 1 class, you’ve probably heard about variables. You know, x + 4 = 6 and all that good stuff. Don’t worry. JavaScript variables are much less scarier. You get to declare them so that you know exactly what they are. And, for the love of all that’s holy, don’t name your variables x or y or z. Give them reader-friendly names so that you’re not staring at a quadratic equation by the time you’re finished coding.

First, before we start messing around with variables and learning what variable deceleration even means, let’s learn to need them. By that I mean let’s get a little cozy with operators and data.

Data Types

Open up your Twitter or Instagram account and you’re hit with a log in screen prompting you to enter your information. When you enter your username and password, you’ve just entered data. You fill out a survey, you like a post, you order ten fidget spinners on Amazon — all of that is data.

In JavaScript, this data is divided into three groups:

1 ) Numbers

Numbers are exactly what you’ve known them to be all your life — 1, 50, 22.3, 5…Integers, decimals, fractions.

JavaScript is real friendly when it comes to numbers, because you don’t have to specify the type of number. We call this behavior untyped. JavaScript is untyped because determining whether a number is an integer or a decimal(float) is taken care of by the language’s runtime environment.

Why don’t you try entering typeof 5 into the editor and hit the run button. You should get 'number'.

Pro tip: typeof 5 is called a statement. You wrote JavaScript code and expected to get a value in return.

2) Strings: “Hello there”

Strings are simply fields of text. Even the words you’re reading now form a string. To encase these words, we use quotes. Keep in mind that strings aren’t limited to run-on sentences.

In JavaScript, this is also a string: "123";

typeof "1,2,3";
typeof "hello world";

You can probably guess by now that your passwords are stringy bytes of data.

3) Boolean: True, False

Don’t let the name throw you off. It’s the namesake of the mathematician George Bool. Booleans only have two values: true and false.

typeof true;
typeof false;

As you’ll come to know, these are important values when it comes to adding logic to our programs.With just those two values, you can create a complex system of loops and conditions.

But let’s not get ahead of ourselves. We will explore the depths of conditions and loops another time.

For now, let’s move onto what makes all of this data worthwhile.

Operators

What’s the use of data if you can’t do anything to it? That’s where operators come in. Each data type (Numbers, Strings, Boolean) share a set of operators that you can use to come up with nifty solutions to problems. There are four important categories of operators that you’ll use throughout your time as a JavaScript developer and they are

1)Arithmetic Operators

addition +

Number:1234 + 4579;

String:"hello" + "Jerry";

Yes, you can add a string. There’s a fancy term for this called string concatenation. Notice how the two strings glob together. We can solve this problem by adding an empty string in between.

"hello" + " " + "Jerry";

Boolean: true + false;

Performing arithmetic operations on boolean values actually returns a value. In this case, the value 1 isn’t just any ordinary 1. It’s a bitwise 1. In the language of computers, this translates to true. So, we can conclude that true plus false equals true.

Why is that so? You’ll understand once we turn true and false into what our computer actually sees.

computer:
true: 1, false: 0
result:
1 + 0 or 0 + 1 = 1

subtraction –

Number:1234 - 1234;
String: NaN Note: NaN(Not a Number) is the error you’ll get when you try to subtract String values.
Boolean: true - false; or false - true;

division /

Number:1234 / 1234;
String: NaN
Boolean: true / false; or false/true;

multiplication /

Number:1234 * 1234;
String: NaN
Boolean: true * false; or false * true;

modulo %

This cool operator tells us the remainder of a division of two values.

Number: 10%3;String: NaNBoolean: true % false; or false % true;

Increment ++

++ is a fancy way to say add 1 to any value. It matters where you put the incrementer. Oh, and by the way, we need variables now. JavaScript’s interpreter can’t read ++10 if 10 is not saved inside a variable. why? Because plus, plus is what we call syntactic sugar. It’s something that was created to make life easier for developers, because it turns out we’re pretty lazy. Instead of saying 10 + 1, we get to forgo adding the 1. Since plus,plus is technically not a real arithmetic operator, you need to define a variable so that you won’t get errors.

Before we start our lesson on variables, try playing around with them. Type this into a code editor:

var cookies = 5;
console.log(cookies++); > 5
console.log(++cookies); > 7

The variable names are arbitrary. You can name them whatever you like. As we’ll explore later, it’s best to name them appropriately.

Pro tip: var cookies = 5; is called an expression. You defined what value cookie has but you didn’t ask for its value. As you learned earlier, this would be a statement: cookies;

Note: console.log() is a web tool that prints JavaScript code to a console. Every web browser has a console you can access. This “web tool” is really called a Web API. It’s much easier to think of API’s as a set of tools that make your job a whole lot easier.

So…why are we not getting the values we expect???

Well, writing the variable before ++ gives us the original value before it can be incremented and vice versa.

Think of it this way: we asked the baker for 5 cookies before he knew we wanted to add one more to the order(cookies | ++).

We receive a receipt saying we ordered five, but when we ask for one more, the baker runs back to get us one more(so, we have 6 cookies now).

The baker returns, but we ask for one more again(++ | cookies).

Finally, when we ask for our cookies, our total is 7 cookies.

JavaScript’s interpreter is that poor baker when it comes to incrementing and decrementing.

decrement — –

Number: -- number

String: NaN
Boolean: --true

+= Plus Equals, and -= Minus Equals, and *= Times Equals, and /= Divided Equals

It turns out programmers are lazier than you thought. Yes, there are more arithmetic shortcuts.

Say you have var score = 5; and, instead of incrementing score by 1, you want to increment it by 6.

Normally you’d write score = score + 6;

With Plus Equals you simply have to write it as score += 6;
Why don’t you try it out with different operators?

2. Comparison Operators

logical operators return true or false. Without them, we wouldn’t have all of the apps that are available to us.

operators

equals ==
not equal !=
greater >
less <
greater/equal< =
less/equal> =

There’s also a special triple equals(===). This checks to make sure that the types are the same as well.

Try this out: 3 == '3';. You got true, right? The fact that JavaScript ignored our stringed ‘3’ can cause some unwanted bugs. To fix this, add another equals. Now you should get false. That’s because triple equals also ensures that the types are exactly the same as well.

Operators are useful for conditional logic. Let’s use an if/else statement to test out an equals operator.

If ('you feel overwhelmed by this new topic'){
 'Do not worry. Sometimes the best way to learn is to try and fail'
}else {
 'Let's get this show on the road!'
}

Try this real if/else statement.

if(2==3){
 console.log('correctomundo');
}else {
console.log('wrooong');
}

Note: the end of if statements don’t receive semi-colons. Here’s a pro tip: Exclude them from any statements or expressions ending in a bracket.
Be sure to use different data types in your if/else statement. You can even play around with all of the operators you’ve learned so far.

3. Logical Operators

Logical and &&, Logical or||, Logical not !

Logical operators allows us to add complexity to our conditional statements. Practically, if you want maximum control over a condition, you’d use && because all of the conditions must be met in order to be true. Conversely, if you want the condition to be more inclusive, you’d use || because only one condition has to be true to get a return value of true.

if(2==2&&3==3&&3==2){
 console.log('correctomundo');
}else {
console.log('wrooong');
}

Variables, Finally!

So, you were introduced to variables prematurely. Even then, you saw how badly we needed a variable in order to get the increment and decrement operator working.
Now, let’s think of numbers, strings, and booleans as Snap chat photos that ghost away after a short period. They don’t stay around long enough to be useful. If you want to use the same data, you’d have to re-type it somewhere else in your JavaScript file.

Imagine having to write this formula over and over again: 1/2(60 * 120);

Or this really long string: "superkalafragilisticespialadocious";.

What a variable does is allow us to save data so that we can use it again.
Let’s declare two variables

var triangleArea, poppinsQoute;

Now for some takeaways:

The var keyword creates what’s called a global variable. It’s like taking a shower in public. Everyone can see you. In JavaScript, we have blocks, like neighborhood blocks. Within our if/else statements, we wrote a block of code that only ran based on certain conditions. Those two variables can be accessed within that block, because we declared them in a global scope.

Think of scope as perspective. From the perspective of the outside, we can’t always see what is inside someone’s house. But from the inside, we can see everything that’s outside.

We shouldn’t be able to look inside an if/else statement and see its local variables. Local variables are variables that are declared within a block.
pro tip: any code within curly braces form a block.

if(3==3){
 var number = 3;
}

Notice the assignment operator. In this example, I’ve declared and initialized my variable at the same time. The equals sign in this case is not the same as the equal sign you use in math. It simply means that you want to assign particular data to a variable you made up. The operator used is called an assignment operator.

Alright. Remember what I mentioned about global and local variables. You’re probably guessing that if I were to use this variable outside of the block, we should get an error.

if(3==3){
 var number = 3;
}
console.log(number);

Wait…we were still able to access the variable outside of the block. Did we just acquire X-Ray vision? So all this talk about local and global variables must be a lie then, right?

Well, the problem with the var keyword is that it loves to expose itself in public. Even if it’s defined within a block, it’ll still want to be seen by everyone. The only thing that can tame it is a function.

function test(){
  var number = 3;
}
console.log(3);

We will get into functions another time, but all you need to know for now is that functions create their own scope. They’re like highly secured mansions.
That’s all fine and dandy that functions are so secure, but how do I secure an if/else statement?

There is a new way to declare variables as of Es6. Every so often Ecma International comes up with new ways for us to code in JavaScript. What they’ve come up with to solve this issue is the let keyword.

Let’s use it!

if(3==3){
 let number = 3;
}
console.log(number);

Great. Now we truly have global and local variables.

Going back to our original variable declarations, var triangleArea, poppinsQoute;, you can see that we are able to declare multiple variables at the same time by separating them with a comma. Also, look at how the second word in the variable name starts off with a capitalized letter. This convention is called camel case. It’s good to stick to this convention so that your code is legible to you and to others that might look at your code one day.

The Variable Warehouse

We’ve messed around with variables a little, but we haven’t pushed them to the limit. Let’s see what we can put inside of a variable.

numerical statement

triangleArea = 1/2(60 * 120);

strings

poppinsQoute = "superkalafragilisticespialadocious";

boolean

let true_ = true;

Wait. Why the underscore? See, you can’t name a variable anything that is already named by those who’ve designed the language. Just make sure that you don’t start naming your variables with numbers: 123true.

logical statement

let check = (2==2&&3==3&&4==4);

The parenthesis is there for readability. You can plug this right into your if statement and it’ll work beautifully.

if(check){
 console.log("true");
}

Pro tip: I did not have to type check === true because the if statement automatically checks for true or false.

functions

var myFunction = function(){
  return 'hello';
}

variables also consume functions. These functions are called anonymous functions because they aren’t named.

arrays

var myArray = [1,3,4,5];

Arrays are a collection of data.

objects

var myObject = {me: "too", save: "me"};

Objects also hold a collection of data.

Other variables.

var newVariable = oldVariable;

Multiple variables!

var varOne = varTwo = varThree = 1;

Don’t try this one at home, because it has unwanted side effects. Variable assignment works from right to left. So in order for varOne to finally receive value, the other two variables are pushed to the global scope automatically. This means even functions won’t recognize varTwo and varThree as local variables. This is called leaking and is a pretty big no,no.

Closing Note

Variables are here to stay so make sure you get into the habit of using them. Whenever you find yourself using the same data type repeatedly, try sticking it into a variable. You’ll be happy you did.

Please follow and like us:
0

Node.js Foundation and JS Foundation Announce Intent to Create Joint Organization to Support the Broad Node.js and JavaScript Communities

October 4, 2018 Posted by News, Programming 0 thoughts on “Node.js Foundation and JS Foundation Announce Intent to Create Joint Organization to Support the Broad Node.js and JavaScript Communities”

The Node.js Foundation and JS Foundation today announced an intent to merge. A Q&A session will be held onsite at Node+JS Interactive from 7:30am – 8:30am PT, October 10 at West Ballroom A. Anyone attending Node+JS Interactive is welcome to attend; questions can be submitted in advance anonymously via this Google Form.

Leaders from the Node.js Foundation Board of Directors, Technical Steering Committee and Community Committee will join representatives from the JS Foundation Board of Directors and Technical Advisory Committee to facilitate the discussion, answer questions and solicit community input on the possible structure of a new Foundation. Joining forces will not change the technical independence or autonomy for Node.js or any of the 28 JS Foundation projects such as Appium, ESLint, or jQuery.

JavaScript is a versatile programming language that has expanded far beyond its role as a backbone of the web, entering new environments such as IoT, native apps, DevOps, and protocols. As the ecosystem continues to evolve — moving from browsers to servers, desktop applications to embedded devices — increased collaboration in the JavaScript ecosystem is more important than ever to sustain continued and healthy growth.

“The Node.js Foundation and JS Foundation boards have met several times already to discuss a potential alignment of the communities. The Foundation leaders and key technical stakeholders believe that a tighter alignment of communities will expand the scope of the current Foundations and enable greater support for Node.js and a broader range of JavaScript projects,” said Mike Dolan, Vice President of Strategic Programs, the Linux Foundation.

“We are very interested in hearing directly from the community and welcome all questions, ideas and opinions so that the structure aligns with the expectations of the community. For this reason, no formal decisions regarding a merged Foundation and its potential organizational structure, governance policies, technical framework or leadership have been made at this point and will be formalized based on feedback from the community.”

Additional goals for a merger include:

  • Enhanced operational excellence;
  • Streamlined member engagement;
  • Increased collaboration across the JavaScript ecosystem and affiliated standards bodies;
  • An “umbrella” project structure that brings stronger collaboration across all JavaScript projects; and
  • A single, clear home available for any project in the JavaScript ecosystem.

Today, JavaScript is nearly ubiquitous. Enterprises have been able to greatly reduce training costs and increase developer productivity because frontend JS developers can work on the server side, and vice-versa, eliminating the context switches and enabling all developers to pull from the same knowledge base and vast module ecosystem. Node.js is a major catalyst for this growth. It has become an important part of the modern web development stack and is often the assumed default when working with JavaScript. Merging the Foundations will bring the governance of these technologies in line with its real-world use.

“JavaScript is at the core of an ecosystem of technologies that form the backbone of the web and play an increasingly vital role across industry and society,” said Dan Appelquist, Director of Web Advocacy & Open Source at Samsung Research UK and JSF Board Member. “Strong governance, encouraging inclusive contributor communities and engagement in the ongoing standards development are all important factors in ensuring this ecosystem continues healthy development. A merged foundation is well positioned to deliver on these goals.”

“The possibility of a combined Foundation and the synergistic enhancements this can bring to end users is exciting,” said Todd Moore, Node.js Board Chairperson and IBM VP Opentech. “Our ecosystem can only grow stronger and the Foundations ability to support the contributors to the many great projects involved improve as a result.”

About the Node.js Foundation
Node.js is used by tens of thousands of organizations in more than 200 countries and has around 10 million users. It is the runtime of choice for high-performance, low latency applications, powering everything from enterprise applications, robots, API engines, cloud stacks and mobile websites.

The Foundation’s membership base includes Platinum members Google, IBM, Intel, Joyent, and Microsoft. Gold members include GoDaddy, PayPal, and NodeSource, and Silver members include Bitnami, Chef, Dynatrace, Fidelity, Groupon, HackerOne, NearForm, npm, Oath:, Profound Logic, Red Hat, RisingStack, SafetyCulture, Sauce Labs, Snyk, and YLD. Get involved here: https://foundation.nodejs.org.

About the JS Foundation
The JS Foundation’s mission is to drive broad adoption and ongoing development of key JavaScript solutions and related technologies through ongoing efforts and services such as mentorship programs, events and support of web standards. The JS Foundation works to facilitate collaboration within the JavaScript development community to ensure its projects maintain the quality and diverse contribution bases that provide for long-term sustainability.

The Foundation is supported by members IBM and Samsung (Platinum); Accenture (Gold); and Agile FAQs, Blog Starter, BLOQspace, Bocoup, BrowserStack, Cloud Grey, Kenzan, Particle, Ripple, Sauce Labs, SitePen, Sourcegraph, StackPath, WebsiteSetup, and White October Events (Silver). Learn more about the members who support the Foundation and how to join at https://js.foundation/about/members.

Please follow and like us:
0

Code JS in Stlye: Early Return

October 4, 2018 Posted by Programming 0 thoughts on “Code JS in Stlye: Early Return”

There comes a point in the life cycle of a project that we no longer have to worry about whether or not the darn piece of code works in the first place. We’ve got to look back and see if the darn piece of code has style.

In this series, we’ll explore how we can write code that’s worthy of the runway.

Today, we will be implementing the early return.

The IF Spaghetti

When we’re controlling the flow of data within a function, it can be tempting to use only a single return statement. A variable will be assigned a new value depending on a condition.

function divider(dividend, divisor){
   let response;
   if(isNaN(dividend) || isNaN(divisor))
   {
     response = "Error: input a number";
   }
   else if(divisor === 0)
   {
    response = "Error: cannot divide by 0";
   }
   else 
   {
    response = dividend / divisor;
   }
return response;
 }

Note: Admittedly, that else block is a stretch.

The code above has a single exit point(return statement), which is fine if you’re thinking in terms of functional logic. When we learn about functions for the first time, it’s ingrained in our being that you only return once. A function is a dog and a dog only has one tail, the return statement. Logically-speaking, the notion of multiple exit points can appear confusing…like a dog with multiple tails. “Which tail will the dog wag next?” is the sort of thing a cynic might say about functions that have multiple returns.

But a single exit point in a maze can create a game of cat and mouse as we peruse through nested conditions. If you looked at the earlier code example long enough, you may have gotten that nagging feeling that said, ‘if the condition is met, why are we not exiting right now? Why do we have to wait?’

It’s as if we reached a possible exit after meeting a condition, only to be funneled to a waiting room. Think: your flight’s delayed after meeting the condition of booking your ticket and being there on time. Yeah, rough.

Conversely, we can use early returns.

function divider(dividend, divisor){
   if(isNaN(dividend) || isNaN(divisor))
   {
     return "Error: input a number";
   }
   else if(divisor === 0)
   {
    return "Error: cannot divide by 0";
   }
return dividend / divisor;
 }

Multiple exit points allow us to make sense of the logic. Sometimes, we need to be reminded that we’re still within a function as we traverse conditions.

When you think about early returns in terms of pseudo code, you’ll realize that early returns are succinct.

If a condition is true 
  return value.

As opposed to,

If a condition is true
 assign a value
the value may or may not change...
return value

There’s less ambiguity, less confusion, and more assurance with early returns. It feels good to know that if you have a base case that handles invalid input, you are exiting the function immediately.

Doing otherwise is akin to dragging your feet, saying, “Yeah, yeah I’ll take care of that later.” Then, assigning the task of garbage disposal to someone else.

if(hackyInput)
{ 
  return; //!!!!
}
//vs
if(hackyInput)
{ 
  handleLater = ERROR_MSG; 
}

Sprinkling More Style

All of this code can be stripped down by deleting all of those brackets.

function divider(dividend, divisor){
   if(isNaN(dividend) || isNaN(divisor))
     return "Error: input a number";
   else if(divisor === 0)
    return "Error: cannot divide by 0";
return dividend / divisor;
 }
if(hackyInput) return; //!!!!
//vs
if(hackyInput) handleLater = ERROR_MSG;

Thoughts?

Of course, all of the above should be taken with a grain (or a couple more) of salt. At the end of the day, it is a style of programming. There is a time and place for early returns just like there’s a time and place for fanny packs(is there?).

It would be responsible to include a disclaimer. So here it is:

When you abuse the return statement by placing it in the middle of code, or, worse, a callback, you can create a hellish “Where’s Waldo?” debugging scenario. When your logic is bursting at the seams with complexity, so much so, that you need multiple returns to diffuse some of that complexity, then early returns become a crutch, rather than a tool. In that case, you may want to decouple your code, which is a nice way of telling you to nuke it.

Semantically, an early return should signify to the code reviewer that your first validation is make or break. The function cannot run without the condition being met. In that case, the early return reads more like a fail safe than clever coding.

At the end of the day, good style is in the eye of the beholder…for the most part.

Please follow and like us:
0

Google launches a sneak peak of Flutter, its Android and iOS mobile app SDK

September 21, 2018 Posted by Apps, News, Programming 0 thoughts on “Google launches a sneak peak of Flutter, its Android and iOS mobile app SDK”

At Google Developer Days China today, Google launched the final developer preview of Flutter, the company’s open source mobile UI framework that helps developers build native interfaces for Android and iOS. Flutter Release Preview 2 is the last major milestone before the stable Flutter 1.0 release, which is slated to arrive later this year.

If you already have Flutter installed, just type the command flutter upgrade to get the latest build. If you don’t, follow the getting started guide for Windows, macOS, or Linux.

This is the sixth preview. Flutter was first announced as an early alpha at Google’s I/O developers conference in May 2017. The first beta arrived in February, followed by two more, and then two release previews. Meant to compete with frameworks like Facebook’s React Native, the library is designed to combine the performance and platform integrations of native mobile with the rapid development and multi-platform reach of portable UI toolkits. Flutter apps are built using Google’s Dart programming language.

Flutter Release Preview 2

Flutter Release Preview 2 includes support for executing Dart code in the background, even while the application is suspended. Plugin authors can use this to create new plugins that execute code upon an event being triggered, such as the firing of a timer or the receipt of a location update.

Flutter adoption

Google says new developers are continuing to adopt Flutter. The company notes that thousands of Flutter-based apps have already made it to the Apple App Store and Google Play, even before version 1.0, including some of the world’s most popular: Alibaba (Android, iOS), Tencent Now (Android, iOS), and Google Ads (Android, iOS).

Flutter has also broken into the top 50 active software repositories on GitHub:

On StackOverflow, Flutter activity (new questions being posted, answered, and viewed) is also on the rise:

For more information about Flutter, Google offers a slew of resources, including samples, hands-on videos, newsletters, community articles, developer shows, discussion groups, chat rooms, community support, and a weekly online hangout. Source

Please follow and like us:
0

Rick and Morty Teach JavaScript Hoisting

June 28, 2018 Posted by Programming 0 thoughts on “Rick and Morty Teach JavaScript Hoisting”

This is a fan-fictional representation of Rick and Morty. This post is not sponsored by the show.
Written by Raji Ayinla

Morty: Here’s a question I’d like answered. Why does this work? What is this Jedi nonsense?


sayMyNameSayMyName('Morty'); // 'I said your name, Morty.'
function sayMyNameSayMyName(name){
return `I said your name,${name}.`;
}

Rick: Hoisting.

Morty: Yeah, yeah, but what is hoisting exactly?

Rick: I will attempt to utilize the gerund that labels this quirky phenomenon to help with the definition. Here goes. Declarations, whether they are a variable or function, are lifted up to the top of your program.

Morty: Okay, that’s digestible. Sort of. But wait…so you’re telling me that this can’t be hoisted with the Force?


sayMyNameSayMyName('Morty'); // TypeError: undefined is not a function
var sayMyNameSayMyName = function(name){
return `I said your name,${name}.`;
}

Rick: Well, you see, declarations get special treatment. Assignments are second class, so to speak. They don’t get the privilege of being hoisted.

Morty: But why?

Rick:It’s the execution context. That’s to blame.

Morty: Execution what?

Rick: Every line of code has a context. There are two key contexts to keep in mind. You have the global and the function context. It looks like this:


/*Global--woohooo I'm freee*/
two(); // 2
function two(){
/*Function
========
*/
return 2;
}

Morty: Wait. Context is the same as scope, right?

Rick: *Sigh*

You have much to learn young Jedi. No, scope refers to access. If a variable is declared in a global scope, it can be accessed by functions or blocks. Functions are unicorns because they create their own scope. But that differs from context.
You see, we can all say that we are from planet Earth. That is our global context. But we cannot all say that we are from Washington DC. That is the function context. In JavaScript, you can determine the current context with the this keyword.

Morty: So what does context have to do with hoisting?

Rick: Yes, so…

First, imagine that the interpreter is an alien who found your signal and is now looking for you. The alien would start on planet earth, our global context. There are seven continents on Earth. It might start in North America.

Morty: Why?

Rick: It loves North America’s bizarre geometry.

Anyway, it will then create a scope chain containing your possible country, then your state, then your city, then your street.

Now, let’s try to look within the mind of JavaScript’s interpreter. When the interpreter reads code, it automatically enters the global context.

The interpreter does something similar to the alien’s search tactics by first looking for a function invocation(the signal). It won’t execute it until it can create the context(find your info).

There are two stages the interpreter goes through to accomplish its mission: the creation stage and the execution stage.

1) Mind you, we’re entering the creation stage.

A function can have multiple functions within it, so the interpreter will initialize a scope chain(country,state,city,street).

It will create a variable object to hold all sorts of arguments, parameters, and function/variable declarations.

It then creates this to store the current context.

This is an oversimplification. We’ll simplify it further by only concerning ourselves with how the interpreter deals with function declarations versus variable declarations.

Function:

When the interpreter’s nose bumps against a function keyword, it looks for the name. It then stores a reference to that function name in variables object.

Variable:

When the interpreter’s nose bumps against a var, let, or any keyword associated with variables, it first stores the variable name in variable objects. Then it automatically initializes it with undefined.

Can you start to see how assigning a function to a variable and hoping it will be hoisted does not work? When we invoke myNameIs(name), the interpreter will find our function expression, but it will only read in the variable name and assign undefined to it.


sayMyNameSayMyName('Morty'); // 'I said your name, Morty.'
myNameIs('Morty'); // undefined
//
function sayMyNameSayMyName(name){
return `I said your name,${name}.`;
}

var myNameIs = function(name){
return `your name is,${name}.`;
}

You’ll understand this more in the next stage.

2) The Execution Stage

In the execution stage, values are assigned to variables within the execution context.
The problem with calling myNameis() early is that the interpreter has assigned undefined tomyNameIs() in the creation stage. If you had invoked myNameIs() after the function expression, the interpreter would have had time to assign the value of myNameIs() within the global context during the execution stage.

Invoking sayMyNameSayMyName() works because a reference to the declared function is stored in the creation stage. When the code is executed, we’re able to run it without a problem.

Conclusion

Morty: So…hoisting is all about execution context?

Rick: Yep.

Please follow and like us:
0

4 Quick HTML Rules You Should Know

June 1, 2018 Posted by Programming 0 thoughts on “4 Quick HTML Rules You Should Know”

When I heard about arguments erupting at the work place over proper line spacing(double space or tab?), I though it was hyperbole. Like, really? I mean, I get fighting over the superiority of one language over another, but line spacing?

Then I joined a team to build an app and a problem arose: we coded HTML differently from one another. Style guides I’d read in the past stressed the use of double space, but, apparently, another member of the team liked using tabs because, “Sublime allows you to minimize elements based on tab spacing,’ he claimed.

We ended up agreeing on tabs because I’m a team player.

Looking back on it, I should have referenced the style guides that insist on double spacing. Anyway, that’s why I’m going to go through a rundown of the major rules for HTML. I’m also going to go over CSS rules in a future article because HTML and CSS go together like [insert horrible parable(bread and jam’s my choice, if you wanted to know)].

Jokes aside, agreeing on a universal set of rules is crucial for scaling and maintaining large apps. Of course, a pre-processor like Pug is a good mediator. That’s if you’re using Node.js for your back end, of course. You also have Slim and HAML for Ruby.


Pug Life

Really, don’t read the rest of this article. Just use Pug.

But if you insist on writing markup, here are four guidelines.

1) Filenames

Filenames must be lower case.

Good: pugs.html
Bad: Pugs.html

If you need your filenames to be longer than one word, they should be separated by hyphens.

pugs-are-in-the-kitchen.html
(more…)

Please follow and like us:
0

How To UX The Right Way

May 31, 2018 Posted by Programming 0 thoughts on “How To UX The Right Way”

When you look up the definition of User Experience, you get, “the overall experience of a person using a product such as a website or computer application, especially in terms of how easy or pleasing it is to use.”

That definition is misleading because it boils UX design down to pretty interfaces that two year olds can use. Let’s note that most users are not two year olds and aren’t using a product simply because it looks “nice.” Rather, we should define UX design as a system of design that recognizes a user’s problem and solves this problem by providing an interface that makes accessing the solution pleasing.

This means that we’re thinking of the product itself rather than features. Instead of trying to design the most vibrant, eye-popping User Interface, we’re designing functional interfaces that are legible to users of all backgrounds.

The Wrong UX

For an example of how not to UX design, you need look no further than Microsoft’s initial release of Windows 8. This much-loathed OS update is a perfect example of UX designers favoring candy-colored visuals over practical design.

Sure, Microsoft’s Metro UI looks modern and cool if you’ve got this hooked up to your entertainment system. You’ve got time to kill and the visual collage is effective at distracting you. But, one of the most sacred rules of product development is knowing your audience. Microsoft has over an 80 percent market share in the OS market and you can bet that a large portion of its costumer base are business owners and employees who simply use their OS to get work done on their PCs. They rely on Microsoft’s products to be stable, reliable, and easy to use.

Suddenly, in an organized work environment, all of the visuals speak of disorganization and confusion. As you may have guessed, some users erupted.

Microsoft’s designers assumed that placing the avant-garde features found within the latest smartphones at the time would make their product sought after.

What they failed to do was think with a product-first mindset. The designing of new features only served to bury the problem Microsoft’s product was supposed to solve. The problem being that Microsoft doesn’t want to teach everyone the command line so that they can access files. The solution? Make accessing files easy by designing a simple GUI.

So, the UX design should have correlated with the solution. Microsoft learned a costly lesson. Their mistake is history and the reason we learn history is to avoid repeating the same mistakes.

The Right UX

Let’s take Twitter’s home feed as an example of how to UX design the right way. As a product, Twitter offers users the ability to write messages that can be seen by anyone using their platform. Users should be able to have real time access to the tweets of other users that share similar interests. To solve this problem, Twitter’s UX designers implemented an endlessly scrolling timeline.

The most important aspect of this design is the buffer that holds incoming tweets. The designers understood that the product was a rapid-fire messaging system and designed around the problems that would arise from too many tweets loading on to the screen. The call to action does an adequate job of drawing the user’s eye to the tab. You don’t need a tutorial to use this feature. Now that’s solid UX design.

Conclusion

As a designer, it can be very tempting to follow the latest trends. Designers will always be designing. Jaw-dropping features may seem too irresistible to pass up. But before you add that awesome parallax scroll, think, how does this serve the user? How can I bridge the gap between product and design?

Please follow and like us:
0

5 Quick Reasons Why Microservices Prevent Headaches

March 29, 2018 Posted by Programming 0 thoughts on “5 Quick Reasons Why Microservices Prevent Headaches”

What Are Microservices?

Microservices are a modularization concept. Their purpose is to divide large software systems into smaller parts. Thus they influence the organization and development of software systems. Due to this modularization, microservices can be deployed independently of one another. Changes to one microservice can be taken into production independently of changes to other microservices.

Here Are Some Quick Benefits

  • Strong modularization
  • Easy replaceability
  • Sustainable Development
  • Highly Scalable

Now For The 5 Reasons

  1. Microservices can be implemented in different technologies. There is no restriction on the programming language or the platform for each microservice.
  2. Microservices possess their own data storage. A private database or a completely separate schema in a shared database.
  3. Microservices can bring their own support services along; for example, a search engine or a specific database. Of course, there is a common platform for all microservices—for example virtual machines.
  4. Microservices are self-contained processes. Bugs in one microservice can be more readily tracked as opposed to a bug in a monolith.
  5. Microservices communicate via the network. To accomplish this, microservices use protocols that support loose coupling, such as REST or messaging. This means you can create an API that branches out to all of your products.
Please follow and like us:
0

Understanding JavaScript Closures

January 2, 2018 Posted by Programming 0 thoughts on “Understanding JavaScript Closures”

When you’re first learning JavaScript, terms like “closures” may make the language appear mystical and hard to understand. But some of these terms are just sugary concoctions that give fanciful names to very simple concepts. If you’ve spent just a few minutes tinkering with JavaScript, you’ve probably used closures without knowing it. That’s because the JavaScript language depends on closures to create programs that are concise and efficient. By the end of this tutorial, you will gain a full understanding of closures.

What is a closure?

In order to really understand closures, it is helpful to know how scope works. We covered scope in a previous article, so we’ll quote it here:

“If you declare a function within another function, you create what’s called a scope chain.

The outer parent cannot see the variables of its child(ren), but the child can see the variables of its parent(s). Confused? Think of a Matryoshka doll. Now imagine if these dolls were given life(scary thought). An outer doll wouldn’t be able to see the gruesome innards of an inner doll. The inner doll can see everything. Now that’s scope.”

We can conclude that the inner function has three scope chains

The first chain allows the inner function to access its own variables. The second allows it to access the variables and parameters of the outer function. And the third allows it to access the global variables. Every time we add a function, we’re adding a new link to the chain.

By defining a function within another function, we create a closure. Closures themselves can also take on the role of outer functions. Take this somewhat practical example of multiple closures:

In this example, we have two closures. combineName() is a closure to the outer function of sayMyName(). getRandomInt() serves as both a closure to combineName() and sayMyName(). What this means is that combineName() has three scope chains while getRandomInt() has four scope chains. Every time we create a closure, one link is added to the scope chain. So, getRandomInt() can access the variables of combineName() and sayMyName().

Side Note: As you can see from the example, we were able to “borrow” the parameters from sayMyName and use them in our first closure, all thanks to the trickle down effect scope chains have, which, *ahem*, is far more reliable than trickle down economics. One point to note, however, is that you cannot call an outer function’s arguments object from within a closure.

 

Closures In Depth

We’ve briefly outlined what closures are. Now let’s go through some use cases and explore the deepest depths of closures.

Closures are basically the walking dead.

When a function returns, the idea is that all of the variables within that function should be non existent. Yet, closures still have access to any variables in their scope chains.

Here’s an example:

The reason why we can still access the name of this “zombie” isn’t due to any sci-fi magic, it’s because closures don’t store value. Values are static. Instead, they store references to values in their scope chains. The amazing thing is that if you were to change the value of a variable up in the scope chain before returning the closure, the same value used within the closure will then update. This phenomenon is called state, which is the backbone of programming. We want to be able to create functions whose inner data lives on through the lifetime of our apps. When a user inputs data, we want that data to be updated.

We’ll show an example of how we can use closures to create a modular pattern by modifying our above code:

What we’ve created is an anonymous closure by enclosing our first function within parenthesis.

(function(){…})();

Side Note: Anonymous closures or Instantly Invoked Function Expressions execute immediately and allow us to maintain state and manage privacy. Unlike other object oriented languages like C++ or Ruby, JavaScript is yet to implement any native private methods. There are several JavaScript developers who, after tasting ES6’s new class keyword, are pining for private syntax. For now, we have to make do with closures to code private/public data.

Any function or variable within our anonymous closure is considered private. The closures within the anonymous wrapper after the return statement have access to the private functions, but users cannot access the private functions outside of the module. The private data is effectively closed off by our anonymous closure, as most private things are.

 

Conclusion

Closures are a prime example of the flexibility of JavaScript’s functions. In just a few examples we’ve set functions to variables, returned functions, called anonymous functions, have used functions as keys, not to mention the fact that we self-invoked a function. All of these functional, acrobatic tricks all have terms that apply to them. Just remember that closures are those functions that are defined within another function.

Here are some great resources if you want to continue on with your journey in mastering closures and many more JavaScript quirks:

Closures
Understand JavaScript Closures With Ease
JavaScript Module Pattern: In-Depth
Practical Closures – iRi

Please follow and like us:
0

Understanding JavaScript’s that and .bind()

December 11, 2017 Posted by Programming 0 thoughts on “Understanding JavaScript’s that and .bind()”

 

If you’ve ever manipulated the DOM in JavaScript, you’ve probably come across the contextual this bug. You’re coding up an amazing click event, slamming the keys and feeling like a code ninja. You go to test your code in the browser and nothing works. this is undefined apparently. You realize that the this keyword in your makeButtonLightUp() function is referring to the local this rather than the this of your outer click function. You grumble because you know the solution and you know it’s hacky.

var that = this

Alternatively, you might call .bind() on your your function just to keep things interesting.Both solutions work, but why do they work and why do we have to implement them?

This answer requires knowledge of exactly what scope and context means in JavaScript. Pull up a chair and grab some popcorn. Things are about to get real interesting.

Note: The use of that as a variable is just a convention and not a rule. You can just as easily name the variable boogabooga.

Context vs Scope.

The terms scope and context at first glance just seem like synonyms and may leave you scratching your head when asked to differentiate the two. Both effect the behavior of your code in different ways. Simply put, scope refers to the viewability of variables and context refers to the accessibility of objects within a function.The confusion often lies in the relationship between scope and context. Let’s break them down further.

Each function you create has its own scope. When you declare a variable with a keyword like var, that variable cannot be seen outside the scope of that function. But, if you declare a function within another function, you create what’s called a scope chainThe outer parent cannot see the variables of its sibling(s), but the sibling can see the variables of its parent(s). Confused? Think of a Matryoshka doll. Now imagine if these dolls were given life(scary thought). An outer doll wouldn’t be able to see the gruesome innards of an inner doll. The inner doll can see everything. Now that’s scope.

Here’s a code example:

function firstFunc(){
  var firstVar = 2;
  firstVar += secondVar; // secondVar is undefined because scope doesn’t look down
  function secondFunc(){
    var secondVar = 5;
  }
}

In the case of our this dilemma, think context, not scope. Context is the object that a function, having been executed within said object, has access to. Even nested functions will still point to the parent object. The keyword often associated with context is this.

Context

To better understand context, let’s imagine a principal’s office. There are three children sitting in chairs and a scowling teacher, without pointing or gesturing, tells the principle “One of them threw a pencil at a student of mine.”

he principal answers, “Which one?” Because the context is global. He cannot properly execute his punishment function because the object is undefined

This one.” The teacher points at a freckled student.

The student is the object to which her this statement refers to. He can now execute his function on the student and has access to the student’s attributes.

Now, let’s imagine that this principle now wants to execute a new function within the dollOutPunishment() function called callParent(). Let’s also imagine that his mind cannot keep state, or, in other words, that he loses his memory after each function declaration and can only remember the global context of three boys. How would he be able to remember which child the teacher pointed out?

He’d have to preserve that name in a variable in order to keep track of the proper context.

So, How Does “This” Work?

So, keeping this example in mind, let’s look at ECMAScript’s definition of this

The this keyword evaluates to the value of the ThisBinding of the current execution context.

ThisBinding is used by JavaScript’s interpreter to keep track of context. If you declare a function with what is called a BindingIdentifier(ex: function example(){…}), a function environment is created and is given a thisbinding by default. If the internal state called[[ThisValue]] is null or undefined, thisis set to the global object.

We have to understand that all functions return undefined as a value. So, our this keyword will point to the global scope.

“that” is often a nemesis and it has everything to do with context, not scope.

You might be wondering, then why does this work beautifully in objects literals? For example, if we create an object literal called myHouse, we can expect this.myHouse to refer to our house, and it will:

var myHouse = {
  neighborhood: "Cherry Wood",
  address: "5 Premium Park",
  city: "Rolly",
  state: "NC",
  printInfo(){ 
    // 'this' refers to the object we created. 
    //'this' is easy to conceptualize here because... 
    //we have manually created an object that we can see
    return this.neighborhood + "," + this.address + "," + this.city + "," + this.state
 }
}

myHouse.printInfo() // >> "Cherry Wood,5 Premium Park,Rolly,NC"

The problem comes when we want to manipulate the DOM. The DOM is an acronym for Document Object Model, which means we’re dealing with a tree of objects with a starting HTMLDocument node.

We are not instantiating new objects that will then be bound to a this keyword. We are using existing objects, accessing one of its many methods, and writing an anonymous function that inherits the [[ThisValue]] of the object. The moment we declare aBindingIdentifier within our anonymous function, our context is loss and must be regained.

 

What is binding?

Let’s recall our stateless principal and how he had to preserve state in order to keep track of context. By assigning this to a variable we are saving a static copy of [[ThisValue]].

We could have also preserved our this value using

bind()

.

bind()

is an exotic built-in JavaScript function(according to EcmaScript 2017) that has an internal [[Call]] method that takes a [[boundThis]](an object you want to bind to the function) and optional arguments. It then sets the function object’s currently undefined this value to the value of the bound this. So, basically we forcefully tie up our object and throw it at the feet of our function saying, “Hey, use this instead.”

The most common use of bind() involves adding an object as our first and only argument:

$(document).ready(function(){
   //It is important to notice that 'button' is a DOM object with various methods
  $('button').on('click', function(){
     //We must preserve the button's context
     bluezy();
     function bluezy(){
       //We're saying, "I want to do fun things with <> button object, 
      //not <> window object you keep giving me
       $(this).css("background-color", "blue"); 
     }.bind(this)   
  });  
});

We’ve wrapped bluezy() with the bind function to define the context we want our function to work with. Because we’re working with the DOM, we use this instead of referring to an actual object name.

TL;DR

Declared functions are assigned a global context if they aren’t declared within the context of an object. So when we want our closure (inner function) to refer to one of our parent objects, we either have to preserve the value of the object or bind the object to the function.

Resources

http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work

https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/

https://blog.kevinchisholm.com/javascript/context-object-literals/

https://blog.kevinchisholm.com/javascript/difference-between-scope-and-context/

http://web.archive.org/web/20110725013125/http://www.digital-web.com/articles/scope_in_javascript/

https://stackoverflow.com/questions/4886632/what-does-var-that-this-mean-in-javascript


 

Please follow and like us:
0