Michael Adsit Technologies, LLC.

Search terms of three or more characters

Some Basic JavaScript Concepts

The purpose of this lesson is to use the investigation techniques started last lesson for seeing what the code actually means. We will also explore some definitions and what they mean practically.

What is JavaScript?

In the first web lesson, we got the brief definition of "JavaScript is the gearing of the web, allowing users to have fully interactive experiences." Through the last several lessons, we have seen that it does stuff both through user interaction and page loading. More formally JavaScript is a scripting language originally designed for creating a dynamic user experience in the browser. It is now used for both client side (the web browser) for that purpose, as well as server side (via node js) to allow running things that an end user will never see. JavaScript is an untyped language, meaning that what kind of things are being worked with are not set in stone.

Types in JavaScript

We just mentioned that JavaScript is untyped, but that does not mean that there are not types. If you still have the server running from the last lesson, you may open the DevTools (f12 button or right click and Inspect) to the Console tab and type in the following (one line at a time), with the comments (everything after //) showing what should appear in the Console tab. If you do not have the server running, everything through buttons should give back 'undefined'

1typeof clickedTimes // 'number'
2typeof onButtonClick // 'function'
3typeof console // 'object'
4typeof buttons // 'undefined'
5typeof 'test' // 'string'
6typeof 123 // 'number'
7typeof [] // 'object'
8typeof undefined // 'undefined'
9typeof null // 'object'
10typeof Symbol('test-symbol') // 'symbol'
11typeof 'abc' // 'string'
12typeof `a${1}c` // 'string'
13typeof 2n // 'bigint'
14typeof false // 'boolean'
15typeof NaN // 'number'
16
typeof console results

So, we can see that there is a way to tell types in JavaScript but we still need to know what they all are. The types we have seen are all of those available for the typeof operator as of the writing of this article. To get more in depth, or check if anything new has appeared, you may check the MDN Web Docs.

String Returned By typeofDescription
bigintUsed for integer (non-decimal) numbers outside of the safe value for number type
booleanUsed to store a true or false value
functionUsed for a chunk of code that may be called from another
numberUsed to store and do mathematical calculations on real numbers
objectUsed to represent a collection of other types all attached to one, or the primitive null
stringUsed for text or character values, created through using quotes or backticks
symbolUsed to create a unique value for identification
undefinedUsed for variables that do not have a value yet, or the primitive undefined

The word primitive was used a few times in that table. In a language, primitive types represent the most basic types that the language has at its core, which compose all of the other types.

JavaScript Primitive Types

Below is a list of primitive types. You will notice there is one type that was not returned by typeof, though it has been given a definition here.

  • BigInt
  • Boolean
  • Null: Represents a purposeful value of nothing, uses the keyword "null"
  • Number
  • String
  • Symbol
  • Undefined

JavaScript Object

As mentioned earlier, an Object is a collection of other types. A standard JavaScript object is composed of properties, which are simply key named values accessible through using object.propertyKey. Functions and arrays ([]) are special objects that we will go into greater detail in a bit.

You may have noticed in the typeof calls earlier that a few gave the String 'object' that were not null. If, in the console, you want to look at these objects closer you may simply type them in. For our example code, we have had the console.log line there the whole time so let us try typing in console. You may additionally try window to see a large object that exists as part of the browser.

If you click the little arrow, you may expand these objects and see that they are made up of more objects, functions (blue f), and primitives.

Console and Window Objects expanded

JavaScript Function

A JavaScript function is a special object that may be called (executed) by other code, including code within itself. Functions have the ability to receive arguments, which affect what the result of the function is. For details on the types of functions that exist, you may again see the MDN Documents. In our sample JavaScript code, we are calling a function assigned to the the console object's log property with the argument 'abc'. A function may have any number of comma separated arguments, and it is good to check what the order they are received does. In the case of this function, we can call with as many arguments as we want, and it will print them all out on the Console tab. Try it with console.log('abc', 123, undefined) and see the results.

When we create a function it is usually to help keep from copying and pasting code, so that we can reduce the overall amount of coding. For instance, let us just make a sample function in the console.

1function addTwo (first, second) {
2  return first + second
3}
4

This function will add the two arguments together, you can try it and see the results in the console. Since JavaScript is untyped, you may try calling it with things other than numbers if you would like, and see what happens. You will notice the keyword return as part of this function, which is what causes something to actually come back from the function. If you were to refresh the page and paste again without the word you will notice that the console gives forth 'undefined'.

JavaScript Arrays

Earlier, we saw that the typeof [] is object. However, this is again a special type of object known as an Array. Standard JavaScript objects are made up of a specific set of property names, but an array has the default property names as integers starting at zero and going up. If you put into the console [1,2,3,'a','b','c'] you may expand it and see this more visually illustrated. Also, if you were to expand the [[Prototype]] you may see some properties to try if you wish, though we will be introducing them later.

JavaScript Array in Console

Since this is a special type of object we can check if an object is one through the Array.isArray function. Additionally, Arrays have the advantage of being iterable so that we can easily perform the same action using all of the pieces within.

JavaScript Operators

Earlier in this lesson typeof was referred to as an operator. An operator is a core part of the language, and is used to perform an action on some values. In the below table, you will see some commonly used operators along with sample code to paste into the console, however for a more in depth view and complete list please check the MDN Docs.

Operator SymbolWhat it doesSample
+Adds two variables or constants together, according to JavaScript Type rule1 + 2
-Subtracts the right number from the left2 - 1
=Assigns the value on the right hand side to the variable on left hand sidelet x = 1 + 2; x
/Divides the left number by the right63 / 3
%Gives integer remaining after division of left number by the right62 % 3
**Multiplies number on left by itself number of times on the right (left to the power of right)2 ** 6
*Multiplies the numbers together3 * 5
&&Checks if both sides are true and returns true of so, else false(true && 1 == 1)
||Checks if either side is true and returns true if so, else false(false && true)
!Returns true if value is not JavaScript truthy, else false!false
==Checks if the two sides are JavaScript equal even across types and returns true if so, else false'' == false
===Checks if the two sides are the same type and equal and returns true if so, else false'' === false
!=Checks if the sides are not JavaScript equal across types and returns true of so, else false'' != false
!==Checks if two sides are not the same type or not equal and returns true if so, else false'' !== false
>Checks if left side is greater than right side and returns true if so, else false5 > 3
>=Checks if left side is greater than or equal to right side and returns true if so, else false5 >= 5
<Checks if the left side is less than right side and returns true if so, else false5 < 3
<=Checks if the left side is less than or equal to the right side and returns true if so, else false5 <= 5

Quick note on JavaScript Object Equality, truthy and falsy

JavaScript objects are only ever considered equal if they are the same exact object, not the same value object. We will get into this more later, but objects can have values on them change without changing the actual object. In addition, JavaScript has the concept of truthy and falsy when doing evaluations, which is why '' == false returns true and is also part of why most of the code we use in the projects will utilize === over ==.

JavaScript Case Sensitivity

JavaScript is a case sensitive language. You may see this illustrated below.

1console.log('abc') // the console prints abc
2Console.log('abc') // there is an error printed to the console 'Console is not defined'
3

JavaScript Variables

In JavaScript we store values in something called a variable. This is a named identifier that must start with a letter, underscore (_) or dollar sign ($) and may be followed by these same characters in addition to digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). Variables names must not be the same as existing keywords, and may be declared in a variety of fashions.

