JavaScript Notes
JavaScript Notes
Primitives
Let firstName = undefined; //uncommon to use undef. The type of this is also undef
Let lastName = null; // used to clear the value. The type of null is object
//Cannot be reserved keyword (let, if else var etc). You’re going to get an error if its reserved
This is allowed but modern conventions like one name per var.
Remember block is like a block of code, if you have a for loop like so, the i is only declared within that for loop, it doesn’t exist outside of it.
For Block scope, the Example class is the largest parent, and its children (processArray and for loop) can access its variables. Example class can’t access the children’s
variables
In ES5, scope is based on functions, so if you declare a variable inside a fxn, you can use it anywhere. So you could use that i outside too
You also have the global scope so each time you declare a var outside a fxn, belongs to the global scope
Scope reasons. Most programs have block scope. If you have function scope then two for loops end up using the same i and overwriting the first for loop. The function
Unlike var, when you use let, a variable with the same name can only be declared once.
Ex. You want to keep GST 5% and don’t want people to accidentally change it.
Const GST = 5%
Const S = [5,6,7]
S = [1,2,3] error
Dynamic Typing
JS is a dynamic language. What does that mean?
Static = once you declare a variable, the type of that variable never changes
Objects
//Bracket notation
Person[selection] = ‘Mary’;
Functions
A param is what we have at the time of declaration but the argument is the value that is actually supplied.
Uninitialized variables
They will be undefined. If you concat a string with an undefined, the whole thing will be undefined.
Immutable Strings
In JS, strings value are immutable; they can’t be altered once created.
myStr[0] = “J”;
Instead, you just assigned it with a whole new value, like this
myStr= “Job”;
Variables outside of a function block have Global scope. They can be seen everywhere in your JS code. Variables declared without const or let are automatically
created in the global scope which can be bad elsewhere. Always declare with let or const.
Variables declared within a function, as well as the function params, have local scope. That means they are only visible within that function.
If you have global and local variables with the same name, the local takes precedence over the global one (not advised to have same name variables however)
Ex. This fxn addFive doesn’t return anything, its returned value is undefined.
addFive(){
Sum += 5;
Strict Equality
Unlike the equality operator, which attempts to convert both values being compared to a common type, strict equality just compares it as it is. If they have different