using ‘add class’ to switch from grid to list

Make sure to have jQuery and bootstrap CSS installed

the HTML

First, we create two buttons.

– One is to indicate list form. The id of this button is list.
– The second button is to indicate grid form. The id of the button is grid

We place the buttons inside a container, with class btn-group. The sibling div has an id of products. This is where we place our contents. Hence, we have a div for out buttons. And another div to maintain our contents

In our content div, the default situation is that we have grids, with content inside them. We create grids by using class col-lg-4 in order to control width. col-lg-4 says we have the grid to have a with of 4 parts, while the total is 12 parts. This means we have three grids for each row. In other words, we want the width to be 33.3333%.

We then fill in the contents with an image, a title, and some text.

Finally, we have something like so:

this will give us a starting point looking like this.

jQuery

The whole trick to making it go from grid to list is to add a class. Then let CSS take over to change the display according to the class.

Hence, the first step is to simply add a class name. Let’s add list-group-item for when the user clicks on the list button. And remove this class when the user clicks on the grid button.

We use jQuery to do this. We simply grab the id of the buttons. Then process the click event. We implement the handler for when the button is clicked. We say, when the buttons is clicked, for each div.item under #products, we want to add a class list-group-item to that div.

When we click on button #list, we add class list-group-item. Thus you’ll dynamically see the class name appear in the DOM. This enables us to use CSS to give it a new look on the fly.

When we click on the button again, the class disappears. Visually, we can use CSS to return it to its default appearance.

the CSS

Now, we get to the part where we change the appearance.

First, we include the style.css in your header

Now, let’s say we want to give appearances of a green border for the grid. And make this green border disappear when its list.

Now when you click the grid list

you add the class to the div. Via CSS, it will know that for that class, we should put a green border on that div. When you click the list button, the class “list-group-item will disappear, and naturally the CSS of green border will not apply anymore. In fact, the CSS for .item, is no border.

The biggest difference between grid and list is that our grid is 33.33%. But a list should take up 100% width. So that’s what we’ll do:

Thus, you’ll be able to toggle it like so:

Basically, that’s all there is to it.

Other stuff

Say I want add a red border around the image when its list form. And clean up some margin spacing issues:

Then I want to put the word list before the list items.

As you can see, just make sure to put CSS for .item.list-group-item because you’re drawing for list form.

Whatever CSS you applied to list-group-item will be gone when you remove the class.

() surrounding the function

  • https://stackoverflow.com/questions/1634268/explain-the-encapsulated-anonymous-function-syntax
  • https://stackoverflow.com/questions/440739/what-do-parentheses-surrounding-an-object-function-class-declaration-mean

The Problem

In javascript, we implement twoPlusTwo.

You can also create an anonymous function and assign it to a variable:

You can encapsulate a block of code by creating an anonymous function, then wrapping it in brackets and executing it immediately:

However, this does not work:

Why?

Answer

doesn’t work because:

is being parsed as a Function Declaration, and the name identifier of function declarations is mandatory.

Also,

is same as

The reason this wouldn’t work is that the JavaScript engine interprets this as a function declaration followed by a completely unrelated grouping operator that contains no expression, and grouping operators must contain an expression.

Surrounding it with a parentheses

Now, when you surround it with parentheses like so:

it is evaluated as a Function Expression, and function expressions can be named or not.

i.e:

…and thus, wrapping parenthesis around it, it gets the result of that expressions in the same way having a variable assigned to the result:

The only difference is that we assigned function f to a variable. But we didn’t assign the anonymous function anywhere.
Let’s try assigning it to a variable so we can see the similarities:

or simply

as an Immediately Invoked Function Expression

The Function Expression used in this term is directly to indicate anonymous function expression.
The Immediately Invoked used in this term is the ( … ) that gets the function expression, which is pushed onto the local stack. We don’t see it because we did not assign any named reference variables to it. Just know that it is pushed onto the local stack.
Then this function expression is executed via ().

Further Information

The ‘()’ surrounding the anonymous function is the ‘grouping operator’ as defined in section 11.1.6 of the ECMA spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.

Taken verbatim from the docs:

11.1.6 The Grouping Operator

The production PrimaryExpression : ( Expression ) is evaluated as follows:

Return the result of evaluating Expression. This may be of type Reference.
In this context the function is treated as an expression.

module pattern (js)

ref – https://toddmotto.com/mastering-the-module-pattern/

1 – create IIFE

The module pattern’s basic premise is that a IIFE is created, and thus, creates a closure.

In other words, it declares a function, which then calls itself immediately.
These are also known as Immediately-Invoked-Function-Expressions

