Bootcamp Notes – Day 8 (Wed) – Bootstrap: JavaScript Fundamentals

JavaScript Fundamentals

 

JavaScript Basics – Overview

The following courses in the bootcamp, React, React Native, and the Back End, will require heavy use of JavaScript. We will be covering what is called plain JavaScript, which you might also hear called “vanilla JavaScript”. The uninitiated, when they hear that, might wonder if it’s referring to a JavaScript library called vanilla.js. It’s actually the opposite – it’s just the plain, native JavaScript programming language itself, without using any libraries at all. JavaScript is an implementation of a specification called ECMAScript, named for the international standards organization ECMA International which maintains this specification.

The Developer Console

All major browsers have a version of the JavaScript developer console, which has two main uses:

  1. Test out small pieces of code
  2. Interact with scripts on the current webpage
  • To open the DevTools to the last tab you had open (whether that’s the Console tab or a different tab):
    • Windows: F12 or Ctrl+Shift+I
    • MacOS: Cmd+Option+I
  • To open the DevTools Console tab directly, regardless of the last tab you had open:
    • Windows – Chrome: Ctrl+Shift+J 
    • Windows – Firefox: Ctrl+Shift+K
    • MacOS – Chrome: Cmd+Option+J 
    • MacOS – Firefox: Cmd+Option+K

The JavaScript developers console lets you test out small pieces of JavaScript and immediately see the results. It is known technically as a REPL (Read Evaluate Print Loop). It will read your JavaScript, immediately evaluate it, then print out the return value of what you entered. Example below:

Interact with loaded scripts in the console

Clear the Developer Console

  • You can clear all the text in the developer console by typing clear(), or you can click the circle with the line through it at the top.
  • The keyboard shortcut for Windows is Ctrl+L, and it’s Option+L for MacOS.

Refresh the Developer Console

  • By refreshing the webpage, you can not only clear everything you entered into the console so far, you also release any functions or variable declarations from memory.

Data Types, Variables, Grammar

The latest ECMAScript standard has defined eight different data types for JavaScript. We will cover these four: NumberStringBoolean, and Undefined. These four will be used the most

    • Number
    • String
    • Boolean
    • Undefined
    • Null
    • Object
    • Symbol
    • BigInt

Number – Can be an integer or have decimal points: 3 or 3.14. Can be positive or negative: 1 or -1

String – Literal, textual data – will always have single or double quotes around it. Example: “Happy Birthday” or ‘Happy Birthday’

Boolean – Is either true or false in value.

Undefined – A place in memory that has not been assigned a value. Example: a variable that has been declared but not initialized

 

Variables

The data types above can be used for either variables or literals.

Literals are what they are; they do not change – they are hard coded. Examples: 3 is a literal number.  “wintercamp” is a literal string.

A variable is a location in the computer’s memory where information can be stored and accessed by an identifier, usually a variable name. The information stored in this way can be changed by the code.

Now let’s talk about some of the basic ways to use variables: declaration, assignment and initialization

To declare a variable means that you are setting a site location in memory. Declare all variables once prior to use, at the top of their scope. Use var/let/const to create and name a variable, e.g: let houseType;

When you assign a value to a variable you are initializing the variable.

So this (  let sky = ‘blue’;  ) declared and initialized the variable at the same time.

Declaration – Declare all variables once prior to use, at the top of their scope use var/let/const to create and name a variable, e.g/:  let houseType;

Assignment – Assign a value to the variable using an assignment operator, usually =, e.g.: houseType = ‘wood’;

Initialization – The first time a variable is assigned a value, which can be done together with declaration, e.g.: let houseType = ‘wood’


Basic JavaScript Grammar

JavaScript is case-sensitive. Look at the example below and see how it will not work.

Now it works!

When you use single or double quotes, use matching pairs: “Dopey” or ‘Dopey’ is fine, but not “Dopey’ or ‘Dopey”

Also, indent you code logically with either tabs or spaces (2 or 4 spaces). Consistent indentation will make your code much more human readable.

Use semicolons at the end of a statement to show that it has clearly finished. A statement is a line of code that does something such as calling a function, assigning a value, returning a value.

You do not need semicolons after the ending curly brace at the end of a code block, such as for function, if, for and while/do code blocks. If you leave out a semicolon where one is needed, the JavaScript engine will automatically insert one for you (Automatic Semicolon Insertion).

Name JavaScript variables using camelCase – typical JavaScript standard where variable names look like myVariableName.

Give variables concise, yet still sensible and human-readable names.

Example:

  • GOOD: numPartyHats or nPartyHats
  • NOT GOOD: numberOfHatsForTheParty or nPyHs

Assignment and Arithmetic Operators

