Strings, Objects, and REPL, Oh My!

So I thought I’d get going again doing algorithms. I’d start simple and go from there.

But alas REPL had other plans for me.

I did a couple of algorithms then got to Reverse Integer. This problem to be exact:

“Given an integer, return an integer that is the reverse ordering of numbers.”

function reverseInt(n) {

}

I like to use repl.it so I got it going on that platform entering:

let int = 12345;
let intStr = int.toString();
console.log(int);
console.log(intStr);

When it was run the result was:
12345
12345

intStr was not a string. Interesting, after checking for typos I enter:

console.log(int.toString());
Still a number. 12345.

I try:

console.log((12345).toString());

Run in repl:
12345

…Ok instead of the toString method I go to the String object:

let int = 12345;
let intStr = String(12345);
console.log(int);
console.log(intStr);

Still:

12345
12345

Next tried:

let intStr = String(int);

Then:
String(12345);

Then:
console.log(String(int))

12345
12345
12345

Now the investigation begins! There must be some reason both the toString method and the String object are not turning this number to a string! There must be something I’m missing about REPL…

I copy/paste my exact code into codepen.io:

let int = 12345;
let intStr = int.toString();
console.log(int);
console.log(intStr);

Result:

12345
“12345”

Finally!

Which means there IS something I’m missing about REPL. Numbers and/or strings or their conversion (at least in JavaScript) may behave differently in a REPL environment. The investigation continues…

I review Number.prototype.toString()
Then review the String object.

I discover that there are String primitives and String objects. And that JavaScript automatically gives primitive strings a wrapper to convert them to String objects, so String object methods can be used on primitive strings. String literals and strings returned from String calls, called without using the new keyword, are primitive strings.

In JavaScript, a primitive is data that is NOT an object and HAS NO METHODS. And all primitives are immutable, meaning they cannot be altered.

From MDN on primitives in JavaScript:

“It is important not to confuse a primitive itself with a variable assigned a primitive value. The variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.

``````// Assignment gives the primitive a new (not a mutated) value
bar = bar.toUpperCase();       // BAZ``````

A primitive can be replaced, but it can’t be directly altered.”

Interestingly String primitives and String objects give different results when using eval().

“Primitives passed to `eval` are treated as source code; `String` objects are treated as all other objects are, by returning the object…For these reasons, the code may break when it encounters `String` objects when it expects a primitive string instead…

`String` object can always be converted to its primitive counterpart with the `valueOf()` method.”

According to the eval() docs, “The `eval()` function evaluates JavaScript code represented as a string.” The return value is “the completion value of evaluating the given code.

`eval()` is a function property of the global object.

The argument of the `eval()` function is a string. If the string represents an expression, `eval()` evaluates the expression. If the argument represents one or more JavaScript statements, `eval()` evaluates the statements…

If the argument of `eval()` is not a string, `eval()` returns the argument unchanged.”

Which brings us back to REPL.

If we recall, or aren’t aware, REPL stands for Read-Eval-Print-Loop.

Wiki:

“In a REPL, the user enters one or more expressions… and the REPL evaluates them and displays the results.

The read function accepts an expression from the user, and parses it into a data structure in memory.

The eval function takes this internal data structure and evaluates it.

The print function takes the result yielded by eval, and prints it out to the user.

The development environment then returns to the read state, creating a loop.”

The value of int, which is 12345, was output in red in repl.it. And the string was output in white, without quotations. So to get deeper insight, to check if numbers are printed in red, maybe strings are white, or maybe something else under the hood, I used the typeof operator:

let int = 12345;
let intStr = int.toString();

console.log(int);
console.log(intStr);

console.log(typeof int);
console.log(typeof intStr)

Output:
12345 (red)
12345 (white)
number
string

Ok so repl knows that intStr is a STRING. But there’s no quotes. Is this a JavaScript quirk of primitive strings vs. String objects? I ask.
Is it (eval)uating, eval() in r-E-p-l, the string to not really be a string? But a number? Or it encountered a String object when it expected it to be a primitive string?