The function creates a new scope, and thus, privacy.

JavaScript doesn’t have privacy, but creating new scope emulates this when we wrap all our functional logic inside them.

The idea then is to return only the parts we need, leaving the other code out of the global scope.

2 – namespace

After creating new scope, we need to namespace our code so that we can access any methods we return. Let’s create a namespace for our anonymous Module.

We then have Module declared in the global scope, which means we can call it wherever we like, and even pass it into another Module.

3 – private methods

Private methods are anything you don’t want users/devs/hackers to be able to see/call outside the scope they’re in.

To make our methods inaccessible outside of that scope:

The privateMethod is declared inside the new scope. If we were to attempt calling it anywhere outside of our module, we’ll get an error thrown and our JavaScript program will break!

Another example. We declare function expression variable privateMethod. Then a function expression variable publicMethod. publicMethod’s anonymous function definition involves calling privateMethod.

Then it gets returned in an object.

…of course, you can use these public methods to manipulate private properties.

4 – giving access to outside using “return”

The object literal syntax goes something like this:

Using the same syntax, we want to return an object so that others can access whatever we decide to give them.
The methods bound to the Object will be accessible from the Module’s namespace.

One way to do this is via

anonymous Object Literal return

And hence we provide access to functionality like so:

..and thus, if you have a private method somewhere, you’ll have to use the public method to access that private

Locally Scoped Object

Another way is to locally create an object. Then set this object up by adding function attributes to it. Finally, when its complete, we return this object

1) create empty literal object on the local stack
2) add properties to it that are functions and variables
3) return this literal object

Stacked locally Scoped Object Literal

1) create object literal referenced by variable name.
2) declare attributes inside this object literal
3) return object literal by returning its variable reference.

Revealing Module Pattern

1) declare function expression variables that references anonymous functions
2) return object literal with properties that references the function expression varaibles.

In this way, we reveal public pointers to methods inside the Module’s scope.
Declare functions via named references so that you don’t get hoisting mixups. Then, return an object with named properties to those references.
This again, can create a really nice code management system in which you can clearly see and define which methods are shipped back to the Module.

Augmenting Modules

Say you have a really nice revealing pattern going like so:

You got your function expressions declared. You return a nice literal object with properties referencing your expressions.
But…what if you want to extend this module? But from a third-party, and not add anything into it anymore.

In other words, we want to add a “thirdMethod”, but not mess with the current Module implementation.

Solution:

Let’s create another Module named ModuleTwo, and pass in our Module namespace, which gives us access to our Object to extend:

Hence, its basically creating a singleton, and passing in another singleton via injection. We then add a property for a function expression. Then we simply return Module.

You’ll notice I’ve passed in Module || {} into my second ModuleTwo, this is incase Module is undefined – we don’t want to cause errors now do we ;). What this does is instantiate a new Object, and bind our extension method to it, and return it.

Private Naming Conventions

make sure to label private properties with underscore

functions (and different ways of defining them in js)

ref – https://dmitripavlutin.com/6-ways-to-declare-javascript-functions/
https://www.davidbcalhoun.com/2011/different-ways-of-defining-functions-in-javascript-this-is-madness/

A function is a parametric block of code defined one time and called any number of times later.

1) function declaration

A function declaration is made of function keyword. It is followed by an obligatory function name, a list of parameters in a pair of parenthesis (para1, …, paramN) and a pair of curly braces {…} that delimits the body code.

The function declaration creates a variable in the current scope with the identifier equal to function name. This variable holds the function object.

The function variable is hoisted up to the top of the current scope, which means that the function can be invoked before the declaration

Which practically means that, yes, you can call the functions before they’re written in your code. It won’t matter, because the entire function gets hoisted to the top of its containing scope. (This is contrasted with variables, which only have their declaration hoisted, not their contents, as we’ll see in the next section).

Function Expression

A function expression is determined by a function keyword, followed by an optional function name, a list of parameters in a pair of parenthesis (para1, …, paramN) and a pair of curly braces { … } that delimits the body code.

This function object can:
– be referenced by a local variable you declare.
– assigned to a method name on an object
– be used as a callback function

2) unnamed function expression

function expression used as a method name on an object:

Will be executed as this:

Therefore, with functions, the order of setting and calling is important:

function expressions with parenthesis

Here again, we’ll see that if we declare an anonymous function, the function’s name property will be valid to use inside the function. In other words, the function name is only accessible within the function. However, globally, we’ll have to use the reference name.

Useful for Recursion
Because the function’s name is accessible in the function itself, this turns out to be useful for recursive functions, much more useful than the plain old anonymous function.

