Javascript: Node Package Manager (NPM)

  • What are NPM’s
  • Set Up

In this blog we will cover what NPM is and what they do in an abstract manner that serves to give context so that reader can gain a basic understanding. If the reader is just starting to use React or learning Javascript or new to programming in general, then this post will be useful. For more veteran programmers, please skip to the end of the article where links will be provided that lead to the more complex nature of NPM.

NPM, or Node Package Manager, is a software library (similar to gem’s for Ruby users) that is open to the public to quickly solve issues that have already been solved before. NPM’s also give programmers tools to make certain tasks easier. NPM especially helps when using frameworks like React.

Setting up NPM is pretty straightforward. First, check if you node installed, if you do then you should already have NPM installed. Check by typing in the following into your command line interface.

npm -v

If you don’t have node installed click on this link that will take you to the node site -> https://nodejs.org/en/

Once you have NPM installed, you can install packages by typing the following code block into your command line interface (CLI). Make sure you are in your project folder so that the proper packages get installed in the correct location. You can search through the npm website to find packages and descriptions of their functionality. https://www.npmjs.com/

// Windows example

C:\>npm install <package>

// Mac example

npm install <package>

Simply put, NPM and it’s packages are great for daily programmer. It saves times, makes coding a lot easier, and makes coding more straightforward. This is the very beginning of NPM usage and there are deeper rabbit holes to be found. The following are a list of links that’ll give you these holes to dive into.

Alternative introduction to NPM
https://nodesource.com/blog/an-absolute-beginners-guide-to-using-npm/
How to use npm’s
https://flaviocopes.com/how-to-use-npm-package/
Creating and Publishing your own npm’s
https://docs.npmjs.com/creating-and-publishing-private-packages

Javascript Oddities

  • ‘Null’ and ‘undefined’
  • ‘objects objects objects’
  • Number or String?
  • if it an Array?
  • typeof
  • function fun

After learning of a few weird ‘bugs’ that javascript produces, I became intrigued and thought it would be fun to look for more of these cases. This is by no means a full list but just some examples I found by messing with JS and searching the internet.

Null and undefined, on their own, are part of the seven instances that are treated as falsey values in JS. Maybe because they belong to this exclusive club, do they act oddly in these scenarios. Feel free to test these examples out in your terminal and watch the magic(?) happen.

null ** 2;
// 0

undefined ** null;
// 1

This already looks some sort of brain teaser where the problem is to figure out what the logic is even based on. Even mathematically (outside the scope of code) if we were to treat null as zero values, the returns don’t make sense. The first example here would look like 0**2, which would return a value of 1. The second example would look like 0**0 which has no agreed on value (either 1, 0, or undefined). Obviously, math and programming logic might be directly connected here, but the point is to try to tackle illogical outcomes through logical means.

The next five examples involve arrays ‘[]’ and objects ‘{}’. These examples are even weirder because of odd outcomes and because of the fact that these code examples would likely never be practiced in the field.

{} + {};
// '[object Object][object Object]'

{} + '{}';
// NaN

[] + {};
// '[object Object]'

{} + [];
// 0

[] + [];
// ''

Of these five examples, the second is probably the most reasonable because an object{} or string are numbers. However, you can add strings together in JS, so the oddity here is the return value of NaN as the error instead of another error. What’s curious about the first, third, and fifth example, is the fact that they return strings. Also, the fourth example returns zero. None of these values could rationally be predicted.

This next set of oddities, are probably the ones that make the most sense because they can be somewhat logically predicted, but are included in this blog because they are still interesting to explore.

1 + 2 + 3;
// 6

'1' + 2 + 3;
// '123'

1 + '2' + 3;
// '123'

1 + 2 + '3';
// '33'

The first example is completely normal, and something taught right away in most education systems. The second example is slightly weirder. We know that JS likes to add strings together and it makes sense that it would convert the number 2 into a string to create ’12’ and do the same to the number 3 to create ‘123’. The third example still does this string conversion, but only after adding two numbers. 1 + 2 is 3, 3 + ‘3’ is ’33’. The insight we can gain here is that order matters, and more than anything this is good visual practice to get used to this fact.

This next section covers the Array(); function.

Array(5);
// [<5 empty items]

Array(5) + 2;
// ',,,,2'

Array(5).join("w");
// 'wwww'

Array(5).join(2);
// '2222'

Array(5).join("w"+1);
// 'w1w1w1w1'

Array(5).join("w"-1);
// 'NaNNaNNaNNaN'

The first example here is more or less normal. If you assign a variable to this example and looked at length, it would indeed return 5 even though the array has undefined values. The second example, is odd because it converts the array to a string with the fifth (assumed) comma replaced with a 2. The third and fourth examples are more or less the same but with the letter ‘w’ and the number ‘2’ respectively. The odd part here is that the fifth (assumed) comma/placeholder is missing. The fifth example makes sense after looking at the third example here but on its own, again, out of the ordinary. The last example, again, looks normal after the third and fifth examples but it’s interesting that NaN is converted to a string and that subtracting is where JS draws the line in returning an error type.

These last few examples include typeof() and anonymous function behavior. The typeof behavior is most likely intended to work like this but is still interesting and could be used to the advantage by the savvy programmer.

typeof(Null); 
// 'undefined'

typeof(Null) + 'hey';
// 'undefinedhey'

typeof(5);
// 'number'