Then I looked into how repl.it prints strings.
Then how console.log prints strings in general.  Maybe there’s something I’ve forgotten or maybe something new.
Also the differences between codepen and repl.it.

“The console.log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.

Parameters: It accepts a parameter which can be an array, an object or any message.
Return value: It returns the value of the parameter given.”

Notice it did not include a “string” as an accepted parameter. It said a message. And it says it returns the value of the parameter given. Which means the quotes can be removed in order to just display the “message.” Which would be the contents of a string, not including the quotes.

I experiment with the Chrome console:

let num = “12345”;
undefined
num
“12345”
let Str = “12345”;
console.log(Str);
12345
undefined
let Str = “12345”;
undefined
console.log(Str);
12345
undefined
Str.valueOf();
“12345”
typeof Str
“string”
Str
“12345”
console.log(Str);
12345
undefined

The a couple of more IDEs that basically did the same thing.

But still there are other IDEs like codepen that print the way I remember, and the way I remember the Chrome console printing console.log’s previously:

let int = 12345;
let intStr = int.toString();

console.log(int);
console.log(intStr);

Console:
12345
“12345”

It appears console.log is not consistent across browsers and IDEs.

So like I’ve mentioned in my newer videos, it’s been quite some time since I’ve programmed last. So I’m accustomed to how things were outputting in some IDEs and Chrome several years ago. And after searching high and low, and going around the world and back, little did I know that some IDEs are now removing the quotations from a string output from console.log. I don’t recall repl.it doing this, so this may be new. And the Chrome console now does this.

That’s it.

-_-

I’m still going to publish this because most likely someone else somewhere is experiencing the same confusion. Especially someone like me who hasn’t used these tools in a while. Maybe this can be the quicker answer for someone else that I couldn’t find.

😏

Much Love & Peace,

Danielle

Visibility: Hidden vs. Display: None

Someone asked me the difference between visibility: hidden and display: none, so I thought I’d put the explanation I gave them, here as well.

The main difference between visibility: hidden and display: none is the effect they have (or don’t have) on the document layout.

The visibility CSS property itself, can show or hide an element without changing the document layout. Meaning the page will look exactly the same, except the element you applied visibility: hidden to will be invisible. The element still holds it’s place so all of the elements around it will stay exactly where they are. They will not shift into its space. Even though you can’t see the element, it’s still there.

And for those interested, the visibility property can also hide columns or rows in a table with the collapse value.

Now the display property set to “none” on the other hand doesn’t just hide an element, it actually removes the element from the layout of the document all together. So when using display: none the appearance of the page may change because the elements around the element set to display: none will now shift appropriately to fill its space. This is because the element display: none was applied to is no longer there at all. So that space in the layout must now be filled.

Hope this is helpful to someone, and for those who have any comments or suggestions, let me know below.

Love & Peace,

Danielle

The Box Model: CSS

So the box model is where it all starts when it comes to making great designs with CSS. Many people don’t know this but every element on a web page is actually a rectangular box. Even if it LOOKS like a circle, LOOKS like a triangle, or if it even looks like a dog, behind the scenes all of the elements that comprise the web page document layout are actually boxes.

Boxes, Boxes, and More Boxes

To give an example, below is a screenshot of me inspecting the logo on Google’s homepage. Although the logo may look like it’s six letters of different shapes and sizes originally, when you inspect the element it shows that these things are all apart of one rectangular img element:

The green spacing above the logo is a top padding. The width of it is measured in pixels, and the padding above the logo is 109 pixels. The image below is a better illustration of padding as well as the other components of the box model:

Components of the Box Model

The middle blue section represents the content of the element. It has a width and height, which in the image above is 512px (pixels) and 128 px, respectively.

The green section surrounding the content represents the padding. This section is in-between the border, and the content. It creates space around the content within the border of the element.

The orange-ish section surrounding the padding is the border. The border property not only has width, but also has style and color.

And outside the border of the element is the margin. The margin is always transparent and creates space between elements.

The padding, border and margin work in a similar way. Above, with the padding for example, sense all sides have the same width of 16px, the CSS property/value would appear as “padding: 16px;”. If you wanted the padding to be on a specific side however, you could use the padding-top, padding-right, padding-bottom, or padding-left properties. These properties are represented in the illustration below:

Box Model Shorthand

If you wanted each side to have a different value, you could use the padding property with multiple values such as, “padding: 10px 50px;” which will give you 10px of padding on the top and bottom, as well as 50px of padding on the right and left. You could also use the shorthand, “padding: 25px 50px 75px 100px;”. This shorthand is the same as going around the box in a clock-wise fashion. Following the image above, 25px would be the top padding, 50px would be the right padding, 75px the bottom padding, and 100px the left padding. Margin works the same way. With border you must specify a width, style and color for the border to appear. As an example it can be written like so, “border: 2px solid black;”.

Plus You Can Change It

If you needed to limit the width of certain elements it is possible to change the box model with the “box-sizing: border-box;” property/value. Here instead of the content being a certain width and height, now the content, padding and border are limited to that width and height.

Conclusion

Even though every web page may look somewhat different, the layout of every web document is made up of boxes. These boxes are made up of the content in the middle, which is surrounded by the padding, which is then surrounded by the border, and they are surrounded by the margin. When you combine your content with the box model, you can customize them in virtually endless ways to get the look you want for your website. And if you need more consistency, you can even change the box model all together to make your page do what you need.
Happy styling! 🙂

Love & Peace,

Danielle

Inline vs. Block vs. Inline-Block: CSS

So I haven’t really been covering CSS too much on this blog and I really want to get in-depth and have a mastery of it. But first I want to progress from some of the more basic concepts of Front-End Web Development, on to the more advanced. These building blocks are the foundation and it’s time I dug into it in more depth as opposed to a wide breadth (seems like I have binary trees on the brain right now).

This should be fun getting back to basics for a while with HTML & CSS. Gradually on this blog I’ll get back into covering more JavaScript and React.js.

CSS Display Property

Display is a property of CSS that controls how an element displays on the page.

Syntax

display: value;

Three values of the display property are inline, block, and inline-block.

There are plenty more but these are the three most common.

Inline

Span is a great example of an inline element. Great demonstrations and descriptions are provided by MDN:

``````<p>The following span is an <span class="highlight">inline element</span>;
its background has been colored to display both the beginning and end of
the inline element's influence.</p>``````

Below is the rendering of the example above. The span tag is wrapped around the highlighted section:

The following span is an inline element; its background has been colored to display both the beginning and end of the inline element’s influence.

An `inline` box flows with the document’s text (i.e. it will appear on the same line as surrounding text and other inline elements, and its content will break with the flow of the text, like lines of text in a paragraph.) Width and height settings have no effect on `inline` boxes; any padding, margin and border set on `inline` boxes will update the position of surrounding text, but will not affect the position of surrounding `block` boxes.

Block

Now div is an example of a block-level element. Below span has been replaced with div.

``````<p>The following div is an <div class="highlight">block-level element;</div>
its background has been colored to display both the beginning and end of
the block-level element's influence.</p>``````

And the rendering:

The following div is an

block-level element;

its background has been colored to display both the beginning and end of
the block-level element’s influence.

`block` box is the opposite of an inline box: it is defined as a box that’s stacked upon other boxes (i.e. content before and after the box appears on a separate line), and can have width and height set on it. The box model (ex: content, padding, border, margin, width, height) applies to block boxes.

Inline-Block

An `inline-block` box is something in between the first two: It flows with surrounding text without creating line breaks before and after it like an `inline` box, but it can be sized using width and height and maintains its block integrity like a `block` box — it won’t be broken across paragraph lines (an inline-block box that overflows a line of text will drop down onto a 2nd line, as there is not enough space for it on the first line, and it won’t break across two lines.)

This image can be found here.

Let’s Put It Together

The following descriptions of the inline, block, and inline-block values are found here:

The inline value displays an element as an inline element (like <span>). Any height and width properties will have no effect.

The block value displays an element as a block element (like <p>). It starts on a new line, and takes up the whole width.

The inline-block displays an element as an inline-level block container. The element itself is formatted as an inline element, but you can apply height and width values.

