CategoryJavaScript Console

How to Write Idiomatic JavaScript

JavaScript is a language that has very few constraints on how you can write it. As a result of this, programmers can have a tough time writing idiomatic JavaScript. If you follow the proper guidelines, then you will not have this problem. In this post, we will talk about these various guidelines and how you should follow them when writing your JavaScript.

Writing Variables Idiomatically

varUsing a lot of global variables can be one of the largest mistakes that a JavaScript programmer can make.  Because of the lack of scope in JavaScript, global variables are extremely susceptible to unwarranted modifications. This is why ES6 introduced the block binding keyword let and the reason why programmers use closures. When writing a program in JavaScript, it is always better to try to find a way to make your variables local.

Generally, you want to declare and initialize your variables at the beginning of a block of code. Doing this is more idiomatic JavaScript and it creates cleaner code. Doing this will also help reduce the number of global variables in your code and reduce the possibility of re-declaring variables redundantly.

JavaScript naturally hoists variable declarations towards the top of a block. If you already have your variable declared and initiated you will not have to deal with the side effects that can occur from this hoisting. Remember, the initialization of a variable is not hoisted; only the declarations are.

Working with Types Idiomatically

When working with primitive types, it is best to not define them as objects. Declaring a primitive type as an object using the new keyword can slow down your code significantly. It is more idiomatic JavaScript to avoid using the new keyword even for objects themselves. Instead, use the literal syntax rather than the constructor syntax when defining a new variable.

ObjectsIn the examples above, you can see that each type has its own literal notation, this includes functions.

When dealing specifically with numbers and strings, try to avoid type conversions. When writing idiomatic JavaScript, it is best to avoid using variables and functions that can accidently lead to producing NaN. As we’ve already seen, NaN can be extremely detrimental to a code base. Also, we’ve already seen that you can add and subtract numbers from strings and get confusing results.

With idiomatic JavaScript, it is almost always better to use the triple equals operator === then the double equals operator ==. The double equals operator will automatically change the type of the compared variables to a similar type before making the comparison. It’s much more safe to use the triple equals operator when making a comparison.

Functions and Control Flow

When you write a function with arguments or call a function that is expecting arguments, always pass the correct number of arguments to the function. If you do not pass an argument to a function that is expecting one, JavaScript will automatically pass undefined to the function. Undefined values can often break the code. It is idiomatic JavaScript to assign default values to arguments for your functions.

When writing a switch statement you can ignore writing a default case but in doing so can easily create errors. It is more idiomatic JavaScript to write a default case even if you don’t think the switch statement will need one. Ignoring a default case in your switch statement can break your entire code base if some unexpected fringe event were to happen.

Increasing Performance

idiomatic JavaScript with ReactAccessing the DOM is extremely slow in JavaScript. Many different libraries and frameworks have been created to either speed up the DOM or create an artificial “shadow DOM”. React.js is a good example of this. React.js uses a “Shadow DOM” to allow the programmer to gain access to the DOM as many times as they want without accessing the real DOM. You are able to create HTML components inside of the JavaScript code which significantly speeds up performance.

The Todo application example that we covered a few posts back is very inefficient code. This is mainly because of how many times it accesses the DOM. If we were to rewrite the code using a library or framework like React.js, we could create the entire Todo front end inside of our code instead binding the input box and buttons to the JavaScript through DOM query methods. Then we would be able to render the buttons and input box all as one single component inside of the HTML. This not only decreases the page load speed but also would increase the rendering speed.

Conclusion

In this post, we talked about idiomatic JavaScript. We discussed various different rules which should be followed for efficiency and to avoid needless errors. We also talked about increasing the overall performance of our code and touched on the advantages of using a shadow DOM. In our next post, we will start to look at a more advanced piece of JavaScript.

Errors and Exceptions in JavaScript

In this post, we are going to look at errors and exceptions in JavaScript. Errors and bugs will happen even to the most careful programmer. They mainly happen due to a direct error that the programmer makes or because the program does something that wasn’t accounted for. luckily, JavaScript features some in-code tools to help us debug these problems.

Try-Catch Statements

The main in-code method that JavaScript has to handle errors is called a try-catch statement. The try-catch statement is a type of control flow statement in which the catch block will only execute if an error is thrown in the try block. In other words, the try block is where the code we want to test resides. The catch block is a block of code which will be executed if the try block throws an exception.