The first example shows that ‘undefined’ is returned as string, and the second example proves it because adding a string to a string combines the two (string behavior). The third example shows that it always returns a string regardless of type.

let fn = function(){console.log('hello there')};
5 + fn;
// "5function(){ console.log('hello there') }"
'hey' +fn;
// "heyfunction(){ console.log('hello there') }"
5 + fn();
// hello there
// NaN
'hey' + fn()
// hello there
// 'heyundefined'

Here I set up a variable to equal an anonymous variable. Interestingly, adding a num or string to the variable (without calling the function), returns a string with the combination of the string and the whole function as if it were initially written as a string. However, adding a number to the variable with the function called returns NaN (after the console.log is outputted), which finally makes sense. Adding a string, instead of a number, again runs the console.log but then returns a string of the original string that was added to fn() along with ‘undefined’.

Although this information is a step away from relevant Javascript knowledge, it offers an illogical side to what is supposed to be something built on logic. It’s important to realize the faults of our tools so that we can recognize their limits and so that the next generation of that language, or any other language, can be better than the last.

Other relevant links to further your knowledge in Programming Oddity

Ruby on Rails: Seeding Data

  • Before we begin… (pre-intro)
  • Intro
  • Faker
  • Other ways to seed…
  • Outro

Before we begin, make sure that you have your tables (schema) set up and their associations. Click on the next two links if you need a little help with that.

https://guides.rubyonrails.org/active_record_migrations.html

https://guides.rubyonrails.org/association_basics.html

Creating a rails app/website requires a lot of coordination between a lot of models through associations. Then you have to toss in model methods, controllers, views, routes, and… well, you get the point. Any project or product is daunting to begin with.

By injecting some data into your project and making it look more like a real concept than some abstract idea (programming provides enough of that), you can find it much easier to navigate your project through the back and front end of your code.

Table looks like this:
create_table "boxes", force: :cascade do |t|
    t.string   "brand"
    t.string   "sender"
    t.string   "receiver"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

Faker is one of the more popular methods of seeding data into your project without the headache of thinking up relevant words. After installing your Faker gem, simply go to your seed.rb file in the db folder of your rails project and type in some code similar to this…

25.times {
   Box.create(
   brand: Faker::Company.name,
   sender: Faker::Name.first_name,
   receiver: Faker::Name.first_name
   )
}

aaaand type in ‘Rake db:seed’ into your consoler and let the magic happen. If you need more data user 50.times or 100.times, as long as your environment can handle it all at once. Or use less…

Perhaps Faker isn’t for you, maybe you want some data that is more specific to your needs! .each is your friend. The hard of writing Box.create fifty times is subverted by creating an array of data and then filtering through that list with .each. Here is an example…

box_list = [
    ["Company 1", "John", "Jane"],
    ["Company 2", "Alex", "Alexa"],
    ["Company 3", "Samantha", "Sam"],
    ["Company 4", "Martha", "Mark"]
]

box_list.each do |obj|
    Box.create(company: obj[0], sender: ob[1], receiver: [2])
end

This does require some more work than using the Faker gem, but using relevant data can be helpful depending on your programming preferences. But using either of these two methods is much better than typing Box.create over and over again.

Here are some additional links and threads to further your seeding knowledge or some common errors you may get in the seeding world:

Ruby: ‘ampersand’, ‘and’, ‘pipes’, and ‘or’

  • && vs ‘and’ with examples
  • || vs ‘or’ with examples
  • The case for and/or in Ruby

There are many secrets to be unlocked from using `and` and `or`, but for the purpose of their introduction to a new Ruby coder, we will cover their general usage and direct relatability/substitution of `&&` and `||`.

Ampersand GIF by GIPHY Studios Originals - Find & Share on GIPHY

Most programmers naturally believe that because programming language is a ‘foreign’ idea in contrast to the ‘real’ world, then the language itself must look different than English (directed toward English speakers). The following code would look completely normal to a programmer…

&& Example

if 5 == 5 && 4 > 2
    return "This will pass"
end 

However, this might look more friendly to the average laymen…

‘and’ Example

if 5 == 5 and 4 > 2
    return true
end

Although there are some minor differences between the deeper functionality of `&` and `and` for conditional formatting, they are virtually the same.

Detective Pikachu Pokemon GIF - Find & Share on GIPHY

By this point you can assume how `or` and `||` are related.

if 5 == 4 || 4 > 2
    return "This will pass"
end

`or` Example

if 5 == 4 or 4 > 2
    return "This will pass"
end

While `and` and `or` have different eventual functions than their counterparts, it is extremely important to know that they exist and can be using in lieu of the more ‘traditional’ methods.

Ruby is a novice programmer’s best friend due to its relatively superior maneuverability and readability. This colorful language, made by Yukihiro “Matz” Matsumoto, is born from the philosophy that programming should be enjoyable for the programmer, not just the user. Using `and` or `or` in lieu of `&&` or `||`, is no exception.

`and` and `or` offer a more realistic view of the connection between programming languages and our regular common languages. They give us a truth that all languages are based on blocks of logic, either if they are based on one’s and zeros’s, T’s A’s G’s C’s, or the simple point and grunt. If it carries the point across, it’s usually best to remain as universal as possible.

Additional links to explore the inner magic of `and` and `or`…

Using ‘and’ and ‘or’ in Ruby
http://www.virtuouscode.com/2010/08/02/using-and-and-or-in-ruby/

Design a site like this with WordPress.com
Get started