And if everything above wasn’t your cup of tea, here’s a breakdown from Stack Overflow:

Inline elements:

1. respect left & right margins and padding, but not top & bottom
2. cannot have a width and height set
3. allow other elements to sit to their left and right.
4. see very important side notes on this here.

Block elements:

1. respect all of those
2. force a line break after the block element
3. acquires full-width if width not defined

Inline-block elements:

1. allow other elements to sit to their left and right
2. respect top & bottom margins and padding
3. respect height and width

Conclusion

So there we have it: Block vs. Inline vs. Inline-Block. And all the ways they differ in their glory.

With much love see you next time,

Danielle

Models of the World

I’m reading the book JavaScript and JQuery by Jon Duckett, and it has given me a new perspective on programs and how they interact with data. In this vlog I expound on that.

Video transcript:

Hey! So I wanted to make a video about this book I’m looking at called JavaScript and JQuery. It’s kind of made a shift in the way I look at programming and how programs interact with computers. I had made some things, I’ve made some objects, functions, put some data in there, and the programs done some things but, the way that it explains it in this book, I think it would be beneficial to everybody. So first of all this is the book I’m looking at, JavaScript and JQuery. So firstly it says computers create models of the world using data. And I like this because it makes you think of programs as a representation of the world as opposed to, you know, a bunch of lines of code lol… And here it shows you a hotel and some cars and it goes on to say, you can think of objects as the hotel, the people, the cars. And when you look at events, this is when we interact with those objects and cause something to happen. Like it says here an event at the hotel would be a reservation being made, or a reservation being cancelled. With the car, if the driver brakes it slows down, accelerate, it speeds up. And it goes on to say with methods, these in a way are the things that we DO with the objects in the world. Like it had a method here for, there’s a method make booking for… increases the value of make bookings property. Cancel booking decreases value of bookings property. With the cars it said there’s a method change speed where it increases or decreases the value of current speed property. So I just thought it was a really interesting way to look at programs as not just lines of code that are making a computer or an application do something. But it’s like, a representation of the world, and the things or the objects IN the world and how we interact with them.

_

Love & Peace,

Danielle

Up & Rolling

Getting a new project going.

Love & Peace,

Danielle

Block Formatting Context

So I built a mock social media profile converting a Photoshop Design to a functional HTML5 & CSS3 webpage:

While working on the social network profile and positioning the elements, I wanted the submenu in the content area to overlay the top area with the profile and background photos.
The live page of the project I’m referring to can be seen here and you can check out the code on my GitHub repo.

So I added “overflow: visible” to the #content-area element, and realized that I had overwritten the previous “overflow: auto” value that I had already written like so:

#content-area {
background: #FAFAFA;

overflow: auto;

position: relative;
}

To:

#content-area {
background: #FAFAFA;

overflow: auto;

position: relative;

overflow: visible;

}

And while that alone wasn’t that important, the issue was that without the overflow: auto, the background color of the content area was no longer covering the whole background. Only where the content area had padding (width within the border-box). This is because the content area no longer had a Block Formatting Context. So now being that the side column and the main area are floated elements, they are Out of Flow elements, out of the flow of the layout. Therefore, the content area and its background only contain the content/padding, not the floated elements.

So I set out to find an alternative to how I could create a block formatting context for the content area. First I considered creating another container inside or outside the content area to contain the background color while the content area contains the content. But after thinking about it for a few moments it didn’t appear that would work.

Next I reviewed the different ways a block formatting context is created, trying to find if there’s a different CSS property that I could apply to the content area, that would achieve the same result. Here I stumbled upon the experimental “Display: Flow-Root” value. And more information on the overflow property.

According to the MDN docs:

“The problem with using overflow to create a new BFC [block formatting context] is that the overflow property is meant for telling the browser how you wish to deal with overflowing content. There are some occasions in which you will find you get unwanted scrollbars or clipped shadows when you use this property purely to create a BFC. In addition, it is potentially not very readable for a future developer, as it may not be obvious why you used overflow for this purpose.