Here’s a trivial recursive function to illustrate calling itself from within the named function expression:

IIFE

first, lets look at a standard example:

Useful for debugging
As a few have pointed out, giving previously anonymous functions names helps in debugging, since the function name shows up on the call stack.

3) Named function Expression

the function object has a property name, which displays the name of the function. It is assigned to a variable. The variable is used in the current scope. But inside the function body, the function name is used.

Also, a named function is created, the “name” property holds the function name.

Inside the function body a variable with the same name holds the function object. The function name (funName) is available inside the function. However, outside, it is not. Outside, it recognizes the variable name which the function was assigned (getType).

4) Shorthand Method definitions

short hand method definitions are used in object literal construction like so:

add() and get() methods in collection object are defined using short method definition. These methods are called as usual: collection.add(…) and collection.get(…).

but why?
The short approach of method definition has several benefits over traditional property definition with a name, colon : and a function expression like so:

– A shorter syntax is easier to read and write
– Shorthand method definition creates named functions, contrary to a function expression. It is useful for debugging.

5) Arrow Functions

An arrow function is defined using a pair of parenthesis that contains the list of parameters (param1, param2, …, paramN), followed by a fat arrow => and a pair of curly braces {…} that delimits the body statements.

note: When the arrow function has only one parameter, the pair of parenthesis can be omitted. When it contains a single statement, the curly braces can be omitted too.

The function declared using a fat arrow has the following properties:

– The arrow function does not create its own execution context, but takes it lexically (contrary to function expression or function declaration, which create own this depending on invocation)

– The arrow function is anonymous: name is an empty string (contrary to function declaration which have a name)
– arguments object is not available in the arrow function (contrary to other declaration types that provide arguments object)

this keyword is one of the most confusing aspects of JavaScript (check this article for a detailed explanation on this).
Because functions create their own execution context, often it is hard to catch the flying around this.

ECMAScript 6 improves this usage by introducing the arrow function, which takes the context lexically. This is nice, because from now on is not necessary to use .bind(this) or store the context var self = this when a function needs the enclosing context.

short callbacks

The parenthesis pairs and curly braces are optional for a single parameter and single body statement. This helps creating very short callback functions.

Originally, given an array, we use Array’s prototype function some to see if there exist a zero in the array. The some() method tests whether at least one element in the array passes the test implemented by the provided function.
If it exists, return 0, if it does not, return false.

However, since there’s only a single parameter, and a single body statement, we can do it shorthand like so:

5) Generator functions

Function declaration

standard declaration of a generator function:

Function expressions

now we assign an anonymous function generator definition to an expression variable. Execute the expression, and call the methods on it.

shorthand

In all 3 cases the generator function returns the generator object g. Later g is used to generated series of incremented numbers.

6 – new Function

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code because such functions are parsed with the rest of the code.

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using eval with code for a function expression.

for of loop

Standard Array

for standard arrays, you can definitely use for of and it would log


output:

mini
mani
mo

iterating function argument object

There’s a argument object that is of object Array. You can iterate through it


output:

a
b
c

sets

Map


output:
Key: one and Value: 1
Key: two and Value: 2

arguments object

The Arguments Object

JavaScript functions have a built-in object called the arguments object.

The argument object contains an array of the arguments used when the function was called (invoked).

This way you can simply use a function to find (for instance) the highest value in a list of numbers:

..or create a sum function

Arguments are Passed by Value

The parameters, in a function call, are the function’s arguments.

JavaScript arguments are passed by value: The function only gets to know the values, not the argument’s locations.

If a function changes an argument’s value, it does not change the parameter’s original value.

Changes to arguments are not visible (reflected) outside the function.

spread operator

ref – https://codeburst.io/javascript-the-spread-operator-a867a71668ca

The spread operator allows an expression to be expanded in places where multiple elements/variables/arguments are expected

given…normally, the middle reference in arr would reference var middle. This makes it so that its an array inside of an array. Its not what we want.

What we can do is to expand middle’s elements into arr like so:

Remember the spread operator definition you just read above? Here’s where it comes into play. As you can see, when we create the arr array and use the spread operator on the middle array, instead of just being inserted, the middle array expands. Each element in the middle array is inserted into the arr array. This means that instead of nested arrays, we are left with a simple array of numbers ranging from 1 to 6.

Copying arrays

Voila! We have a copied array. The array values in arr expanded to become individual letters which were then assigned to arr2. We can now change the arr2 array as much as we’d like with no consequences on the original arr array.

Appending Arrays

String to Array

