Javascript Basics
Introduction to Javascript
- Javascript is mainly used to create:
- Websites
- Web applications
- Server-side applications using NodeJS
- Can be also used to create mobile applications, create programs for microcontrollers, or create smartwatch applications
- Javascript features are:
- high level - provides abstractions to lower level code
- Has garbage collection, provides abstracts and constructs such as classes that allow you to deal with powerful variables and objects
- dynamic - executes things at runtime such as:
- dynamic typing
- late binding
- reflection
- functional programming
- object runtime alteration
- closures
- dynamically typed - variables don't enforce types, can reassign values of different types
- loosely typed - no enforcing of types on a variable, but leads to issues with type safety and type checking
- interpreted - unlike C++ or Java, Javascript is interpreted meaning that it doesn't neeed to compile the code into machine code
- multi-paradigmed - Javascript does not enforce a certain programming style
- Unlike C which enforces an imperative style or Java which enforces an object-oriented style
- Javascript gives you the option to program in an object-oriented style using ES6 classes or a functional style with first-class functions
- high level - provides abstractions to lower level code
Javascript History
- First scripting language natively supported by web browsers that gives it an advantage
- Other languages need to be compiled into Javascript
- Javascript now has grown past just the client-side applications by being able to write server-side code as well as power databases, develop embedded applications, mobile apps, etc.
Javascript Syntax Intro
White Space
- Javascript doesn't care about the amount of spaces or line breaks
- Stick to a style and use linters such as Prettier
Case Sensitive
- Javascript is case sensitive
- "Something" is not the same as "something"
Literals
- The values that is written into the source code
- Can be things like numbers, strings, arrays, functions, objects, etc.
Identifiers
- Sequence of characters that are used to identify a variable, function, or object
- Characters include: letters, dollar sign, underscore, numbers
Comments
- Single line comments using "//"
- Ex.
// This is a comment function test() { //... } - Multi-line comments using "/* */"
- Ex.
/* This is a multi line comment */
Semicolons
- In Javascript, semicolons are necessary at the end of each line, but now Javascript intepreters are smart enough to add semi-colons on the end of each line
- Not necessary unlesss it must be absolutely specified
Values
- "hello" is a value and is of type "string"
- Values have a type such as "string" or "number" but each type has their own characteritics
- When needing to save a value, you create a variable and pass the reference of the value to the variable
- The variable has a name and the value is what is stored inside it so that you can later access the value through the variable name
Variables
- A variable is a reference to a value using a label
- This is done to reference it and use it later in a program
- 3 ways to declare a variable
- let
- const
- var
const
- "const" refers to a constant reference to a value
- This means that the value of the variable cannot change
- "const" doesn't mean constant meaning that the value cannot change
- It just means that it cannot be reassigned
- Objects that are referenced with const can have their internal values changed
let
- A way of declaring variable that allows for changing the value of the variable
- Better to use const if you know that the variable won't be reassigned since it leads to less code bugs
Types
- When assigning a value to a variable, you give it a "type"
- Since Javascript is loosely typed, the type of the variable can be reassigned to a host of another type
- 2 main types:
- Primitive types
- Numbers
- Strings
- Booleans
- Symbols
- null
- undefined
- Object types
- Anything that is not a primitive type
- Objects have special properties and methods that can be used to act on those properties
- Primitive types
Basic Expressions
- Expression is a single unit of Javascript code that the Javascript engine can evaluate and return a value
- Different types of basic expressions
- Primary - just one type or value
- Arithmetic - involving a variable and an operator and result in a number
- String - expressions that result in strings
- Logical - expressions that use logical operators and resolve into a boolean value
Operators
- Operators take in 1 - 3 operands to combine them in to a more complicated expression
- Examples of binary operators (2 operands)
- "=" - assignment
- "+" - addition
- Doubles as a string concatenator when dealing with strings
- "-" - subtraction
- "/" - division
- Dividing by 0 gives an "Infinity" value
- "%" - Remainder
- Remainder with 0 gives "NaN" (not a number)
- "*" - multiplication
- "**" - exponentation or power
Precedence Rules
- When there are multiple operators within one expression, there are precedence rules that come into play
- In this table is the operators with their precedence (higher the in the table means higher precedence)
| Operator | Description |
|---|---|
| */% | Multiplication/Division/Remainder |
| +- | Addition/Subtraction |
| = | Assignment |
- Operators that are on the same precedence level get executed sequentially from left to right
Comparison Operators
- These operators are used for comparing the values of 2 operands
- It always returns a boolean value
- 4 equality operators
- "===" - equal to and type is equal
- "!==" - not equal to and type is not equal
- "==" - equal to
- "!=" - not equal to
- 4 inequality operators
- ">" - greater than
- "<" - less than
- ">=" greater than or equal to
- "<=" less than or equal to
Conditionals
- Conditionals allow you to take one route or another depending on the result of an expression
- Conditional checks whether the result of the expression is true or false
- If number is passed, it is always true unless the number is 0
- If string is passed, it is always true unless it is the empty string ""
- After the conditional a statement must be added to execute
- Put inside things called "blocks" which are represented by the curly braces "{}"
- An "Else" statement can be added to the second part of the if statement for executing statements in the case that the conditional is false
Primitive Types
Numbers
- Numbers in Javascript represent any kind of Integer, Decimal, or hexadecimal
- Numbers can be positive, negative, or prefixed with "0x" to denote hexadecimal
- Javascript represents all numbers as "floats" meaning there will be problems with precision
- Ex. 0.1 * 0.1 = 0.0100000000000000000002
- Solution is to not store decimal numbers
- If a number has 2 decimals, multiply by 100 before storing
Exercises with Numbers
- In Javascript "number" is different than "Number" as the latter represents the object type of the number
- There are several Number properties that can be utilized
- Get max possible integer value "Number.MAX_SAFE_INTEGER"
- There are also additional Number object methods
- Can check if numbers are integers or finite
- Can parse strings into floats or integers
- When you create a new Number object, it has some instance methods that allow you to format the value
- Most of the methods such as .toFixed() or .toPrecision() round the internal value
- Access the primitive value using .valueOf()
Strings
- Strings in Javascript are just a sequence of characters
- Can be defined with
- Single quotes: ''
- Double quotes: ""
- Template literals (backtick) ``
- Can concatentate variables with strings or multiple strings with "+" operator
- Template literals allow for easy concatentation of strings and expressions
- Use
${somevariable or expression}syntax
- Use
Exercises with Strings
- Strings have a bunch of useful methods
- Each of the methods are case sensistive and do not immutable, meaning they don't mutate the original string
- Some useful methods are
- trim
- subString
- split
- repeat
- search
- Full list here
Booleans
- Booleans in Javascript represent "true" and "false"
- Useful for comparison values and controlling the flow of the program using conditionals
- There are "truthy" and "falsy" values which translate to true or false in a conditional
- The falsy values are:
- 0
- -0
- NaN
- undefined
- null
- ''
- Rest are truthy
- The falsy values are:
Null and Undefined
- Javascript reserves "null" and "undefined" as special types with only one value
- "null" represents the absence of a value
- "undefined" represents that a variable is not initialized and the value is absent
- In functions with no return value or unintialized parameter
Functions
Functions
- Functions in Javascript are a self-contined, block of code designed to be reused
- Functions can have any number of parameters and the parameters can be of any type
- Functions can return any value or for multiple values, use arrays or objects
- Functions can also return other functions
Arrow Functions
- Arrow functions are another way to declare functions
- Anonymous so they must be set to a variable
- Ex. ``` let something = () {
} ``` * Arrow functions allow for shorter syntax * Can have implicit return when only having one line and omitting curly braces * Don't need parenthesis if there is only one parameter being passed * Arrow functions are useful because it bind the "this" keyboard for the object in that object's scope
Nested Functions
- You can nest functions within the scope of another function
- Useful because it modularizes the code (if inner function is only useful to that outer function)
- Also, allows you to reuse names without having to worry about overwriting
- The nested function is within the outer function's scope
- Means it can only be called within the outer function, can't be called outside the outer function
- Can call a funciton before the definition due to something called Hoisting
Recursive Functions
- Recursive functions are when a function invokes itself within its block of statements
- Recursion is very useful because it unlocks being able to utilize techniques such as divide and conquer, graph traversal, and new approaches to solve problems
Ex. Factorial recursively ``` function factorial(n) { if (n == 1){ return 1 }
return n * factorial(n-1) } ```
In recursion the program stores each function call's information and context on the call stack
When the base case is reached and something returns, the returned value goes to the previous function call's context and that previous function call resumes execution where it left off
If the recursion doesn't end, the function calls will fill up the call stack and the maximum size is reached
Objects
Intro to Objects
- In JS any value that is not a primitive type is an object
- Can initialize an object as a "class" by having the "new" keyword before the function call
- Ex.
const myCar = new Car(params)
- Ex.
- Objects are always passed by reference