A newer value of display gives us the ability to create a new BFC without any other potentially problematic side-effects…The value name of flow-root makes sense when you understand you are creating something that acts like the root element (html) in terms of how it creates a new context for the flow layout inside it.”

So I removed the overflow: auto and added display: flow-root:

#content-area {
background: #FAFAFA;
overflow: auto;
position: relative;
overflow: visible;
}

To:

#content-area {
background: #FAFAFA;
position: relative;
overflow: visible;

display: flow-root;

}

And this did indeed work in making the background color cover the whole content area BUT, alas, the display: flow-root value is still experimental and still doesn’t have much browser compatibility.

So I had to try something different.

Then I thought maybe I should’ve added the background color to the root. Not so much the root but to the body to be precise. And I then removed display: flow-root and the background color from the #content-area, and added the background to the body:

body {

background: #FAFAFA;

}

#content-area {
position: relative;
overflow: visible;
}

I did not need to add overflow: auto to the body to replace the overflow: auto/display: flow-root I had on the #content-area element, because most browsers automatically give the body that capability. As per W3C Recommendation:

“UAs [User Agents] must apply the ‘overflow’ property set on the root element to the viewport. When the root element is an HTML “HTML” element or an XHTML “html” element, and that element has an HTML “BODY” element or an XHTML “body” element as a child, user agents must instead apply the ‘overflow’ property from the first such child element to the viewport, if the value on the root element is ‘visible’. The ‘visible’ value when used for the viewport must be interpreted as ‘auto’. The element from which the value is propagated must have a used value for ‘overflow’ of ‘visible’.”
Source: https://www.w3.org/TR/CSS2/visufx.html#propdef-overflow

So this is how it currently looks. Let me know your thoughts or any tips, tricks or another way you might’ve seen to do it. I’d love to hear your perspective.

Love & Peace,

Danielle

Margin Wants To Play Too

I built a mock social media profile converting a Photoshop Design to a functional HTML5 & CSS3 webpage:

You can see the live page here and check out the code on my GitHub.

While I was doing this project some of the elements and columns did not do as expected, and I realized that some elements kept moving out of place. And after a process of elimination I uncovered that this was only happening when I applied margin to certain elements.

It never really struck me why box-sizing: border-box is called border-box until I tried to use it to adjust the sizes of some elements. I had assumed that sense margin is a part of the box model that that would go right along and get adjusted to. Did that happen? Not so much…

It turned out that box-sizing: border-box limits the width and height of the content, padding and border of an element. But if for example, you’re trying to limit and split elements evenly within a container, but you have margin on them…

It seems that’s why it’s called border-box, not margin-box. The elements on your page are going to be doing their own thing.

To give an example I tried using margin in the code below with box-sizing: border-box active on all elements.

#top-area .profile-info .user-details h3 {
color: #000;
font-size: 24px;
font-weight: 300;
margin-top: 40px;

margin-bottom: 10px;

}

#top-area .profile-info .user-details a {
display: inline-block;
color: #000;
font-size: 12px;
text-transform: uppercase;
background: rgba(255, 255, 255, .7);
margin-left: 5px;
width: 45%;
margin-right: 5px;
text-align: center;
transition: background .4s ease-in-out;
}

So instead I changed it to:

#top-area .profile-info .user-details h3 {
color: #000;
font-size: 24px;
font-weight: 300;

margin-top: 40px;

/* margin-bottom: 10px; Not apart of box-sizing */

}

#top-area .profile-info .user-details a {
display: inline-block;
color: #000;
font-size: 12px;
text-transform: uppercase;
background: rgba(255, 255, 255, .7);
margin-left: 5px;
width: 45%;
margin-right: 5px;
text-align: center;
transition: background .4s ease-in-out;
}

Here I simply swapped the margin for padding. In a different situation with rows or columns I could also add a class to the last container in a row and remove its margin. Sense there would be no next item in a row, no margin is needed to be between anything, after the last row/column.
In addition, with columns I’ve found I could do something like “width: calc(50% – 10px);” on each column, similar to Bootstrap.

It should be interesting configuring more work-arounds for this. Especially for more complex issues. But it should be fun getting margin back in on the party. If you have any suggestions or work-arounds feel free to let me know. I’d love to hear about it.