Here we have a pseudo-code version of a try catch block. The try block throws an error, e which is passed into the catch block like a variable. We can pass a variable into catch because when JavaScript code raises an exception it generates a message. We can use the throw statement to manually throw our own exceptions in JavaScript. The throw statement can take a type of String, Number, Boolean or Object.

The main reason why the try-catch statement is so powerful is because it is hard to tell what a user will do when they are accessing your program. One of the more common uses for a try-catch block is for form validation. You can’t control what a user will put into your input text boxes but you can restrict what inputs are valid in these boxes.

Using Debuggers in JavaScript

errorThe other main resource used for dealing with bugs in JavaScript is a debugger. The debugger allows you to set breakpoints in your JavaScript code to see what “state” the code is in at a given moment. Natively in JavaScript, there is a keyword debugger which will stop the execution of the code and send a call to a debugging function. This is basically like setting a breakpoint in the browser, except you manually are typing it into your code. If you try typing debugger into your JavaScript console, it should bring up your browser’s native debugger window.

In most browsers, your debug window is actually your JavaScript console or an extension of the JavaScript console. It is actually quite common for programmers to use the console.log() function for debugging as well. You may notice that upon opening the console in certain URLs you will see error codes. These are mostly from broken JavaScript on the page you are viewing or from an extension you have installed on your browser.

Closing

Though this post was much shorter than normal, we covered error exceptions in JavaScript and exception handling in JavaScript. We looked at the throw statement, the try-catch statement and we looked at the debugger keyword. We also talked about setting breakpoints and looking at state.

In our next post, we will start to look at a simple real world example of JavaScript.

 

Regular Expressions in JavaScript

In our last post, we went over some of the smaller features that we skipped over in this tutorial. In this post, we will be looking at Regular Expressions in JavaScript or regex for short. Regular expressions are an important part of any language and JavaScript is no exception.

Writing RegEx

Regular expressions are patterns of characters that are used to match character combinations in strings. Regular expressions are objects in JavaScript and you will often see them in form verification applications. There are two ways to create a new regular expression in JavaScript; you can use a literal format or a constructor.

A regular expression literal is surrounded by backslashes /, which are the escape characters in JavaScript. Here is an example of a regex literal.

The regular expression constructor format follows the pattern of all other constructors in JavaScript. You use the new keyword followed by RegExp. Typically, you will use a constructor when you know that the pattern will be changing or when you might be getting the regex pattern from another source. Here is an example of a regex constructor.

RegEx Characters

long-regexRegular expressions composed of simple characters are used for direct matching. Keep in mind that regex are case sensitive by default. For example, a regex of /dog/ will only match strings with the characters “dog” in them. The characters must also be in the original order, “dog”.  The string “let us walk the dog” will match with this regex, but a string like “dinosaurs of Georgia” will not match even though it contains the “dog” characters.

When you need to go further than a direct match you can use special characters as well. For example, the regex /ea*t/ will match with any character combination where a single “e” is followed by zero or more “a”s which is immediately followed by a “t”.  To find out what all of the special characters do look at the Debugex cheatsheet here.

RegEx Methods

Like any other object in JavaScript, Regular expressions have their own methods. Here are some of them in action.

The exec method applies the regex to the given string then returns an array of the match information. The test method looks for a match then returns true or false. The match method returns an array with the first matched string and all matches if you pass the global flag. The search method returns the first index value of the match and -1 if there is no match. The replace method matches the regex then replaces the match with the second argument. The split method matches the regex then splits the string into an array at the matches.

RegEx Flags

Regular expressions also have what are called flags. There are three flags which are used in JavaScript regular expressions; g, i and m. When you create a regular expression literal, the format follows, /pattern/flags; The constructor has a pattern like this, new RegExp('pattern", "flags"); You many pass multiple flags at once. The global flag g makes the regular expression match the entire string and creates an array of the match occurrences. The ignore case flag i makes the regular expression case insensitive. The multi-line input m flag makes the beginning of input character ^ and the end of input character $ apply to both the beginning and end of input. The last flag is not used as much and is only supported by JavaScript version 1.5 and above.

Closing

In this post, we looked at regular expressions in JavaScript. We talked about the methods that come with regular expressions and the various characters and flags that can be used in them. Our next post will look at exception handling and we will start to move into real world examples.

Filling in the Holes

In this post, we are going to go over some of the topics that we glossed over in our main tutorial. There are a few important topics that we didn’t fully cover when going through the core language. Before we start to look at real examples of programs, we need to fill in the gaps of our knowledge.

The Ternary Operator

The first topic that we need to look it is called the ternary operator. The ternary operator is a type of conditional. It follows this pattern: condition ? true : false. The basic idea is that the ternary operator is shorthand for an if statement. Here are some examples.

ternary-operatorThe ternary operator is a quick way to determine if a condition is true or false and a shortcut for allowing you to simply execute code based on the condition. You can assign a ternary expression to a variable like you would with a function. This assigns the “return” value of the ternary operator to the variable. The return value being the last line of each expression. In our example, the value of t will be true or false depending on the value of x.

And, Or, and Not

The next set of concepts that we need to look at are the logical operators && and, || or, and ! not. These logical operators allow us to make complex conditionals. Take a look at the logic table below.

booleanoperatorsThese can be used for complex conditional statements but make sure to use the correct conditional symbols for your statements. If you have code that should run if only both statements are true then you use an “and” conditional. If you are using multiple if statements, you might find that you can combine them with one of these operators.

The Continue Keyword

continueThe last concept that we will look at today is the continue keyword. We talked briefly about the break keyword when we looked at switch statements. The continue keyword tells the program to continue a loop rather than break completely out of it. However, the continue keyword is still a “break point” keyword. This means that when the loop hits a continue keyword, the code will go back up to the top of the loop and start with the next loop iteration. Look at the example below.

In this example, because of the continue keyword and the if statement, the code will not print out any even integers in the loop. The break keyword ends the loop at 15 rather than at 20, and so the console doesn’t print out 15.

Closing

Before we dive deep into real word programming examples, we still need to cover two larger concepts. The first concept is exception handling and the final concept will be regular expressions.

In this post, we looked at the ternary operator, the and/or/not logical operators and the continue keyword. In our next posts, we will look at exception handling and regular expressions.

Prototypes and Object Getter and Setter Functions

Our last post looked at object constructors in JavaScript. In this post, we plan to refine our knowledge of object constructors by adding Getter and Setter functions. We will also be looking at JavaScript object prototypes which are a feature that is a consequence of the DOM.

Using Prototypes in JavaScript

Object Prototype flowIt is probably best to take a look at object prototypes first. When you use a constructor to create an object, that object inherits it’s prototype’s properties and methods. An array object in JavaScript will inherit the various properties and methods which are specific to arrays in JavaScript. Objects defined with the new Object() constructor function inherit from a prototype called Object.prototype.

You can think of the Object.prototype in this way; when you create an object constructor with a function you define a set of properties and methods for that specific object. If you want to change one of those properties or methods you can’t directly do so without completely rewriting the constructor function. The Object.prototype allows us to change the shape of the object constructor without us having to rewrite the function. Let us take a look at our person object example from before.

As you can see, we can use the Object.prototype keyword to add both methods and properties to all instances of an object rather than just one. If we try to add a method or property without using the prototype keyword we will consequently not be able to change all of the instances of that object. Now that we are able to change and add methods and properties to objects, let’s look at how you protect and relate them to one another.

Getter and Setter Functions in JavaScript

Object AbstractionFormal Getter and Setter function syntax was finally introduced to JavaScript in ES5. In ES6, this was further iterated upon with the introduction of classes. Classes are a topic we will go over some time later. For now, let’s look at Getter and Setter functions in object literals and the Object.defineProperty syntax.

Remember the metaphor we were using before; variables are like labels and objects are containers. Getter and Setter functions allow the program to reach into the containers to either get or set a value without breaking everything else. Getter and Setter functions also allow us to relate one piece of data with another in a way that is safe. Let’s first look at a simple object literal that features Getters and Setters.

In this example, we used a property called fullName to allow us to set the other two properties of the object, firstName and lastName. This consequently lets us define a relationship between all of the variables but also it lets just change the object much quicker. Note, we used the split() function to convert the fullName string to an array of length two. We could iterate on this setter function further and use a set of conditionals to force it to only take two strings but we will leave that for later.

These two keywords, the get and set keywords allow us to define two accessor functions. When we try to access the variable fullName, the fullName() getter function runs and we get it’s return value. When we want to access and set the fullName variable, the fullname(name) setter function is run with the value we assign passed through it.

The Object.defineProperty Syntax

There is another way to define getters and setter methods in JavaScript that is more formal. This method makes use of the Object.defineProperty method. Let’s look at an example of this.

This example is a little bit advanced but if you look closely, you can see that what is happening here isn’t much different from what we did in our first example. This method of defining Getters and Setters also allows us to declare if the object is configurable or enumerable. We discussed what this was in our original post on objects, but configurable values are mutable values while enumerable values can be looped through. Also, we can define properties without using Getters or Setters with this syntax.

Keep in mind that the attributes added through this method are not writable by default so explicitly stating writable: false was a bit redundant in this example. As you can see, the age attribute is immutable. The color attribute is fully mutable in this example because we explicitly stated for it to be this way. As we start to look at Classes and more advanced object literals, these two definition methods will be explored further. For now, just notice the format that we use to define these Getter and Setter functions and the Object.defineProperty function.

Closing

In this post, we introduced the concept of the Object prototype and we took a look at object Getter and Setter functions. As we continue our journey to learn JavaScript, we will see the pros and cons of encapsulation. Next week, we will start off with anonymous functions and then move towards classes.

Object Constructors in JavaScript

Today, we are going to take a more direct look at objects. Our first encounter with objects introduced us to their properties and methods. We looked at two specific ways of creating objects, the use of object literal notation and the new Object() function. In this post, we are going to look at object constructors.

Factories for Objects

Object ConstructorsWhen you define an object using the object literal notation you are defining a specific object instance. To leverage the power of objects as a data type, we need a way to streamline the creation of specific types of objects. Our original object example was that of a Person object. This was a good example for that lesson, however, it only works well for describing one specific person. What if we want to create a data type that can be applied to many different people? This is where object constructors become relevant.

Object constructors work like factories. They allow the programmer to create a function which will output multiple objects with the same general data shape.

In this example, we created a Person object constructor which takes three parameters. We assign these parameters to variables inside of the function which then allows us to create multiple instances of this object with different arguments being passed. If you call one of the three instance variables, you see a return of a Person object with the specified values. But then, what is that weird this keyword?

What The Hell Is this?!?

this keywordBefore we go any further, we need to talk about the this keyword. As you can see in the constructor above, we are using the this keyword three times in the variable assignments. What the this keyword allows us to do is to refer to the Person object directly even though it hasn’t been created. We are essentially saying that the Person function and object owns the firstName variable, the lastName variable, and the age variable. It allows us to differentiate the variables owned by the object from the parameters being passed into the function. this is basically a reference to the object itself. Here is a more general object constructor function.

The Car object constructor in this example uses different variable names for the parameters and the function attributes. Also, when you make a new instance of the Car object, you automatically get the object returned to the console. The this keyword might seem a little abstract at first but as you use it more you will get used to it.

Naturally, we can also create constructors that have methods inside of them. Look at this augmented Person object constructor.

In this example, we can call the greeting() function on any of the instance objects that we create with the new Person constructor using dot syntax. Calling the greeting() function will fire the anonymous function which was declared in the constructor.

Natural Constructor Functions in JavaScript

JavaScript also has it’s own native object constructors. Below is a chart with some of the different built-in JavaScript object constructors. Some are very straightforward and others we have already talked about. There are also a few that we have yet to talk about.

Object Constructors - Mind FuckWe’ve alluded to this many times before but most items inside of JavaScript are Objects and almost everything inside of JavaScript is treated as an Object in some way. The larger exceptions to this rule are the primitive types like numbers and strings. As a result, JavaScript still treats primitive types in a similar fashion to objects even if they aren’t objects themselves.

new Array();Creates an Array Object
new String();Creates a String Object
new Number();Creates a Number Object
new Boolean();Creates a Boolean Object
new Object();Creates an Object Object
new Date();Creates a Date Object
new Function();Creates a Function Object
new RegExp();Creates a new Regular expression Object

Closing

In this post, we introduced the concept of Object constructors in JavaScript. We showed a few examples of Object constructor functions and talked about the this keyword. Our next post will delve deeper into the world of objects as we look at prototypes and getter and setter functions.

Manipulating Strings with String Methods

Thus far in our adventure through JavaScript, we have talked about the different types of data that you can use. We have also looked at functions and objects as well as control flow. In this post, we are going to look a little deeper at strings in JavaScript. Specifically, we are going to take a look at the different functions or methods that we can use on strings.

Something that we’ve neglected to mention up until now, but have more or less implied, is that JavaScript treats it’s primitive data types like Objects. This is why numbers and strings have methods and properties like any other object in JavaScript.

Treating Strings as Objects

4645356096_927c5c0e8c_zIn this example, we declared a string variable, “string object” and we ran three string methods on it. The length method returns the length of a string similar to the length method for an array. The search method allows us to query for characters or strings within the original string. If you try searching for something not inside the string you will get a return value of -1 instead. The ToUpperCase method returns a copy of the string with all of the characters as uppercase letters. In many cases, you will use these methods to either manipulate a string for consistency in a program or to verify what is inside of a string that is being passed through input.

Here we introduce two more methods, the replace method and the toLowerCase method. The toLowerCase method is like the toUpperCase method but it converts all of the characters to lowercase rather than uppercase. The replace method allows us to replace parts of the string with other strings. It takes two parameters, the initial part we want to replace and the item we are replacing it with. Note, you can also use an empty string as a replacement. We can also do something like this:

Intro to RegEx and Slicing

As you can see in the example above, we used the escape character backslash and the character g (global) to indicate that we wanted to replace all of the spaces. This type of syntax is what is called a regular expression or regex. With this simple regex, we can find patterns in our strings and globally replace them. We can also use regex inside of the search method to just find the patterns. (we will talk about regex more later.)

picture2-substring-java-string-diagramWe can also chop strings to pieces using the substr(), substring() and slice() methods. The slice method removes anything outside of the indexes that we specify. Substring() is a much older method that does the same thing as slice() but can not accept negative indexes. Substr() allows us to separate a string in a slightly different way from the slice method, with the second parameter being the length of the extracted string. Below are examples of each.

There is one more feature of strings that we should cover before closing out this post and that is how we can access them as arrays as well as convert them to arrays. Be careful when you try to access a string as an array before converting it because it can throw all kinds of awful errors.  It’s unsafe and unpredictable and doesn’t work in all browsers so for the most part, it is something you should avoid. You can, however, use the split() method to convert a string to an array and then access that array like any other array. The split string method will split the string into an array of strings at the character type you indicate. If you don’t pass anything onto split it’ll just convert the entire string to an array of index one. The string will just be on the first index which is not that useful.

Closing

In this post, we talked about the different string methods that you have access to in JavaScript.  We talked about how JavaScript naturally treats primitive types as objects and how we can manipulate strings with the built-in string methods.  We also looked at converting strings to arrays and splicing strings into parts.

In our next post, we will look at the common number methods that are used in JavaScript. We will also start to build small programs. For this, we will need a more standard environment to develop our JavaScript in. We will go over how to install node.js and the text editor of your choice.

Manipulating the Document Object Model

Today, we are going to introduce the concept of the Document Object Model or DOM. The DOM is a very important concept when you are working with JavaScript. JavaScript is a language that uses HTML and CSS to create its graphical user interfaces. Other languages use similar markdown languages such as XML to streamline the process of creating GUIs. (Note: we won’t really be looking at much code in this post.)

In this tutorial, we will assume that you have at least a basic understanding of HTML and CSS. HTML is a markdown language that basically lets you define where things will be on your GUI and CSS is a styling language that lets you configure how things will look on your GUI. JavaScript becomes very powerful with these two technologies because it can give the elements created by HTML and CSS specific behaviors.

The Document Object Model

The DOM is an application programming interface (API) of the hierarchy of objects inside of a typical HTML document. More specifically, the DOM refers to the structure of the document itself and how you can access and manipulate elements on the document. More or less, the DOM helps programmers by defining a standardized structure for an HTML or XML document.

5733353962_ecd5b221cf_zAll of this sounds really complicated but it truly isn’t. All the DOM really does is allow JavaScript (and other languages) to easily access HTML to read, write, delete and add elements dynamically. When you write an HTML document that you plan to access with JavaScript, you can think of your HTML as a tree structure of JavaScript objects. Each element on the HTML document has various properties that can be accessed and manipulated through the use of JavaScript functions.

The Window Object

For instance, the largest object in the Document Object Model is the window object. If you open your JavaScript console and type window you will see a return value of all of the child objects that exist on the current web page that you are on. The window object is an abstraction of an open window in your browser. Inside of the window object, there are three objects: the history object, the location object and the document object. The document object is the most important object for our purposes.

The history object is a representation of the browser history. If you open a new tab or window with your browser, then open your console and type history.length you will see a return value of 1. This is because you have only been to the first URL since the history object was created. The location object contains information about the current URL that you are viewing. Typing location.href will return the entire URL name of the URL you are currently on.
nodesBefore we talk about the document object in detail, we need to understand what nodes are and why the Document Object Model uses nodes to represent everything (including the document itself). If the DOM is a tree structure, then the nodes are represented by the intersections of the lines of the tree. There is a document node, text nodes, attribute nodes, element nodes and even comment nodes. All of these nodes represent different data structures on the HTML document. A good metaphor for the DOM is to think of the HTML document like a net with the intersection points being nodes. JavaScript can only grab these intersection points when it is manipulating the document.

The Document Object

The document object is the owner of the HTML document that you see in your browser. There are various JavaScript functions that use the document object to manipulate the nodes it owns. For instance, document.getElementById(), searches for an HTML element by it’s id and then returns it. This is a frequently used function which allows you to bind HTML nodes to variable names in a JavaScript program. You can also create different node types with different functions such as document.createElement(). You can create an element type then assign it to a node or near a node with document.appendChild().

We have actually been using various different DOM functions such as console.log() which calls the console object and then prints what’s inside the parenthesis to the console object. As we explore deeper and deeper into JavaScript we will start to see more and more of the Document Object Model and its various functions.

Conclusion

Today, we took a break from looking at pure JavaScript code to talk about the Document Object Model and how we can use it to access data on HTML documents. We looked at a very general overview of how the DOM works and how the nodes on an HTML document are organized.  As we continue forward with our look at JavaScript we will start to look at bigger examples which will start to use and rely on the DOM. In our next post, we will continue by taking a better look at objects and functions.

Variable Scope in JavaScript

In our last two posts, we started looking at functions and objects in JavaScript. Both functions and objects make use of variables and because of this, we must discuss the concept of scope in JavaScript before going further. In fact, objects and functions themselves are also subject to scope in JavaScript because they are also treated as variables.  Scope is a concept that you will see in many different programming languages and it is much more powerful than it seems at first.

So, what exactly is scope and how does scope in JavaScript work specifically? Scope refers to the set of variables, objects, and functions that you have access to at a given area of a program. In JavaScript, where you define a variable is extremely important because it determines the “visibility” of that variable in different parts of the code. In many other languages, you have access to different keywords that let you change the scope of a variable but this is not the case in JavaScript.

Scope in ECMAScript

You have two main forms of scope in JavaScript (pre-ES6); global scope and local scope. The upcoming iteration of JavaScript, ECMAScript 6 (ES6), also features the ability to bind a variable to a block; this is called block scope. To better demonstrate what scope is, take a look at the code below in our JavaScript console.

As you can see, we have defined the variable x on three separate occasions in this code. Our first declaration is what is called a global declaration. This means that all of the code has access to this variable. The variables x that are defined inside of each of the functions are local variables. These variables can only be accessed by the functions themselves. Notice that the function, example_1 also uses a local scope. The x referred to inside of example_1 is the argument passed into example_1.

scope_chainingIn a way, scope refers to the lifetime of variables; that is, how long variables stay in memory. In the case of globally scoped variables, the variables will stay in the ram until you close the program (or browser window).  With locally scoped variables, the variable only lasts until the function it’s scoped to is executing. Let us take a look at this next example to see some of the quirkiness of the scope in JavaScript.

It is worth noting that using a return statement can change the scope of a variable in an artificial way. If you return a variable from a function then it is still visible in the parent code body.  In this way, you are extending the lifetime of a locally scoped variable by passing it into it’s parent.

Strange Scoping

What do you think will happen when we run the strange function? common sense tells us that the function will print 1 then 30 to the console, but this is not actually what happens. We see undefined, then only one print declaration of 30 and then another undefined. The reason for this is that JavaScript always moves the variable declaration to the top of the scope. The function strange should actually look something like this.

strange_2 also gives us the same output as strange did. If you define a variable but do not give it a value and then pass it to the console.log() function, you will see undefined print to the console then get a return value of undefined as well. This is essentially what is happening with strange and strange_2. The variable declaration of x inside of the function becomes locally scoped to the function and it is passed undefined into the first console.log(x) statement. x then receives the value of 30 and it is printed to the console.

The Let Keyword

es6-letBefore we wrap this up, let us take a small peak at block scope from ES6. ES6 introduces many different keywords to JavaScript, one of which is the let keyword. The let keyword works like a var declaration but it is specifically made for block scoping.  Here is an example of block scoping using a modified version of the example_3 function from before.

The non_block function suffers from a similar problem to our strange function in that the var x inside of it is pushed to the top of the scope. This causes the first console.log(x) statement to print undefined and then print "block" twice. In our block_scope function, the let keyword does not become a locally scoped variable because it’s bound to the if statement instead of the function. This is why we get "global" "block" "global" as our print outs.

Like global and local variables, a block scoped variable only “lives” in the code until the code-block it is scoped to finishes running. In this case, the if statement finishes running and the let x binding dies before the last console.log(x) statement is run.

Conclusion

In this post, we looked at scope in JavaScript. We saw examples of local scope, global scope and block scope. We introduced ES6’s let keyword and looked at some of the strange examples that came from pre-ES6 scoping rules. In our next post, we will continue our journey and expand upon what we already know of objects and functions.

Objects in JavaScript

We’ve mentioned objects a few times in past posts though we really haven’t explained what they are. We know that functions are related to objects and that arrays are also related to objects.  We also know that objects are one of the core data types in JavaScript. So what exactly are objects in JavaScript? An object in JavaScript is a complex data type, similar to an array, wherein values are paired with names. Each of the items in this list of values is called a property. Like an object in real life, objects in JavaScript have properties and can have behavior.

One of the most common examples of an object in JavaScript is that of a person object as seen below.

This object has three properties, a first name, a last name, and an age. Each of these properties can be called in a similar fashion to that of a piece of data in an array, except instead of using an index, we can call them through the key names, firstName, lastName, and age. Another difference from calling arrays is that we must use quotes around our key names to call them in this fashion.  Notice that instead of using square brackets like with arrays, we use curly brackets for defining objects in JavaScript like we did with functions.

When you define the person object in the JavaScript console, you can access the data inside using the “dot” syntax or the “square brackets” syntax (the “dot” syntax is more heavily used and idiomatic in JavaScript).  You can also change the values inside of an object though it is through a different syntax than with arrays or variables. Also, unlike the primitive data types in JavaScript, we can not copy an object like we can with a variable, instead we can only refer to the object.

In the example above, when we create a reference to person with the variable anotherPerson. We are not copying the person object to another container. This is why when we change the age property in the person object it also changes in the anotherPerson object.

The Attributes of Object Properties

kettle-objectThe object properties each have three specific built-in attributes that are not really demonstrated in these examples.  All object properties have a configuration attribute which specifies whether or not the property can be deleted or destroyed. Object properties also have a writable attribute which specifies if they are changeable or mutable.  Finally, all object properties have an enumerable attribute which specifies if they can be returned in a for-in or (for/in) loop structure. We will discuss these attributes further when we start to talk about getter and setter functions but for now, let us look at some of the ways that we can create objects in JavaScript.

The object we created above was created using object literal notation.  Another way to create objects is through a constructor, in a similar way that we can create arrays. Object constructors use the new keyword, like arrays, and they use the object keyword.  Below is a new person object that also has a function embedded in it. Properties that contain functions are also called methods (more on this later).

The two objects above are exactly the same but were created through different means.  As we will see when we talk about more complex objects, these two different ways of creating objects both have their advantages and disadvantages.

Note that if you wish to call the function or method built into the object you must use parenthesis. If you type out person.hello, the console will return the function format and not actually run the function, which is the case for all functions.  This function is what’s called an anonymous function. The function itself does not have a name and it is just referenced by the person.hello property. We will talk about these types of functions later.

Conclusion

In this post, we introduced the concept of objects in JavaScript. We talked about the basic attributes of objects and some of the basic methods which are used to create them. In our next post, we will start to discuss “scope” and continue our discussion of both Objects and Functions.