1// old style variable declaration, the keyword 'var'
2var myFirstVariable = 1
3// variables declared with var can have their values updated
4myFirstVariable = 'abc'
5
6// new style
7// using the keyword 'let' to be able to change the variable value later
8let mySecondVariable = 2
9mySecondVariable = 'def'
10
11// using the keyword 'const' keeps the variable value from being able to change later
12const myConstant = 3
13myConstant = 'abc' // throws an error
14
15// declaring an object with const creates an object whose value is a reference
16const myConstantObject = { a: 1, b: 2 }
17// which means that the properties are able to be changed, as the reference has not changed
18myConstantObject.b = 3
19
20// this function shows giving variable names for the arguments as well as the function name
21function testFunction (argumentVariable1, argumentVariable2) {
22  // function itself does nothing
23}
24

JavaScript Scope

Now, you may be wondering why I mentioned var as an old way to do variable declaration when it is still valid. This is because many standard linting rules no longer use it because of something called scope and the ease of making avoidable mistakes. Scope defines where the variable exists and is accessible at any given time. In our sample code, we have the variables clickedTimes, onButtonClick, and buttons that we used in the typeof illustrations earlier you will notice that typeof buttons was 'undefined'. In addition, if you looked at the window object in the console, you may have noticed that it contained our onButtonClick but not the clickedTimes.

This was because of the scoping, if you were to change the word from 'let' to 'var' to declare clickedTimes, it would attach itself to the window object as well. This is because there used to only be the concept of global scope and functional scope. When using only the 'var' keyword in my past programming, we had to do several tricks to make sure to not have unexpected clashes when having multiple files. For the 'var' keyword, it will either be attached globally, or only used inside of the function that it is declared in and there will be no indication that something may be behaving other than expected.

For 'const' and 'let' keywords, they use what is known as block scope. Block scope means that the variable is accessible at the levels that they are declared and deeper, or inside of their block. Blocks in JavaScript are the parts between curly brackets { and }.

While using the debugger in future lessons, the scope will become more visible as we learn how to watch variables. If you would like to learn more now check out the W3 Schools Page.

Conclusion

In this lesson we have learned a lot of terminology to help with the rest of the series. While we have not covered everything available, there should be enough to go over the code we have with the ability to explain it and also add some more knowledge as needed.

Next - Web Page Interactive Button Code Investigation Continued

Prior - Web Button Code Investigation Start

Tags: Practical Programming, JavaScript, Basics

©Michael Adsit Technologies, LLC. 2012-2024