# JavaScript
ALSO SEE: [[HTML]]
file extension: `.js`
(use lowercase in file names)
- high-level
- different from "[[Java]]"
- a core for websites (97.8%)
- most popular programming language
| | |
|---|---|
|Level:|Beginner to Intermediate|
|Skills Needed:|HTML and CSS to define the content and layout of web pages|
|Platform:|Cross-platform (desktop, mobile, web)|
|Popularity Among Programmers:|The most popular programming language in the world|
|Benefits:|- Easy to learn and implement<br>- Used everywhere on the web<br>- Can run immediately within the client-side browser<br>- Reduces the demand on the website server|
|Downsides:|Can sometimes be interpreted differently by different browsers which makes it difficult to write cross-browser code.|
|Degree of Use:|Widely used; highly applicable|
|Annual Salary Projection:|$112,152|
[^1]
## Summary
| Code | Meaning | Link |
| ---------------- | ------------------------------------------------------------- | ------------------------------------------------ |
| `var` | declare a variable | [[#Variables]] |
| `let` | declare a block variable | [[#Variables]] |
| `const` | declare a block constant | [[#Variables]] |
| `if` | marks a block of statements to be executed on a condition | [[#`if` statements]] |
| `switch` | marks a block of statements to be executed in different cases | [[#`switch`]] |
| `for` | marks a block of statements to be executed in a loop | [[#`for`]] |
| `function` | declares a function | [[#Functions]] |
| `return` | exits a function | [[#Functions]] |
| `try` | implements error handling to a block of statements | [[#`try`]] |
| `// ` | comment (single line) | [[#Comment]] |
| `/* */` | comment (multiple lines) | [[#Comment]] |
| `getElementById` | change a section of HTML or CSS | [[#Change HTML or CSS using `getElementByID()`]] |
| `typeof` | returns the type of a variable | [[#Operators]] |
| `instanceof` | returns true if an object is an instance of an object type | [[#Operators]] |
![[#Built-in Methods]]
## Guides
[W3](https://www.w3schools.com/js/default.asp)
[How to Use the JavaScript Fetch API to Get Data](https://www.geeksforgeeks.org/how-to-use-the-javascript-fetch-api-to-get-data/)
#### Ideas
###### Scope
[W3 link](https://www.w3schools.com/js/js_scope.asp)
determines accessibility of [[JavaScript#Variables|variables]]
types:
- Block scope
- variables declared inside a `{ }` block cannot be accessed from outside the block, unless using `var`
- Function/Local scope
- variables declared inside a function cannot be used outside of that function
- created when function starts and deleted when function ends
- Global scope
- all scripts and functions on a web page can access it
- defining a variable that hasn't been declared automatically becomes Global (even if inside a function)
- unless in "[[#Strict Mode]]"
###### Hoisting
JavaScript's default behavior moves all declarations to the top of the current scope
when a [[#Variables|variable]] is declared after it has been used
only the declaration is hoisted, not the definition/initialization
```js
x = 5;
var x;
```
###### Strict Mode
[w3 link](https://www.w3schools.com/js/js_strict.asp)
```js
"use strict";
```
- cannot use undeclared variables
- can be declared inside a function to only apply to that function
- must be declared at the beginning of the script or function
- not allowed:
- deleting a variable or function
- writing to a read-only property or get-only property
- using `eval` or `arguments` as a variable
- using `with` statement
###### Data Types
[w3 link](https://www.w3schools.com/js/js_datatypes.asp)
String
Number
Bigint
Boolean
Undefined
- has no value
- can empty a variable by `variableA = undefined`
- empty strings `""` are NOT considered undefined
Null
Symbol
[[#Objects|Object]]
- written with `{ , , }`
- can contain built-in objects and user-defined objects
- some built-in object types:
- objects
- arrays
- dates
- maps
- sets
- intarrays
- floatarrays
- promises
note: can use `typeof` [[#Operators|operator]] to find the type of a JavaScript variable
###### Objects
[w3 link](https://www.w3schools.com/js/js_objects.asp)
[w3 complete object reference](https://www.w3schools.com/jsref/jsref_obj_object.asp)
type of [[#Data Types|data type]]
contains properties and methods/actions (methods are [[#Functions|functions]] stored as property values)
can access properties by:
```js
objectName.propertyName
//or
objectName["propertyName"]
```
can add a new property by simply giving the property a value
```js
person.nationality = "English";
```
delete property using `delete`
```js
delete person.age;
//or
delete person["age"];
```
Declaring:
defined the same way as other [[#Variables|variables]], just with many values
it is common practice to declare objects with `const` [read more on w3](https://www.w3schools.com/js/js_const.asp)
"object literal" example
```js
const car = {type:"Fiat", model:"500", color:"white"};
```
Can nest objects:
```js
myObj = {
name:"John",
age:30,
myCars: {
car1:"Ford",
car2:"BMW",
car3:"Fiat"
}
}
```
and access like
```js
myObj.myCars.car2;
//or
myObj["myCars"]["car2"];
//or more
```
inserting a method into an object, example (`this` refers to the `person` object)
```js
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
```
###### Built-in Methods
| Name | Description |
| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| [assign()](https://www.w3schools.com/jsref/jsref_object_assign.asp) | Copies properties from a source object to a target object |
| [constructor](https://www.w3schools.com/jsref/jsref_object_constructor.asp) | Returns the function that created an object's prototype |
| [create()](https://www.w3schools.com/jsref/jsref_object_create.asp) | Returns an object created from an existing object |
| [defineProperties()](https://www.w3schools.com/jsref/jsref_object_defineproperties.asp) | Adds or changes properties |
| [defineProperty()](https://www.w3schools.com/jsref/jsref_object_defineproperty.asp) | Adds or changes a property |
| [entries()](https://www.w3schools.com/jsref/jsref_object_entries.asp) | Returns an array of the key/value pairs of an object |
| [freeze()](https://www.w3schools.com/jsref/jsref_object_freeze.asp) | Prevents any changes to an object |
| [fromEntries()](https://www.w3schools.com/jsref/jsref_object_fromentries.asp) | Returns an object created from an iterable list of key/value pairs |
| [getOwnPropertyDescriptor()](https://www.w3schools.com/jsref/jsref_object_getownpropertydescriptor.asp) | Returns an array of the keys of an object |
| [getOwnPropertyDescriptors()](https://www.w3schools.com/jsref/jsref_object_getownpropertydescriptors.asp) | Returns an array of the keys of an object |
| [getOwnPropertyNames()](https://www.w3schools.com/jsref/jsref_object_getownpropertynames.asp) | Returns an array of the keys of an object |
| [groupBy()](https://www.w3schools.com/jsref/jsref_object_groupby.asp) | Groups object elements according to returned callback values |
| [isExtensible()](https://www.w3schools.com/jsref/jsref_object_isextensible.asp) | Returns true if an object is extensible |
| [isFrozen()](https://www.w3schools.com/jsref/jsref_object_isfrozen.asp) | Returns true if an object is frozen |
| [isSealed()](https://www.w3schools.com/jsref/jsref_object_issealed.asp) | Returns true if an object is sealed |
| [keys()](https://www.w3schools.com/jsref/jsref_object_keys.asp) | Returns an array of the keys of an object |
| [preventExtensions()](https://www.w3schools.com/jsref/jsref_object_preventextensions.asp) | Prevents adding new properties to an object |
| [prototype](https://www.w3schools.com/jsref/jsref_object_prototype.asp) | Let you to add properties and methods to JavaScript objects |
| [seal()](https://www.w3schools.com/jsref/jsref_object_seal.asp) | Prevents adding new or deleting existing object properties |
| [toString()](https://www.w3schools.com/jsref/jsref_object_tostring.asp) | Converts an object to a string and returns the result |
| [valueOf()](https://www.w3schools.com/jsref/jsref_object_valueof.asp) | Returns the primitive value of an object |
| [values()](https://www.w3schools.com/jsref/jsref_object_values.asp) | Returns an array of the property values of an object |
###### Loading JavaScript in HTML
[w3 link](https://www.w3schools.com/js/js_whereto.asp)
run JavaScript code
```js
document.getElementById("demo").innerHTML = "My First JavaScript"
```
```html
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
```
run a JavaScript File
- the script will behave as if it was located exactly where the `<script>` tag is located
```html
<script src="myscript.js"></script>
// or using file path
<script src="/js/myScript.js"></script>
```
run an external reference
```html
<script src="https://www.w3schools.com/js/myScript.js"></script>
```
>[!Note] Placing scripts at the bottom of the `<body>` element improves the display speed, because script interpretation slows down the display.
#### Code
###### Strings
can use either double or single quotes
```js
"John Doe"
'John Doe'
```
combine strings
```js
"John" + " " + "Doe"
```
###### Comment
```js
// this is a comment
/*
This is also a comment
*/
```
^834f72
###### Variables
objects and functions are considered variables in JavaScript
identifiers are case sensitive
also see: [[JavaScript#Scope|scope]]
```js
const PI = 3.1415;
```
`const` constant reference to a value
- must be defined in same line as declared
- a `const` array
- can change an element `cars[0] = "dif car"`
- can add an element
- a `const` object
- can change property
- can add a property
```js
let x = 2;
```
```js
var x = 2;
```
>[!warning]- Avoiding using these strings as variables
>`eval`
>`arguments`
>`implements`
>`interface`
>`let`
>`package`
>`private`
>`protected`
>`public`
>`static`
>`yield`
>
>[other reserved terms](https://www.w3schools.com/js/js_reserved.asp)
>[source](https://www.w3schools.com/js/js_strict.asp)
###### Functions
[w3 link](https://www.w3schools.com/js/js_functions.asp)
a block of code designed to perform a particular task
a block of JavaScript code that can be "called"(or "invoked")
Syntax:
```js
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
```
`return` stops the execution of the function and carries return value back to the caller
if function was called with `()` then returns the function result
```js
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius;
```
Example:
```js
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
```
Example: run JavaScript function when button is clicked (`<script>` can be placed before or after using in html)
```html
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
```
`return` exits a function
###### Output
[w3 link](https://www.w3schools.com/js/js_output.asp)
`innerHTML` into HTML element (typically used)
```html
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
```
`document.write()` replaces all HTML in a document (for testing)
```html
<script>
document.write(5 + 6);
</script>
```
`window.alert`
```html
<script>
window.alert(5 + 6);
</script>
//can skip the window keyword
<script>
alert(5 + 6);
</script>
```
`console.log()` for debugging
```html
<script>
console.log(5 + 6);
</script>
```
`window.print()` can print the page off the computer
###### `if` statements
block of statements to be executed on a condition
###### `switch`
block of statements to be executed in different cases
###### `for`
block of statements to be executed in a loop
###### `try`
implements error handling to a block of statements
###### Operators
[w3 link](https://www.w3schools.com/js/js_operators.asp)
###### Keyword `this`
[w3 link](https://www.w3schools.com/js/js_this.asp)
refers to an object - the object it refers to depends on how it was used
###### Change HTML or CSS using `getElementByID()`
[w3 link](https://www.w3schools.com/js/js_intro.asp)
#### Errors
```js
// Code did not run
```
- using a variable before it is declared by `const` (see [[#Hoisting]])
```js
ReferenceError
```
- using a variable before it is declared by `let` (see [[#Hoisting]])
#### Typical JavaScript Coding Convention
[see more on w3](https://www.w3schools.com/js/js_conventions.asp)
variable names:
- new word indicated by capital letter (`firstName` or `myArray`)
- global variables written in all uppercase
- constants (like PI) written in all uppercase
- cannot use hyphens `-`
indent using 2 spaces, not tab
end simple statements (object definition) with a semicolon, not complex statements (functions, loops, conditionals)
#### Cheat Sheet
![[cheat_sheet_javascript-2021.7.19.pdf]] [^2]
[^1]: https://www.simplilearn.com/best-programming-languages-start-learning-today-article
[^2]: https://opensource.com/downloads/javascript-cheat-sheet