Dot Syntax

What is the meaning of the dot?
The dot signifies that we want to use something that’s inside something else.

console.log("log is inside of a console");

myObject.search("Tony de Araujo");
// search is a method which is inside of object myObject

Hope it helps!

Advertisements

JavaScript’s Conditional Operator

The conditional operator is a one liner if/else statement. Another name for it is ternary operator because it uses three operands:

expression1 ? expression2 : expression3;

If expression1 evaluates to boolean true, expression2 gets executed. Else, expression3 gets executed instead.

If you’re like me, you probably prefer to use if, else if, else statements, but the ternary operator can be very handy at times. One of the things we can’t do with our regular branching techniques is to include alternative outputs on a one console.log statement, but with the ternary operator we can:

var x = 10;
var y = 9;
console.log(x < y ? "hello!" : "goodbye!");
// it outputs "goodbye!"
console.log(x > y ? "hello!" : "goodbye!");
// it outputs "hello!"

Cool thing!

JavaScript Searching for a Word in a String

Today I’m going to write about an exercise that shows up on the JavaScript track at Codecademy. The exercise in question is there to facilitate the practice of certain concepts and not really to create a way of searching for a word. As a matter of fact the instructor suggests to think of other ways to implement such search and this is the reason why I’ve decided to answer the question by showing one possible way of doing it. I will be using indexOf().

indexOf() is a JavaScript method and I go into more detail about it on my eBOOK.

Let’s start with the code itself:

var text = "Bla bla Tony bla la Tony bla bla Tony bla bla bla Tony";
var searchWord = "Tony";
var init = text.indexOf(searchWord);
var hits = [];

for (var i = init; i < searchWord.length + init; i++) {
    hits.push(text[i]);
}
console.log(hits);

The idea is to search for the word assigned to the variable seachWord. Then use a for loop to push all the word’s characters into an array named hits.

init is a variable that gets assigned to the result of applying the indexOf() method to the variable seachWord.

indexOF() is very useful here because it returns the position of the first character of the word searched in reference to its location in the variable text. In contrast to the method used at Codecademy’s exercise, this character must be part of the whole word passed to the method indexOf(), not just any character that matches. This is because indexOf() matches the complete word and it is therefore more to the point of what we are trying to accomplish.

By using indexOf() we also limit the result to the first match as opposed to matching all similar words in text.

I hope this inspires you to create other possibilities.

You can read more about indexOf() on my eBook JavaScript Objects Functions and Arrays Explained

A function represents a value

When we look at functions from the same window JavaScript does, things become clearer.

Take for example this function:

 var whatsup = function (){
 return "The sky is up!";
};

JavaScript looks at the function call and it only sees the final product, or what is supposed to return.

Call it like this:

"Do you know what? " + whatsup();

And JavaScript will reply with this:

Do you know what? The sky is up!

So the function was just a placeholder for “The sky is up!”.

By placing the string “The sky is up!”  in a function, we saved it and we are now able to call it at will, since the function is just like a Lego puzzle piece: we can plug it anywhere we want, and it always delivers if we interface it properly.

… Will continue tomorrow, mañana, amanhã, 明天, demain, morgen, 明日kesho …|
(Thank goodness for Google Translate!)

Some JavaScript Storage Concepts

So we want to store data to be used in a script, what options do we have?

Storing simple values:

If the value is single, such as a string or a number, we can just assign it to a variable.
Normally a variable is a pointer, it points to some data in memory. However, in JavaScript, simple values such as strings and numbers are saved in the variable name location, in other words, the variable points to itself like if it was telling this simple data to “stay here near me, don’t go anywhere, you’re too small to wonder around on your own!“.

Storing complex values:

For more complex data we can use an array which is an ordered list, or we can use a hash, also known as an “object” or an unordered list. I placed “object” in quotes because in reality almost everything is an object in JavaScript. I’d rather call this kind of “objects” unordered lists or key-value paired lists.

Now since this data is more complex, the variable pointer stays on one side of the memory ( the stack), and the data stays on the other side of memory ( the heap). The variable points to the data, it does not hold the data. We can actually have several variables pointing at the same data.

Storing scripts such as functionality:

Now if we want to store a program routine, such as to print or to calculate or to fetch some data, etc. Then we use functions. Like any other object, functions can be moved around and placed inside of other scripts. Functions are also great to isolate one script from another script. Moreover, functions are great to help cleaning up the trash in memory because once returned, a function clears itself out (this cleaning is browser dependent since every browser uses a different kind of broom).

And there you have it. If you want a more in depth explanation please read my eBook
JavaScript Objects Functions and Arrays Explained

