Javascript Bootcamp | Basics | Part 4–9
Mastering the Basics
Intro
Hello! I did not abandon the seriousness, I was just simply busy with work. I recorded the videos already and will upload them to YouTube. I tried to be thorough for you to understand these concepts. They are challenging for new programmers, but soon enough you will be kicking up and taking names (in js) haha.
05 JS Statements
In javascript, the applications are comprised of statements. Statements may extend beyond one line and or many statements may be contained in a single line. Statements are often syntactically separated by semicolons ; [1].
Declarations
Declarations were talked bout in the earlier portion of this section. They represent the method for, you guessed it, declaring variables. Here are the ways you can declare variables. Up until now, we have only encountered the var option. Let's explore the differences.
- let: let allows you to declare a variable within a block scope.
- var: var allows you to declare a variable globally.
- const: const is a read-only variable, aka its constant and immutable.
const num = 5 // it will return a 5let num = 5 // it will return a 5var num = 5 // it will return a 5
Now let's see how they operate in relevance to block scope. Since var is global in a sense, the variable can be manipulated from different areas of the scope while let is scope specific. Here is an example
function varExample() {
var num = 5;
{
var num = 2; // same variable!
console.log(num); // 2
}
console.log(num); // 2
}
function letExample() {
let num = 5;
{
let num = 2; // different variable
console.log(num); // 2
}
console.log(num); // 5
}
Notice how the var variable was changed when reassigned inside the nested scope of the varExample function whereas the let was NOT reassigned in the letExample function?
Similarly, there are dead zones when parsing code. I believe this is bad practice but it may be important to understand the distinction [2].
function deadZone() {
console.log(varExample) // undefined
console.log(letExample) // Reference Error
var varExample = 5
let letExample = 4}
var is automatically assigned undefined whereas let needs to be initialized prior to accessing the variable. A good practice is to initialize and declare variables prior to being called, regardless.
Functions
Functions are objects that return a value. values can range from primitive types, other objects like object literals, or even functions. There are different elements of a function and different types of functions. We will talk about those nuances in greater detail soon. For now, let's familiarize ourselves with the basics and terms.
- function: This is your normal function object. The function is declared and assigned to a variable or constructed anonymously. like other functions, this can take in parameters, if previously defined. Here are various ways to write functions [3].
function funName() {} // function named funName. to initiate we use funName(). Can take in arguments.(function() {} ()) // anon function automatically initated after the {} with the (). Can take in arguments. const anon = function() {} //anon function assigned to the constant variable anon. Can take in arguments. initiated by anon()
You wanna be a cool cat and kitten-like Carol Baskin? You can use es6 syntax for declaring functions [4].
const anon = () => {} // naming and anon function(() => {} ) // anon funciton. You will see me use this often in the future.
Do NOT get overwhelmed. This tripped me up a lot when I moved to JS but all these ways to write a function mean (and do) the same thing. I just wanted to expose you to the different ways of writing these functions so that when you encounter it in real life or while I'm coding on the screen you are not confused. They look a little different but ultimately perform the same tasks.
There are slight differences in es6 syntax functions when using the this keyword, but we will explore those differences later. For now, get acquainted with these forms of functions.
- function*: Like the normal function the generator allows for a unique stop and go execution. I will just quickly point out that there is a distinction between generator functions and regular functions for now. We will explore generators in greater detail later.
- async function: Like a regular function that runs code synchronously (ie. parsing and running in time from top to bottom executing in chronological order). Async functions allow you to execute functions that are not synchronous (hence the async keyword). What this allows you to do is use an await keyword in functions withing the async function scope to parse once the await function has been successfully resolved. We will explore this in greater detail later.
- class: Classes are glorified functions that can not only be refused like a function but also enhanced by using things like inheritance and prototypes. Classes also use this keyword and in react have lifecycle methods inherent in the prototypes as well. When we created a string using the parent object we were actually using a class same with the Date and Math object.
class name [extends otherName] {
// class body
}
Classes can extend other existing classes which allows you to inherit the extended class attributes and methods. We will explore the practical use case of classes in greater detail later but I wanted to show you that if you see a class object it acts similar to a regular function with extra superpowers [5].
- return: Return is found in all iterations of the functions objects. The return keyword stops the function at that point and returns a specified expression (value) or undefined [6].
In code, if the function is a simple one-liner the return keyword is not needed
const addNums = (a,b) => a+bconst sum = addNums(5,10)console.log(sum) // return 15
Otherwise, it would look something like this:
function counter() {
for (var count = 1; ; count++) { // infinite loop
console.log(count + 'A'); // until 5
if (count === 5) {
return;
}
console.log(count + 'B'); // until 4
}
console.log(count + 'C'); // never appears
}
counter();// [6]
return is used often in js so we will encounter this many times in the future.
Iterations
Iterations allow you to, well, iterate multiple objects. The iteration of objects is most commonly performed with arrays. arrays contain multiple elements and in a list of elements (arrays), we can perform a tasks on each element within the list itself.
- for: for loops allow the user to iterate through an array or perform repetitious tasks while the conditions in the for loop are satisfied.
for (i = 5, i > 0, i--) {
console.log(i)
}
// returns:
// 5
// 4
// 3
// 2
// 1
- do ... while: similar to a for loop, the do while loop continues to perform a task while the conditions are true and performs the tasks at least once or until a false value is evaluated in the condition.
do
statement
while (condition);
There are other versions of for and do loops check those out here. I wanted to show you what happens behind the scenes when the code is parsed because I would like to introduce more elegant iterators in the near future such as nameArray.forEach() and nameArray.map().
Control Flow
Lastly is the control flow. We control the flow of the code using these statements and logic. We will quickly highlight some of the control flow statements that are relevant for you to know for the upcoming courses, otherwise, the more “advanced” control flow statements will be further explained in the following sections.
- if … else: This is the most commonly used control flow statement (imo) and the easiest to comprehend how control flow works. If conditions are met then execute the code otherwise (else) execute something else.
if (condition) {
// condition met} else {
// condition not met}
There is also an else if statement.
if (conditionA) {
// condition A met} else if (conditionB) {
// condition B met} else {
// catch all}
- switch: Switches will be used in the more advanced section but essentially a function is fed an argument and based on that argument if the condition is satisfied an action or statement is dispatched and executed. Do not worry about this TOO much right now since we will cover in greater detail later.
- continue: inside a loop you can use continue to break the loop at that specific point and continue with a new iteration.
- break: break, well you guessed it, breaks the loop entirely stopping it at the instance it is read. Good to use initially to prevent infinite loops
- block: is a grouping tool used to group zero or more statements together. this is not a keyword used as much as a keyword to represent the use case of curly braces { // statement(s) or Empty}
Other Statements
There are loads more of other statements. The ones I listed out are the most used IMO and most necessary to learn for now. We will cover the remaining statements in greater detail later but for now, understand and master the ones listed above.
For a full list of statements go here.
Wrap Up
Declarations allow us to assign variables, and let differs from var in that let is specific to a local scope. Yet both let and var are immutable as opposed to const.
Functions come in various forms but perform the same tasks.
Iterations allow the user to iterate through multiple elements of an array or perform a string of repetitious tasks while a condition is met. Iterations are most often used in the form of for loops and do … while loops.
Control flow allow the coder to control the flow of code parse by using logic such as if, else, and else if and statements like break and continue.