Love & Peace,

Danielle

First Example

The code below is some of the code from the Color Guessing Challenge pictured above.

Some snippets from the code are great examples of Execution Context (The Creation and Execution Phases) and Hoisting.

var gameOver = false;
var squares = document.querySelectorAll(‘.square’);

var newRandomColors = [];

var colorDisplay = document.querySelector(‘#colorDisplay’);

colorDisplay.textContent = winningColor;

var messageDisplay = document.querySelector(‘#message’);

for(var i = 0; i < squares.length; i++) {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var colorString = ‘rgb(‘ + r + ‘, ‘ + g + ‘, ‘ + b + ‘)’;
squares[i].style.backgroundColor = colorString;

newRandomColors.push(colorString);

var clickedColor = this.style.backgroundColor;
if(clickedColor === winningColor) {
changeColors(clickedColor);
messageDisplay.textContent = ‘Correct!’;
gameOver = true;
} else if(clickedColor !== winningColor) {
this.style.backgroundColor = ‘#232323’;
messageDisplay.textContent = ‘Try Again’;
}

});
}

var winningColor = newRandomColors[Math.floor(Math.random() * newRandomColors.length)];

function changeColors(color) {
for(var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = winningColor;
}
}

If the winningColor variable were defined BEFORE the for loop, then no RGB winningColor would display in the header. That’s because the random colors are added to the newRandomColors array within the for loop. So if you had this line,

var winningColor = newRandomColors[Math.floor(Math.random() * newRandomColors.length)];

before the for loop, the newRandomColors.length part would be 0, and the newRandomColors array would be empty. Therefore a winning color would not exist, and the squares and header would not change color when you win, nor does the game do anything except still do what it does when you choose an incorrect square.

This illustrates that before the code is executed, the Execution Context during the Creation phase will create memory space for variable declarations, not their definitions, and for function statements. Then due to Hoisting, when the code is executed during the Execution Context Execution phase, the code will have access to these values from the very first line of code, even if the location (Lexical Environment) the values are physically written in the code is all the way at the bottom.

Second Example

This version of the code is a little more organized, now using a function to pick the winning color, instead of the winningColor variable:

var gameOver = false;
var squares = document.querySelectorAll(‘.square’);
var newRandomColors = [];
var colorDisplay = document.querySelector(‘#colorDisplay’);
var messageDisplay = document.querySelector(‘#message’);

for(var i = 0; i < squares.length; i++) {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var colorString = ‘rgb(‘ + r + ‘, ‘ + g + ‘, ‘ + b + ‘)’;
squares[i].style.backgroundColor = colorString;
newRandomColors.push(colorString);

var clickedColor = this.style.backgroundColor;
if(clickedColor === winningColor) {
changeColors(clickedColor);
messageDisplay.textContent = ‘Correct!’;
gameOver = true;
} else if(clickedColor !== winningColor) {
this.style.backgroundColor = ‘#232323’;
messageDisplay.textContent = ‘Try Again’;
}

});
}

var winningColor = pickColor();

colorDisplay.textContent = winningColor;

function changeColors(color) {
for(var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = winningColor;
}
}

function pickColor() {
var randomIndex = Math.floor(Math.random() * newRandomColors.length);
return newRandomColors[randomIndex];
}

The winningColor variable is still placed after the for loop, and now the execution of the pickColor function also placed after the for loop in this example, for the same reasons the winningColor variable was in the first example. And the execution of the function pickColor would not work when the code is executed, were it not for the Hoisting of its function statement. Because of this, pickColor() can be written before its function statement, and the function will still be executed.

Conclusion

So that about sums it up for these examples of Execution Context (Creation and Execution Phases) and Hoisting. And this also was an unintentional example of Lexical Environments. Let me know your thoughts. And of course if you have any suggestions feel free to share those too.

Love & Peace,

Danielle

Self-Development: Event Time

I’m pulling this book back off the shelf and sharing points about Event Time vs. Clock Time, from the book The One Thing by Gary Keller.

Love & Peace,

Danielle