JavaScript method slice

Today I’m bringing a section from my eBook where we cover the JavaScript library String method slice.

The method slice( ) extracts the text from one string and returns a new string with the extracted text. There is no change to the original variable unless of course the method is applied to itself. This is the same as taking a slice of cake but the cake stays intact. We must give this copy of sliced cake to another variable in order to reuse it.

This method uses up to two parameters. The first parameter indicates the zero based first character to be sliced (copied from). The second parameter indicates the first character to be excluded from the action of slicing. (included from, excluded from).

Sample scripts:

1- Declare a variable:

var xpt = "red,blue,white,black";

2- Extracting the word “blue” into another variable:

var xpt = "red,blue,white,black";
var xpt2 = xpt.slice(4,8);

3- Call xpt2;

It returns “blue”. The first character to be included is on position 4 ( as in 0,1,2,3,4), and the first to be excluded is on position 8, which is the comma.

Using negative numbers:

As an alternative, if we apply a negative number to the second parameter, it changes its meaning: now it means to start excluding from the right, based on the number of characters indicated. Commas and spaces count as characters.

4- For example: excluding the last color (black and the comma to its left) from our slicing):

var xpt = "red,blue,white,black";
var xpt3 = xpt.slice(0,-6);

5- Call the variable: xpt3;

It returns “red, blue, white”. In other words, it includes all characters from position zero on, except the last 6 from the end. This also means that we could exclude some characters from the extreme left, if instead of zero we entered some other number as the left parameter.

Using just one parameter:

When using just one positive parameter, this parameter represents the first character position to be included on the slice which extends all the way to the end.

1- For example:

var xpt = "red,blue,white,black";
var x = xpt.slice(3);

// returns “,blue,white,black”, which means that “red” was cutoff.

If the single parameter is negative, it has an opposite effect: it tells JavaScript how many characters to include from the right and exclude all else.

2- Example:

var xpt = "red,blue,white,black";
var x = xpt.slice(-3);

// it returns “ack” from “black”. It counted from the right to the left 3 characters and cutoff all the others at the left.

3- One more example. Extract the “e” from ecmascript:

"ecmascript".slice(1);

// returns “cmascript”.
This is actually useful to remove the first character and replace it with another similar character capitalized, as we will see later in the eBook

The fizzBuzz word game using ternary operators in JavaScript

A ternary conditional statement goes like this:

condition result ? do this if true : do that if false;

condition 1 ? condition 2 ? do this if both true : do that if only condition 1 true : else do something else;

If we want a third alternative for condition 2 true, we add another ternary operator as the last expression:

condition 1 ? condition 2 ? do this if both true : do that if condition 1 true : condition 2 ? do this if true : else do something else;

multiple ternary operator JavaScript

On the following fizzBuzz game I’ve used a multiple ternary conditional operator as an alternative to the regular if, else if, else. Not that I prefer seeing it this way, but as a curiosity and to illustrate  ternary operation processing for multiple conditional outcomes.

var fizz = "Fizz";
var buzz = "Buzz";
var counter = " ";
for (var i = 1; i < 21; i++) {
  counter = !(i % 3) ? !(i % 5) ? fizz + buzz : fizz : !(i % 5) ? buzz : i;
  console.log(counter);
}

We already know how the ternary logic works. The next thing to find out is the meaning of that exclamation point before a boolean expression wrapped in parentheses, like for example !(1 % 3)?

The exclamation symbol before parentheses negates the statement in the sense that in, for example (5 % 3) having 2 as a remainder will result in a boolean “true”, and !(5%3) will result in “false” because it is the opposite of (5%3). Viewing it from a different perspective, when i is 3, an expression such as (3%3) will result in zero and therefore false, but by inverting it like !(3%3), the result will be true, which is the outcome that we want to get fizz.

So JavaScript will replace !( i % 3) for true or false and the result of the ternary expression may be as follows:

count = (i % 3 is true) ? (i % 5 is true ) ? fizz + buzz : fizz : (i % 5 is true) ? buzz : i;

To further understand this expression we need to consider that a ternary expression evaluates from right to left.

On the extreme right side, (i % 5 is true) ? buzz : i gets replaced by either buzz or i, whichever applies,
resulting in count = (i % 3 is true) ? (i % 5 is true ) ? fizz + buzz : fizz : i ( if false, as an example).

Then if (i % 3 is true) ? (i % 5 is true )? are both true, the counter’s end result is fizz + buzz.
else if only (i % 3 is true) ? is true, the counter result is fizz.

Lastly, if both are false the counter result is i which corresponds to a regular number.

test, test, test!!!