Bonus example: Use the spread operator to simply convert a string to an array of characters

No need to use ‘call’

default parameters

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

Evaluated at runtime

The default argument gets evaluated at call time.

we can even assign functions to it:

with call, argument list, and default parameters

then we declare a function with defaults.

The 1st param a references 1st param.
We then have 2nd param b, which defaults to 5.
3rd param c copies over from 2nd param.
d param references go function
e references the ‘this’ object, whatever it is pointing.
f references the default argument list
g references the ‘this’ object, and then access its property ‘value’

We call the function like so:

using call, we provide the first object as the ‘this’ object for withDefaults function. the integer 6680 is the 1st parameter.
thus, just from this knowledge:

a will be 6680
e is the {value: ‘=^_^=’}

We then look at the 2nd param which is b = 5.
third is c = b, which means c is 5.
param 4 is d referencing the returned string of function go().
param 5 e reference the this object, which is supplied by our call function’s 1st parameter.
Hence e references {value: ‘=^_^=’}

f references the basic argument list
finally, g references the this object’s value property.


output:

a is referencing param1: 6680
b references 5
c references 5
d references function go(), which returns 😛
e = this:
{ value: ‘=^_^=’ }
f = [object Arguments]
=^_^=

Object as Hash

ref – https://medium.com/front-end-hacking/es6-map-vs-object-what-and-when-b80621932373

Object is the great choice for scenarios when we only need simple structure to store data and knew that all the keys are either strings or integers (or Symbol), because creating plain Object and accessing Object’s property with a specific key is much faster than creating a Map (literal vs constructor, direct vs get() function call).

An Object in Javascript is dictionary type of data collection — which means it also follows key-value stored concept.

Construction

In general, like in Array, do not use built-in constructor over literal in creating new object, because:

  • More typing
  • Slower performance
  • Confusion & increasing more chances for mistake

for example:

Setting key/values

You can initialize it with key/value pairs, or simply assign it via brackets.
Each key in Object — or we normally call it “property” — is also unique and associated with a single value.
In addition, Object in Javascript has built-in prototype. And don’t forget, nearly all objects in Javascript are instances of Object.

Object: keys must be in simple types (int, string, or symbol)

In Object, it follows the rule of normal dictionary. The keys MUST be simple types — either integer or string or symbols. As shown previously, strings and integers are used often. However, we can also use symbols.

Looping through the Object keys

Looping through symbols

try catch performance issues

ref –

  • http://shanghaiseagull.com/index.php/2018/06/22/try-catch/
  • http://shanghaiseagull.com/index.php/2018/06/25/throw-error/
  • https://stackoverflow.com/questions/3217294/javascript-try-catch-performance-vs-error-checking-code
  • https://stackoverflow.com/questions/1722964/when-to-use-try-catch-blocks

Programs must be written for people to read, and only incidentally for machines to execute

Always aim for readable code

The key thing to remember is: Avoid try-catch in performance-critical functions, and loops

Anywhere else they won’t do much harm. Use them wisely, use them sparingly. As a side note if you want to support older browsers they may not have try-catch.

The try-catch block is said to be expensive. However if critical performance is not an issue, using it is not necessarily a concern.

The penalty with try-catch blocks everywhere is:

  • Readability: plumbing your code with plenty of try-catch is ugly and distracting
  • inappropriate: it’s a bad idea to insert such block if your code is not subject to exception-crash. Insert it only if you expect a failure in your code.
  • the try-catch block is synchronous and is not effective when it comes to async programming. During an async request you handle both the error and success events in dedicated callbacks. No need for try-catch.

The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.

Don’t catch an exception if you’re only going to log the exception and throw it up the stack. It serves no meaning and clutters code.

Do catch an exception when you are expecting a failure in a specific part of your code, and if you have a fallback for it.

Of course you always have the case of checked exceptions which require you to use try/catch blocks, in which case you have no other choice. Even with a checked exception, make sure you log properly and handle as cleanly as possible.

Assuming undefinedfunction() is undefined, when the browser runs it, no errors will be shown. The syntax for try/catch/finally is a try clause followed by either a catch or finally clause (at least one or both of them). The catch clause if defined traps any errors that has occurred from try, and is indirectly passed the error object that contains additional info about the error. Lets see a slightly more complex example now:

Click on the above button, and notice how only “An Error has occurred” alert pops up, but not “I guess you do exist”. This tells us that when try encounters an error, it immediately skips any remaining code inside it and goes straight to catch. The default error message is obviously suppressed, though you can still retrieve this information by accessing the Error object that gets indirectly passed into catch.