Let us look at this example:

i = 5

The = is an assignment operator. Next to the = sign are its operands the values or values on which it operates. There are many operators in JavaScript and in any programming language.

Note: The best way to learn to code is to do it yourself.

Arithmetic Operators + – * / ++ —

NAN is not a number. It is a special value to let you know when you have a value that should be a number but is not for some reason like you try to multiply two strings together like ‘a’ * ‘b’. But this one is a special case ‘a’ + ‘b’ and does not give NAN. It becomes a string concatenation operator rather than the addition operator.

Now… What happens if you try to add a string and a number? What happens if you try arithmetic operators with Boolean values (true and false)? See below or try yourself on a console within your browser.

  • ++ Increment Operator – Takes a single operand, no spaces between ++ and variable name: myNum++
  • Operand must be a variable containing a number. Will increment the value of the variable by 1
  • ——————————————————————————————————————————————————————–
  • — Decrement Operator – Takes a single operand, no spaces betweenand variable name: myNum–
  • Operand must be a variable containing a number. Will decrement the value of the variable by 1

An important note about: ++ — is they can be used by:

  • prefix: ++myNum
  • postfix: myNume++

Using prefix or postfix can make a big difference!

The increment & decrement operators ++ and actually change the value of the operand. Example: if you type x++, the value of x actually changes to x+1

However, the other arithmetic operators do not change the value of the operand. They simply return the value from the operation, but they do not actually change their operands.

For example:

You can use the simple assignment operator with other data types not just numbers. JavaScript is what’s called loosely typed meaning, that we can take a variable that’s storing one data type like a number then we assign that same variable to store a different data type like a string or a boolean or any other data type. Some other languages are strongly typed and you can’t just easily switch the data type of a variable like that.

+=   -=   *=   /=

Each take 2 operands – left operand must be a variable. Will each perform the arithmetic operation first, then assign the result to the left operand’s value.


JavaScript Comparison and Logical Operators

==   ===   !=   !==   >   <   >=   <=

All comparison operators return either true or false after evaluating their operands.

== Equality Operator

Is more relaxed about the data type comparing. Loose equality – the data types of its operands do not need to match.

=== Strict Equality Operator

Is more strict. The data types of its operands must match

Best practice is to always use strict equality unless there’s a good reason otherwise.

Now look below at our example. Even though zero is a number data type and false is a boolean data type it comes up as true using == but using === comes out false.

!= Inequality Operator – This is the loose not equal.

! is called the bang.

!== Strict Inequality Operator – This is the strict not equal.

>   <   >=   <=

These do not have strict or loose versions

>   <   >=   <=

You can also use these operators to compare strings. When you compare strings, it’s the letters that are compared starting with the first letter then moving left to right and the comparison is roughly alphabetical  with letters toward the end of the alphabet being higher than letters to the right. So in our example below, albatross is less then zebra.

Logical Operators

&&  ||  !

These are such basic yet powerful concepts.

&& Logical And

|| Logical Or

! Logical Not

All logical operators return either true or false.

 

! Logical Not – returns the opposite of the Boolean value of its operand. It only takes one operand.

All values can be converted to Boolean values!

There are 2 ways that a value’s data type can be converted:

Explicitly – type conversion (a.ka. casting)

You could for example explicitly convert a number to a string using the global function string. Often in JavaScript data types get automatically implicitly converted to a different type. This is called Type Coercion. For example: “1” === 1;  comparing a string to a number is that the JavaScript engine will secretly convert the string to a number before doing the operation. Also remember this “eek” + 5 , which shows as “eek5” , this is also Type Coercion.

Logical operators only work with Boolean values: true or false

The Logical Not ! operator will coerce the type of any non-boolean operand to true or false for evaluation.

  • If the Boolean value of an operand is true, then that operand is considered “truthy
  • If the Boolean value of an operand is false, then that operand is considered “falsy

Rules for determining whether a non-Boolean value would be converted to true or false/is truthy or falsy:

  • Any value that is 0, “”, undefined, null or Nan converts to false (is falsy)
  • All other values are converted to true (is truthy)

A shortcut way to get the Boolean value of any variable is to use double bangs. It converts to boolean then getting the opposite of the opposite. The longer way would be to use the Boolean function.

 

Logical And: &&

The && operator takes 2 operands and checks if both are truthy. Returns a truthy value if yes, a falsy value if no.

When you use a logical && , that means both operands have to be truthy.

The || OR operator on the other hand will check either of it’s operand’s boolean values are truthy. When you use the logical || or with operands that are not Booleans you will get back the first truthy value. If there are no truthy values then you get back the last falsy value.

You can chain logical || or && together as well.

 


Additional Resources: